Update ci branch name

This commit is contained in:
halx99 2021-12-31 11:00:35 +08:00
parent e726066595
commit 64d7b55366
1098 changed files with 46409 additions and 42237 deletions

42
.appveyor.yml Normal file
View File

@ -0,0 +1,42 @@
version: 1.0.{build}
skip_tags: true
skip_branch_with_pr: true
image:
- Visual Studio 2019
environment:
PYTHON: "C:\\Python27"
PYTHON_VERSION: "2.7.13"
PYTHON_ARCH: "32"
matrix:
- build_type: windows32_cmake_test
# - build_type: android_cpp_tests
# - build_type: android_lua_tests
# - build_type: android_cocos_new_test
# - build_type: android_cpp_empty_test
# - build_type: android_gen_libs
platform:
- x86
configuration:
- Release
before_build:
- ps: ./tools/appveyor-scripts/before-build.ps1
build_script:
- ps: ./tools/appveyor-scripts/build.ps1
branches:
except:
- v1
- v2
- v4-develop
- v3-doc
- v3.11_backup
- v35-for-tizen
clone_depth: 50
test: off

View File

@ -4,7 +4,7 @@ on:
push: push:
branches: branches:
- dev - dev
- main - release
paths: paths:
- cmake/**/* - cmake/**/*
- cocos/**/* - cocos/**/*
@ -16,9 +16,12 @@ on:
env: env:
# Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.)
GH_OS_NAME: linux TRAVIS_OS_NAME: linux
BUILD_TARGET: android BUILD_TARGET: android
# Simple let github action to build all (TODO: optimize in the future)
TRAVIS_PULL_REQUEST: true
BUILD_TYPE: Release BUILD_TYPE: Release
GITHUB_CI: true
PYENV_VERSION: 2.7.18 PYENV_VERSION: 2.7.18
jobs: jobs:
@ -48,8 +51,8 @@ jobs:
- name: Create Build Environment - name: Create Build Environment
# Some projects don't allow in-source building, so create a separate build directory # Some projects don't allow in-source building, so create a separate build directory
# We'll use this as our working directory for all # We'll use this as our working directory for all
run: tools/unix-ci/before-install.sh run: tools/travis-scripts/before-install.sh
- name: Build - name: Build
# Execute the build. You can specify a specific target with "--target <NAME>" # Execute the build. You can specify a specific target with "--target <NAME>"
run: tools/unix-ci/run-script.sh run: tools/travis-scripts/run-script.sh

View File

@ -7,7 +7,7 @@ on:
# actions run ID # actions run ID
description: 'Commit clang-format changes?' description: 'Commit clang-format changes?'
# Default value if no value is explicitly provided # Default value if no value is explicitly provided
default: 'false' default: false
# Input has to be provided for the workflow to run # Input has to be provided for the workflow to run
required: false required: false
@ -21,9 +21,9 @@ jobs:
- name: Run clang-format lint - name: Run clang-format lint
uses: DoozyX/clang-format-lint-action@v0.13 uses: DoozyX/clang-format-lint-action@v0.13
with: with:
source: './cocos ./extensions ./tests ./templates' source: './cocos ./extensions'
exclude: './thidrparty ./extensions/fairygui ./extensions/scripting/lua-bindings/auto ./extensions/spine ./tests/fairygui-tests' exclude: './thidrparty ./extensions/fairygui ./extensions/scripting/lua-bindings/auto ./extensions/spine'
extensions: 'h,cpp,c,mm' extensions: 'h,cpp,c'
clangFormatVersion: 13 clangFormatVersion: 13
inplace: True inplace: True
- name: Commit clang-format changes - name: Commit clang-format changes

View File

@ -1,36 +0,0 @@
name: genbindings
on:
push:
branches:
- dev
- main
paths:
- cocos/**/*
- extensions/**/*
- .github/workflows/genbindings-ci.yml
jobs:
build:
if: ${{ !startsWith(github.event.commits[0].message, 'Merge pull request') }}
# The CMake configure and build commands are platform agnostic and should work equally
# well on Windows or Mac. You can convert this to a matrix build if you need
# cross-platform coverage.
# See: https://docs.github.com/en/actions/configuring-and-managing-workflows/configuring-a-workflow#configuring-a-build-matrix
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
with:
submodules: 'recursive'
lfs: 'true'
- name: Setup Python
uses: actions/setup-python@v2
- uses: ilammy/msvc-dev-cmd@v1.9.0
with:
arch: ${{ env.BUILD_ARCH }}
- name: Build
run: tools\win-ci\genbindings.ps1

View File

@ -4,7 +4,7 @@ on:
push: push:
branches: branches:
- dev - dev
- main - release
paths: paths:
- cmake/**/* - cmake/**/*
- cocos/**/* - cocos/**/*
@ -16,9 +16,12 @@ on:
env: env:
# Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.)
GH_OS_NAME: osx TRAVIS_OS_NAME: osx
BUILD_TARGET: ios BUILD_TARGET: ios
# Simple let github action to build all (TODO: optimize in the future)
TRAVIS_PULL_REQUEST: true
BUILD_TYPE: Release BUILD_TYPE: Release
GITHUB_CI: true
jobs: jobs:
build: build:
@ -38,8 +41,8 @@ jobs:
- name: Create Build Environment - name: Create Build Environment
# Some projects don't allow in-source building, so create a separate build directory # Some projects don't allow in-source building, so create a separate build directory
# We'll use this as our working directory for all # We'll use this as our working directory for all
run: tools/unix-ci/before-install.sh run: tools/travis-scripts/before-install.sh
- name: Build - name: Build
# Execute the build. You can specify a specific target with "--target <NAME>" # Execute the build. You can specify a specific target with "--target <NAME>"
run: tools/unix-ci/run-script.sh run: tools/travis-scripts/run-script.sh

View File

@ -4,7 +4,7 @@ on:
push: push:
branches: branches:
- dev - dev
- main - release
paths: paths:
- cmake/**/* - cmake/**/*
- cocos/**/* - cocos/**/*
@ -16,10 +16,12 @@ on:
env: env:
# Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.)
GH_OS_NAME: linux TRAVIS_OS_NAME: linux
BUILD_TARGET: linux BUILD_TARGET: linux
# Simple let github action to build all (TODO: optimize in the future)
TRAVIS_PULL_REQUEST: true
BUILD_TYPE: Release BUILD_TYPE: Release
PYENV_VERSION: 2.7.18 GITHUB_CI: true
jobs: jobs:
build: build:
@ -39,8 +41,8 @@ jobs:
- name: Create Build Environment - name: Create Build Environment
# Some projects don't allow in-source building, so create a separate build directory # Some projects don't allow in-source building, so create a separate build directory
# We'll use this as our working directory for all subsequent commands # We'll use this as our working directory for all subsequent commands
run: tools/unix-ci/before-install.sh run: tools/travis-scripts/before-install.sh
- name: Build - name: Build
# Execute the build. You can specify a specific target with "--target <NAME>" # Execute the build. You can specify a specific target with "--target <NAME>"
run: tools/unix-ci/run-script.sh run: tools/travis-scripts/run-script.sh

View File

@ -4,7 +4,7 @@ on:
push: push:
branches: branches:
- dev - dev
- main - release
paths: paths:
- cmake/**/* - cmake/**/*
- cocos/**/* - cocos/**/*
@ -16,9 +16,12 @@ on:
env: env:
# Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.)
GH_OS_NAME: osx TRAVIS_OS_NAME: osx
BUILD_TARGET: osx BUILD_TARGET: osx
# Simple let github action to build all (TODO: optimize in the future)
TRAVIS_PULL_REQUEST: true
BUILD_TYPE: Release BUILD_TYPE: Release
GITHUB_CI: true
jobs: jobs:
build: build:
@ -38,8 +41,8 @@ jobs:
- name: Create Build Environment - name: Create Build Environment
# Some projects don't allow in-source building, so create a separate build directory # Some projects don't allow in-source building, so create a separate build directory
# We'll use this as our working directory for all # We'll use this as our working directory for all
run: tools/unix-ci/before-install.sh run: tools/travis-scripts/before-install.sh
- name: Build - name: Build
# Execute the build. You can specify a specific target with "--target <NAME>" # Execute the build. You can specify a specific target with "--target <NAME>"
run: tools/unix-ci/run-script.sh run: tools/travis-scripts/run-script.sh

View File

@ -8,7 +8,9 @@ on:
env: env:
# Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.)
BUILD_TYPE: Release BUILD_TYPE: Release
PYENV_VERSION: 2.7.18 # Simple let github action to build all (TODO: optimize in the future)
TRAVIS_PULL_REQUEST: true
GITHUB_CI: true
jobs: jobs:
build-windows: build-windows:
@ -29,13 +31,13 @@ jobs:
- name: Setup Python - name: Setup Python
uses: actions/setup-python@v2 uses: actions/setup-python@v2
- name: Build - name: Build
run: tools\win-ci\build.ps1 $env:BUILD_ARCH run: tools\windows-ci\build.ps1 $env:BUILD_ARCH
build-linux: build-linux:
name: build-linux name: build-linux
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: env:
GH_OS_NAME: linux TRAVIS_OS_NAME: linux
BUILD_TARGET: linux BUILD_TARGET: linux
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
@ -44,8 +46,8 @@ jobs:
lfs: 'true' lfs: 'true'
- name: Build - name: Build
run: | run: |
tools/unix-ci/before-install.sh tools/travis-scripts/before-install.sh
tools/unix-ci/run-script.sh tools/travis-scripts/run-script.sh
build-android: build-android:
name: build-android name: build-android
@ -57,8 +59,9 @@ jobs:
- arm64-v8a - arm64-v8a
- x86 - x86
env: env:
GH_OS_NAME: linux TRAVIS_OS_NAME: linux
BUILD_TARGET: android BUILD_TARGET: android
PYENV_VERSION: 2.7.18
BUILD_ARCH: ${{ matrix.arch }} BUILD_ARCH: ${{ matrix.arch }}
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
@ -67,14 +70,14 @@ jobs:
lfs: 'true' lfs: 'true'
- name: Build - name: Build
run: | run: |
tools/unix-ci/before-install.sh tools/travis-scripts/before-install.sh
tools/unix-ci/run-script.sh tools/travis-scripts/run-script.sh
build-osx: build-osx:
name: build-osx name: build-osx
runs-on: macos-latest runs-on: macos-latest
env: env:
GH_OS_NAME: osx TRAVIS_OS_NAME: osx
BUILD_TARGET: osx BUILD_TARGET: osx
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
@ -83,14 +86,14 @@ jobs:
lfs: 'true' lfs: 'true'
- name: Build - name: Build
run: | run: |
tools/unix-ci/before-install.sh tools/travis-scripts/before-install.sh
tools/unix-ci/run-script.sh tools/travis-scripts/run-script.sh
build-ios: build-ios:
name: build-ios name: build-ios
runs-on: macos-latest runs-on: macos-latest
env: env:
GH_OS_NAME: osx TRAVIS_OS_NAME: osx
BUILD_TARGET: ios BUILD_TARGET: ios
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
@ -99,5 +102,5 @@ jobs:
lfs: 'true' lfs: 'true'
- name: Build - name: Build
run: | run: |
tools/unix-ci/before-install.sh tools/travis-scripts/before-install.sh
tools/unix-ci/run-script.sh tools/travis-scripts/run-script.sh

View File

@ -4,7 +4,7 @@ on:
push: push:
branches: branches:
- dev - dev
- main - release
paths: paths:
- cmake/**/* - cmake/**/*
- cocos/**/* - cocos/**/*
@ -44,4 +44,4 @@ jobs:
arch: ${{ env.BUILD_ARCH }} arch: ${{ env.BUILD_ARCH }}
- name: Build - name: Build
run: tools\win-ci\build.ps1 $env:BUILD_ARCH run: tools\windows-ci\build.ps1 $env:BUILD_ARCH

View File

@ -1,9 +1,7 @@
# adxe # adxe
[![dev](https://img.shields.io/badge/v1.0.0-beta5-yellow.svg)](https://github.com/adxeproject/adxe/releases)
[![LICENSE](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/adxeproject/adxe/blob/master/LICENSE)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/1c5628dea478449ea0c6e1b0e30c3be9)](https://app.codacy.com/gh/adxeproject/adxe?utm_source=github.com&utm_medium=referral&utm_content=adxeproject/adxe&utm_campaign=Badge_Grade_Settings) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/1c5628dea478449ea0c6e1b0e30c3be9)](https://app.codacy.com/gh/adxeproject/adxe?utm_source=github.com&utm_medium=referral&utm_content=adxeproject/adxe&utm_campaign=Badge_Grade_Settings)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-blue.svg)](https://github.com/adxeproject/adxe/pulls) [![dev](https://img.shields.io/badge/v1.0.0-beta4-yellow.svg)](https://github.com/adxeproject/adxe/releases)
[![LICENSE](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/adxeproject/adxe/blob/master/LICENSE)
[![Windows Build Status](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml/badge.svg)](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml) [![Windows Build Status](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml/badge.svg)](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml)
[![Android Build Status](https://github.com/adxeproject/adxe/workflows/android/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aandroid) [![Android Build Status](https://github.com/adxeproject/adxe/workflows/android/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aandroid)
@ -11,7 +9,7 @@
[![Linux Build Status](https://github.com/adxeproject/adxe/workflows/linux/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Alinux) [![Linux Build Status](https://github.com/adxeproject/adxe/workflows/linux/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Alinux)
[![macOS Build Status](https://github.com/adxeproject/adxe/workflows/osx/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aosx) [![macOS Build Status](https://github.com/adxeproject/adxe/workflows/osx/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aosx)
**This is another more radical fork of *Cocos2d-x-4.0*, use OpenAL for all platforms, single texture multi GPU texture handler, C++ 17 and some more (see 'Highlight Features' for more info).** **This is another more radical fork of *Cocos2d-x-4.0*, use OpenAL for all platforms, single texture multi GPU texture handler, C++ 14/17 and some more (see 'Highlight Features' for more info).**
### View code with vscode online: ### View code with vscode online:
- [![github1s](https://img.shields.io/badge/github1s-green.svg)](https://github1s.com/adxeproject/adxe) - [![github1s](https://img.shields.io/badge/github1s-green.svg)](https://github1s.com/adxeproject/adxe)
@ -21,9 +19,10 @@
**[简体中文](README_CN.md)** **[简体中文](README_CN.md)**
### Purpose Summary ### Purpose Summary
* C++ 17 * C++ 14/17
* Focus on native game dev (quick starting, easy to use, fast) * Focus on native game dev (quick starting, easy to use, fast)
* Bugfixes ASAP * Bugfixes ASAP
* Usefull PRs from **you** are welcome (review/merge ASAP)
### Highlight Features ### Highlight Features
* Windows x64 build support * Windows x64 build support
@ -37,7 +36,7 @@
* Implement all .wav formats supported by ```OpenAL Soft```, such as MS-ADPCM, ADPCM, ... * Implement all .wav formats supported by ```OpenAL Soft```, such as MS-ADPCM, ADPCM, ...
* Use modern GL loader ```Glad``` * Use modern GL loader ```Glad```
* Google [angle](https://github.com/google/angle) renderer backend support * Google [angle](https://github.com/google/angle) renderer backend support
* C++ 17 standard * C++ 14 standard
* IOS SDK 9.0 as minimal deployment * IOS SDK 9.0 as minimal deployment
* Use fast pugixml * Use fast pugixml
* Use [curl](https://github.com/curl/curl) for transferring data with URL syntax * Use [curl](https://github.com/curl/curl) for transferring data with URL syntax
@ -137,7 +136,7 @@ https://github.com/adxeproject/adxe/discussions/411
- @aismann - @aismann
- @weiwest - @weiwest
### Fully changes since cocos2d-x-4.0 ### Fullly changes since cocos2d-x-4.0
- [HIGHLIGHT] Implement Windows WebView using WebView2 Edge Chromium, thanks to @rh101 - [HIGHLIGHT] Implement Windows WebView using WebView2 Edge Chromium, thanks to @rh101
- [HIGHLIGHT] Windows x64 build support - [HIGHLIGHT] Windows x64 build support

View File

@ -1,9 +1,8 @@
# adxe # adxe
[![dev](https://img.shields.io/badge/v1.0.0-beta5-yellow.svg)](https://github.com/adxeproject/adxe/releases)
[![LICENSE](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/adxeproject/adxe/blob/master/LICENSE)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/1c5628dea478449ea0c6e1b0e30c3be9)](https://app.codacy.com/gh/adxeproject/adxe?utm_source=github.com&utm_medium=referral&utm_content=adxeproject/adxe&utm_campaign=Badge_Grade_Settings) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/1c5628dea478449ea0c6e1b0e30c3be9)](https://app.codacy.com/gh/adxeproject/adxe?utm_source=github.com&utm_medium=referral&utm_content=adxeproject/adxe&utm_campaign=Badge_Grade_Settings)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-blue.svg)](https://github.com/adxeproject/adxe/pulls) [![dev](https://img.shields.io/badge/v1.0.0-beta4-yellow.svg)](https://github.com/adxeproject/adxe/releases)
[![LICENSE](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/adxeproject/adxe/blob/master/LICENSE)
[![Windows Build Status](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml/badge.svg)](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml) [![Windows Build Status](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml/badge.svg)](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml)
[![Android Build Status](https://github.com/adxeproject/adxe/workflows/android/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aandroid) [![Android Build Status](https://github.com/adxeproject/adxe/workflows/android/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aandroid)
@ -12,15 +11,16 @@
[![macOS Build Status](https://github.com/adxeproject/adxe/workflows/osx/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aosx) [![macOS Build Status](https://github.com/adxeproject/adxe/workflows/osx/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aosx)
**这是另外一个基于 *Cocos2d-x-4.0* 持续维护的分支, 全平台基于OpenAL, c++17...** **这是另外一个基于 *Cocos2d-x-4.0* 持续维护的分支, 全平台基于OpenAL, c++14/17...**
**[English](README.md)** **[English](README.md)**
### 宗旨: ### 宗旨:
* C++17 * C++14/17
* Focus on native game dev only * Focus on native game dev only
* Fix bugs ASAP * Fix bugs ASAP
* Review PR ASAP * Review PR ASAP
* Excellent PRs from any guys are welcome, we will review & merge ASAP
### 主要特性: ### 主要特性:
* Windows x64编译支持 * Windows x64编译支持
@ -33,7 +33,7 @@
* AudioEngine实现wav所有 ```openal-soft``` 支持的封装格式, 例如MS-ADPCM, ADPCM等 * AudioEngine实现wav所有 ```openal-soft``` 支持的封装格式, 例如MS-ADPCM, ADPCM等
* 使用现代化的GL加载器glad代替glew * 使用现代化的GL加载器glad代替glew
* 增加google angle渲染后端支持 * 增加google angle渲染后端支持
* C++最低标准要求: C++17 * 设置默认C++标准为C++14
* 设置ios下最低目标平台为ios9.0 * 设置ios下最低目标平台为ios9.0
* 使用更快的xml解析库pugixml代替tinyxml2 * 使用更快的xml解析库pugixml代替tinyxml2
* Downloader全平台统一实现均基于curl * Downloader全平台统一实现均基于curl

View File

@ -247,7 +247,7 @@ Vec2 ShuffleTiles::getDelta(const Vec2& pos) const
pos2.x = (float)(_tilesOrder[idx] / (int)_gridSize.height); pos2.x = (float)(_tilesOrder[idx] / (int)_gridSize.height);
pos2.y = (float)(_tilesOrder[idx] % (int)_gridSize.height); pos2.y = (float)(_tilesOrder[idx] % (int)_gridSize.height);
return Vec2(static_cast<float>((int)(pos2.x - pos.width)), static_cast<float>((int)(pos2.y - pos.height))); return Vec2((int)(pos2.x - pos.width), (int)(pos2.y - pos.height));
} }
void ShuffleTiles::placeTile(const Vec2& pos, Tile* t) void ShuffleTiles::placeTile(const Vec2& pos, Tile* t)

View File

@ -29,7 +29,7 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
ActionTween* ActionTween::create(float duration, std::string_view key, float from, float to) ActionTween* ActionTween::create(float duration, const std::string& key, float from, float to)
{ {
ActionTween* ret = new ActionTween(); ActionTween* ret = new ActionTween();
if (ret->initWithDuration(duration, key, from, to)) if (ret->initWithDuration(duration, key, from, to))
@ -42,7 +42,7 @@ ActionTween* ActionTween::create(float duration, std::string_view key, float fro
return nullptr; return nullptr;
} }
bool ActionTween::initWithDuration(float duration, std::string_view key, float from, float to) bool ActionTween::initWithDuration(float duration, const std::string& key, float from, float to)
{ {
if (ActionInterval::initWithDuration(duration)) if (ActionInterval::initWithDuration(duration))
{ {

View File

@ -59,7 +59,7 @@ public:
@param value The new value of the specified key. @param value The new value of the specified key.
@param key The key of property which should be updated. @param key The key of property which should be updated.
*/ */
virtual void updateTweenAction(float value, std::string_view key) = 0; virtual void updateTweenAction(float value, const std::string& key) = 0;
}; };
/** ActionTween /** ActionTween
@ -93,7 +93,7 @@ public:
* @param to The value of the specified property when the action end. * @param to The value of the specified property when the action end.
* @return If the creation success, return a pointer of ActionTween; otherwise, return nil. * @return If the creation success, return a pointer of ActionTween; otherwise, return nil.
*/ */
static ActionTween* create(float duration, std::string_view key, float from, float to); static ActionTween* create(float duration, const std::string& key, float from, float to);
// Overrides // Overrides
void startWithTarget(Node* target) override; void startWithTarget(Node* target) override;
@ -111,7 +111,7 @@ public:
* @return If the initialization success, return true; otherwise, return false. * @return If the initialization success, return true; otherwise, return false.
*/ */
bool bool
initWithDuration(float duration, std::string_view key, float from, float to); initWithDuration(float duration, const std::string& key, float from, float to);
protected: protected:
std::string _key; std::string _key;

View File

@ -165,7 +165,7 @@ void Animation::addSpriteFrame(SpriteFrame* spriteFrame)
_totalDelayUnits++; _totalDelayUnits++;
} }
void Animation::addSpriteFrameWithFile(std::string_view filename) void Animation::addSpriteFrameWithFile(const std::string& filename)
{ {
Texture2D* texture = Director::getInstance()->getTextureCache()->addImage(filename); Texture2D* texture = Director::getInstance()->getTextureCache()->addImage(filename);
Rect rect = Rect::ZERO; Rect rect = Rect::ZERO;

View File

@ -199,7 +199,7 @@ public:
* Added to facilitate the migration from v0.8 to v0.9. * Added to facilitate the migration from v0.8 to v0.9.
* @param filename The path of SpriteFrame. * @param filename The path of SpriteFrame.
*/ */
void addSpriteFrameWithFile(std::string_view filename); void addSpriteFrameWithFile(const std::string& filename);
/** Adds a frame with a texture and a rect. Internally it will create a SpriteFrame and it will add it. /** Adds a frame with a texture and a rect. Internally it will create a SpriteFrame and it will add it.
* The frame will be added with one "delay unit". * The frame will be added with one "delay unit".

View File

@ -63,12 +63,12 @@ AnimationCache::~AnimationCache()
CCLOGINFO("deallocing AnimationCache: %p", this); CCLOGINFO("deallocing AnimationCache: %p", this);
} }
void AnimationCache::addAnimation(Animation* animation, std::string_view name) void AnimationCache::addAnimation(Animation* animation, const std::string& name)
{ {
_animations.insert(std::string{name}, animation); _animations.insert(name, animation);
} }
void AnimationCache::removeAnimation(std::string_view name) void AnimationCache::removeAnimation(const std::string& name)
{ {
if (name.empty()) if (name.empty())
return; return;
@ -76,7 +76,7 @@ void AnimationCache::removeAnimation(std::string_view name)
_animations.erase(name); _animations.erase(name);
} }
Animation* AnimationCache::getAnimation(std::string_view name) Animation* AnimationCache::getAnimation(const std::string& name)
{ {
return _animations.at(name); return _animations.at(name);
} }
@ -205,7 +205,7 @@ void AnimationCache::parseVersion2(const ValueMap& animations)
} }
} }
void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary, std::string_view plist) void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary, const std::string& plist)
{ {
auto anisItr = dictionary.find("animations"); auto anisItr = dictionary.find("animations");
if (anisItr == dictionary.end()) if (anisItr == dictionary.end())
@ -245,7 +245,7 @@ void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary, std
} }
/** Read an NSDictionary from a plist file and parse it automatically for animations */ /** Read an NSDictionary from a plist file and parse it automatically for animations */
void AnimationCache::addAnimationsWithFile(std::string_view plist) void AnimationCache::addAnimationsWithFile(const std::string& plist)
{ {
CCASSERT(!plist.empty(), "Invalid texture file name"); CCASSERT(!plist.empty(), "Invalid texture file name");
if (plist.empty()) if (plist.empty())
@ -259,7 +259,7 @@ void AnimationCache::addAnimationsWithFile(std::string_view plist)
CCASSERT(!dict.empty(), "CCAnimationCache: File could not be found"); CCASSERT(!dict.empty(), "CCAnimationCache: File could not be found");
if (dict.empty()) if (dict.empty())
{ {
log("AnimationCache::addAnimationsWithFile error:%s not exist!", plist.data()); log("AnimationCache::addAnimationsWithFile error:%s not exist!", plist.c_str());
} }
addAnimationsWithDictionary(dict, plist); addAnimationsWithDictionary(dict, plist);

View File

@ -81,13 +81,13 @@ public:
* @param animation An animation. * @param animation An animation.
* @param name The name of animation. * @param name The name of animation.
*/ */
void addAnimation(Animation* animation, std::string_view name); void addAnimation(Animation* animation, const std::string& name);
/** Deletes a Animation from the cache. /** Deletes a Animation from the cache.
* *
* @param name The name of animation. * @param name The name of animation.
*/ */
void removeAnimation(std::string_view name); void removeAnimation(const std::string& name);
/** Returns a Animation that was previously added. /** Returns a Animation that was previously added.
* If the name is not found it will return nil. * If the name is not found it will return nil.
@ -95,7 +95,7 @@ public:
* *
* @return A Animation that was previously added. If the name is not found it will return nil. * @return A Animation that was previously added. If the name is not found it will return nil.
*/ */
Animation* getAnimation(std::string_view name); Animation* getAnimation(const std::string& name);
/** Adds an animation from an NSDictionary. /** Adds an animation from an NSDictionary.
* Make sure that the frames were previously loaded in the SpriteFrameCache. * Make sure that the frames were previously loaded in the SpriteFrameCache.
@ -104,7 +104,7 @@ public:
* @since v1.1 * @since v1.1
@js NA @js NA
*/ */
void addAnimationsWithDictionary(const ValueMap& dictionary, std::string_view plist); void addAnimationsWithDictionary(const ValueMap& dictionary, const std::string& plist);
/** Adds an animation from a plist file. /** Adds an animation from a plist file.
* Make sure that the frames were previously loaded in the SpriteFrameCache. * Make sure that the frames were previously loaded in the SpriteFrameCache.
@ -113,14 +113,14 @@ public:
* @lua addAnimations * @lua addAnimations
* @param plist An animation from a plist file. * @param plist An animation from a plist file.
*/ */
void addAnimationsWithFile(std::string_view plist); void addAnimationsWithFile(const std::string& plist);
private: private:
void parseVersion1(const ValueMap& animations); void parseVersion1(const ValueMap& animations);
void parseVersion2(const ValueMap& animations); void parseVersion2(const ValueMap& animations);
private: private:
StringMap<Animation*> _animations; Map<std::string, Animation*> _animations;
static AnimationCache* s_sharedAnimationCache; static AnimationCache* s_sharedAnimationCache;
}; };

View File

@ -47,7 +47,7 @@ AtlasNode::~AtlasNode()
CC_SAFE_RELEASE(_textureAtlas); CC_SAFE_RELEASE(_textureAtlas);
} }
AtlasNode* AtlasNode::create(std::string_view tile, int tileWidth, int tileHeight, int itemsToRender) AtlasNode* AtlasNode::create(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender)
{ {
AtlasNode* ret = new AtlasNode(); AtlasNode* ret = new AtlasNode();
if (ret->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender)) if (ret->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender))
@ -59,7 +59,7 @@ AtlasNode* AtlasNode::create(std::string_view tile, int tileWidth, int tileHeigh
return nullptr; return nullptr;
} }
bool AtlasNode::initWithTileFile(std::string_view tile, int tileWidth, int tileHeight, int itemsToRender) bool AtlasNode::initWithTileFile(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender)
{ {
CCASSERT(!tile.empty(), "file size should not be empty"); CCASSERT(!tile.empty(), "file size should not be empty");
Texture2D* texture = _director->getTextureCache()->addImage(tile); Texture2D* texture = _director->getTextureCache()->addImage(tile);
@ -222,7 +222,7 @@ void AtlasNode::setIgnoreContentScaleFactor(bool ignoreContentScaleFactor)
auto label = dynamic_cast<LabelProtocol*>(this); auto label = dynamic_cast<LabelProtocol*>(this);
if (label) if (label)
{ {
Vec2 s = Vec2(static_cast<float>(label->getString().size() * _itemWidth), static_cast<float>(_itemHeight)); Vec2 s = Vec2(label->getString().size() * _itemWidth, _itemHeight);
this->setContentSize(s); this->setContentSize(s);
} }
} }

View File

@ -57,7 +57,7 @@ public:
* @param tileHeight The height of the item. * @param tileHeight The height of the item.
* @param itemsToRender The quantity of items to render. * @param itemsToRender The quantity of items to render.
*/ */
static AtlasNode* create(std::string_view filename, int tileWidth, int tileHeight, int itemsToRender); static AtlasNode* create(const std::string& filename, int tileWidth, int tileHeight, int itemsToRender);
/** updates the Atlas (indexed vertex array). /** updates the Atlas (indexed vertex array).
* Shall be overridden in subclasses. * Shall be overridden in subclasses.
@ -106,7 +106,7 @@ public:
/** Initializes an AtlasNode with an Atlas file the width and height of each item and the quantity of items to /** Initializes an AtlasNode with an Atlas file the width and height of each item and the quantity of items to
* render*/ * render*/
bool initWithTileFile(std::string_view tile, int tileWidth, int tileHeight, int itemsToRender); bool initWithTileFile(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender);
/** Initializes an AtlasNode with a texture the width and height of each item measured in points and the quantity /** Initializes an AtlasNode with a texture the width and height of each item measured in points and the quantity
* of items to render*/ * of items to render*/

View File

@ -168,7 +168,7 @@ float PolygonInfo::getArea() const
return area; return area;
} }
AutoPolygon::AutoPolygon(std::string_view filename) AutoPolygon::AutoPolygon(const std::string& filename)
: _image(nullptr), _data(nullptr), _filename(""), _width(0), _height(0), _scaleFactor(0) : _image(nullptr), _data(nullptr), _filename(""), _width(0), _height(0), _scaleFactor(0)
{ {
_filename = filename; _filename = filename;
@ -714,7 +714,7 @@ PolygonInfo AutoPolygon::generateTriangles(const Rect& rect, float epsilon, floa
return ret; return ret;
} }
PolygonInfo AutoPolygon::generatePolygon(std::string_view filename, const Rect& rect, float epsilon, float threshold) PolygonInfo AutoPolygon::generatePolygon(const std::string& filename, const Rect& rect, float epsilon, float threshold)
{ {
AutoPolygon ap(filename); AutoPolygon ap(filename);
return ap.generateTriangles(rect, epsilon, threshold); return ap.generateTriangles(rect, epsilon, threshold);

View File

@ -117,8 +117,8 @@ public:
const Rect& getRect() const { return _rect; } const Rect& getRect() const { return _rect; }
void setRect(const Rect& rect) { _rect = rect; } void setRect(const Rect& rect) { _rect = rect; }
std::string_view getFilename() const { return _filename; } const std::string& getFilename() const { return _filename; }
void setFilename(std::string_view filename) { _filename = filename; } void setFilename(const std::string& filename) { _filename = filename; }
// FIXME: this should be a property, not a public ivar // FIXME: this should be a property, not a public ivar
TrianglesCommand::Triangles triangles; TrianglesCommand::Triangles triangles;
@ -147,7 +147,7 @@ public:
* @param filename a path to image file, e.g., "scene1/monster.png". * @param filename a path to image file, e.g., "scene1/monster.png".
* @return an AutoPolygon object; * @return an AutoPolygon object;
*/ */
AutoPolygon(std::string_view filename); AutoPolygon(const std::string& filename);
/** /**
* Destructor of AutoPolygon. * Destructor of AutoPolygon.
@ -254,7 +254,7 @@ public:
* auto sp = Sprite::create(AutoPolygon::generatePolygon("grossini.png")); * auto sp = Sprite::create(AutoPolygon::generatePolygon("grossini.png"));
* @endcode * @endcode
*/ */
static PolygonInfo generatePolygon(std::string_view filename, static PolygonInfo generatePolygon(const std::string& filename,
const Rect& rect = Rect::ZERO, const Rect& rect = Rect::ZERO,
float epsilon = 2.0f, float epsilon = 2.0f,
float threshold = 0.05f); float threshold = 0.05f);

View File

@ -71,12 +71,12 @@ CameraBackgroundDepthBrush* CameraBackgroundBrush::createDepthBrush(float depth)
return CameraBackgroundDepthBrush::create(depth); return CameraBackgroundDepthBrush::create(depth);
} }
CameraBackgroundSkyBoxBrush* CameraBackgroundBrush::createSkyboxBrush(std::string_view positive_x, CameraBackgroundSkyBoxBrush* CameraBackgroundBrush::createSkyboxBrush(const std::string& positive_x,
std::string_view negative_x, const std::string& negative_x,
std::string_view positive_y, const std::string& positive_y,
std::string_view negative_y, const std::string& negative_y,
std::string_view positive_z, const std::string& positive_z,
std::string_view negative_z) const std::string& negative_z)
{ {
return CameraBackgroundSkyBoxBrush::create(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z); return CameraBackgroundSkyBoxBrush::create(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z);
} }
@ -303,12 +303,12 @@ CameraBackgroundSkyBoxBrush::~CameraBackgroundSkyBoxBrush()
#endif #endif
} }
CameraBackgroundSkyBoxBrush* CameraBackgroundSkyBoxBrush::create(std::string_view positive_x, CameraBackgroundSkyBoxBrush* CameraBackgroundSkyBoxBrush::create(const std::string& positive_x,
std::string_view negative_x, const std::string& negative_x,
std::string_view positive_y, const std::string& positive_y,
std::string_view negative_y, const std::string& negative_y,
std::string_view positive_z, const std::string& positive_z,
std::string_view negative_z) const std::string& negative_z)
{ {
CameraBackgroundSkyBoxBrush* ret = nullptr; CameraBackgroundSkyBoxBrush* ret = nullptr;

View File

@ -105,12 +105,12 @@ public:
@param negative_z texture for the rear side of the texture cube face. @param negative_z texture for the rear side of the texture cube face.
@return A new brush inited with given parameters. @return A new brush inited with given parameters.
*/ */
static CameraBackgroundSkyBoxBrush* createSkyboxBrush(std::string_view positive_x, static CameraBackgroundSkyBoxBrush* createSkyboxBrush(const std::string& positive_x,
std::string_view negative_x, const std::string& negative_x,
std::string_view positive_y, const std::string& positive_y,
std::string_view negative_y, const std::string& negative_y,
std::string_view positive_z, const std::string& positive_z,
std::string_view negative_z); const std::string& negative_z);
/** /**
* draw the background * draw the background
*/ */
@ -253,12 +253,12 @@ public:
@param negative_z texture for the rear side of the texture cube face. @param negative_z texture for the rear side of the texture cube face.
@return A new brush inited with given parameters. @return A new brush inited with given parameters.
*/ */
static CameraBackgroundSkyBoxBrush* create(std::string_view positive_x, static CameraBackgroundSkyBoxBrush* create(const std::string& positive_x,
std::string_view negative_x, const std::string& negative_x,
std::string_view positive_y, const std::string& positive_y,
std::string_view negative_y, const std::string& negative_y,
std::string_view positive_z, const std::string& positive_z,
std::string_view negative_z); const std::string& negative_z);
/** Creates a Skybox brush with 6 textures. /** Creates a Skybox brush with 6 textures.
*/ */

View File

@ -60,8 +60,8 @@ public:
bool isEnabled() const { return _enabled; } bool isEnabled() const { return _enabled; }
virtual void setEnabled(bool enabled); virtual void setEnabled(bool enabled);
std::string_view getName() const { return _name; } const std::string& getName() const { return _name; }
virtual void setName(std::string_view name) { _name = name; } virtual void setName(const std::string& name) { _name = name; }
Node* getOwner() const { return _owner; } Node* getOwner() const { return _owner; }
virtual void setOwner(Node* owner); virtual void setOwner(Node* owner);

View File

@ -33,7 +33,7 @@ ComponentContainer::ComponentContainer(Node* node) : _owner(node) {}
ComponentContainer::~ComponentContainer() {} ComponentContainer::~ComponentContainer() {}
Component* ComponentContainer::get(std::string_view name) const Component* ComponentContainer::get(const std::string& name) const
{ {
Component* ret = nullptr; Component* ret = nullptr;
@ -60,7 +60,7 @@ bool ComponentContainer::add(Component* com)
CCASSERT(false, "ComponentContainer already have this kind of component"); CCASSERT(false, "ComponentContainer already have this kind of component");
break; break;
} }
hlookup::set_item(_componentMap, componentName, com); //_componentMap[componentName] = com; _componentMap[componentName] = com;
com->retain(); com->retain();
com->setOwner(_owner); com->setOwner(_owner);
com->onAdd(); com->onAdd();
@ -70,7 +70,7 @@ bool ComponentContainer::add(Component* com)
return ret; return ret;
} }
bool ComponentContainer::remove(std::string_view componentName) bool ComponentContainer::remove(const std::string& componentName)
{ {
bool ret = false; bool ret = false;
do do

View File

@ -54,10 +54,10 @@ public:
/** /**
* @js getComponent * @js getComponent
*/ */
Component* get(std::string_view name) const; Component* get(const std::string& name) const;
bool add(Component* com); bool add(Component* com);
bool remove(std::string_view name); bool remove(const std::string& name);
bool remove(Component* com); bool remove(Component* com);
void removeAll(); void removeAll();
void visit(float delta); void visit(float delta);
@ -68,7 +68,7 @@ public:
bool isEmpty() const { return _componentMap.empty(); } bool isEmpty() const { return _componentMap.empty(); }
private: private:
hlookup::string_map<Component*> _componentMap; std::unordered_map<std::string, Component*> _componentMap;
Node* _owner; Node* _owner;
friend class Node; friend class Node;

View File

@ -799,7 +799,7 @@ void FastTMXLayer::removeChild(Node* node, bool cleanup)
} }
// TMXLayer - Properties // TMXLayer - Properties
Value FastTMXLayer::getProperty(std::string_view propertyName) const Value FastTMXLayer::getProperty(const std::string& propertyName) const
{ {
auto propItr = _properties.find(propertyName); auto propItr = _properties.find(propertyName);
if (propItr != _properties.end()) if (propItr != _properties.end())

View File

@ -152,7 +152,7 @@ public:
* @param propertyName The value for the specific property name. * @param propertyName The value for the specific property name.
* @return The value for the specific property name. * @return The value for the specific property name.
*/ */
Value getProperty(std::string_view propertyName) const; Value getProperty(const std::string& propertyName) const;
/** Creates the tiles. */ /** Creates the tiles. */
void setupTiles(); void setupTiles();
@ -161,13 +161,13 @@ public:
* *
* @return The tile layer name. * @return The tile layer name.
*/ */
std::string_view getLayerName() { return _layerName; } const std::string& getLayerName() { return _layerName; }
/** Set the tile layer name. /** Set the tile layer name.
* *
* @param layerName The new layer name. * @param layerName The new layer name.
*/ */
void setLayerName(std::string_view layerName) { _layerName = layerName; } void setLayerName(const std::string& layerName) { _layerName = layerName; }
/** Gets the size of the layer in tiles. /** Gets the size of the layer in tiles.
* *

View File

@ -33,7 +33,7 @@ NS_CC_BEGIN
// implementation FastTMXTiledMap // implementation FastTMXTiledMap
FastTMXTiledMap* FastTMXTiledMap::create(std::string_view tmxFile) FastTMXTiledMap* FastTMXTiledMap::create(const std::string& tmxFile)
{ {
FastTMXTiledMap* ret = new FastTMXTiledMap(); FastTMXTiledMap* ret = new FastTMXTiledMap();
if (ret->initWithTMXFile(tmxFile)) if (ret->initWithTMXFile(tmxFile))
@ -45,7 +45,7 @@ FastTMXTiledMap* FastTMXTiledMap::create(std::string_view tmxFile)
return nullptr; return nullptr;
} }
FastTMXTiledMap* FastTMXTiledMap::createWithXML(std::string_view tmxString, std::string_view resourcePath) FastTMXTiledMap* FastTMXTiledMap::createWithXML(const std::string& tmxString, const std::string& resourcePath)
{ {
FastTMXTiledMap* ret = new FastTMXTiledMap(); FastTMXTiledMap* ret = new FastTMXTiledMap();
if (ret->initWithXML(tmxString, resourcePath)) if (ret->initWithXML(tmxString, resourcePath))
@ -57,7 +57,7 @@ FastTMXTiledMap* FastTMXTiledMap::createWithXML(std::string_view tmxString, std:
return nullptr; return nullptr;
} }
bool FastTMXTiledMap::initWithTMXFile(std::string_view tmxFile) bool FastTMXTiledMap::initWithTMXFile(const std::string& tmxFile)
{ {
CCASSERT(tmxFile.size() > 0, "FastTMXTiledMap: tmx file should not be empty"); CCASSERT(tmxFile.size() > 0, "FastTMXTiledMap: tmx file should not be empty");
@ -77,7 +77,7 @@ bool FastTMXTiledMap::initWithTMXFile(std::string_view tmxFile)
return true; return true;
} }
bool FastTMXTiledMap::initWithXML(std::string_view tmxString, std::string_view resourcePath) bool FastTMXTiledMap::initWithXML(const std::string& tmxString, const std::string& resourcePath)
{ {
setContentSize(Vec2::ZERO); setContentSize(Vec2::ZERO);
@ -194,7 +194,7 @@ void FastTMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo)
} }
// public // public
FastTMXLayer* FastTMXTiledMap::getLayer(std::string_view layerName) const FastTMXLayer* FastTMXTiledMap::getLayer(const std::string& layerName) const
{ {
CCASSERT(!layerName.empty(), "Invalid layer name!"); CCASSERT(!layerName.empty(), "Invalid layer name!");
@ -214,7 +214,7 @@ FastTMXLayer* FastTMXTiledMap::getLayer(std::string_view layerName) const
return nullptr; return nullptr;
} }
TMXObjectGroup* FastTMXTiledMap::getObjectGroup(std::string_view groupName) const TMXObjectGroup* FastTMXTiledMap::getObjectGroup(const std::string& groupName) const
{ {
CCASSERT(!groupName.empty(), "Invalid group name!"); CCASSERT(!groupName.empty(), "Invalid group name!");
@ -233,7 +233,7 @@ TMXObjectGroup* FastTMXTiledMap::getObjectGroup(std::string_view groupName) cons
return nullptr; return nullptr;
} }
Value FastTMXTiledMap::getProperty(std::string_view propertyName) const Value FastTMXTiledMap::getProperty(const std::string& propertyName) const
{ {
auto propsItr = _properties.find(propertyName); auto propsItr = _properties.find(propertyName);
if (propsItr != _properties.end()) if (propsItr != _properties.end())

View File

@ -101,7 +101,7 @@ public:
* *
* @return An autorelease object. * @return An autorelease object.
*/ */
static FastTMXTiledMap* create(std::string_view tmxFile); static FastTMXTiledMap* create(const std::string& tmxFile);
/** Initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources. /** Initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources.
* *
@ -109,25 +109,25 @@ public:
* @param resourcePath A path to TMX resources. * @param resourcePath A path to TMX resources.
* @return An autorelease object. * @return An autorelease object.
*/ */
static FastTMXTiledMap* createWithXML(std::string_view tmxString, std::string_view resourcePath); static FastTMXTiledMap* createWithXML(const std::string& tmxString, const std::string& resourcePath);
/** Return the FastTMXLayer for the specific layer. /** Return the FastTMXLayer for the specific layer.
* *
* @return Return the FastTMXLayer for the specific layer. * @return Return the FastTMXLayer for the specific layer.
*/ */
FastTMXLayer* getLayer(std::string_view layerName) const; FastTMXLayer* getLayer(const std::string& layerName) const;
/** Return the TMXObjectGroup for the specific group. /** Return the TMXObjectGroup for the specific group.
* *
* @return Return the TMXObjectGroup for the specific group. * @return Return the TMXObjectGroup for the specific group.
*/ */
TMXObjectGroup* getObjectGroup(std::string_view groupName) const; TMXObjectGroup* getObjectGroup(const std::string& groupName) const;
/** Return the value for the specific property name. /** Return the value for the specific property name.
* *
* @return Return the value for the specific property name. * @return Return the value for the specific property name.
*/ */
Value getProperty(std::string_view propertyName) const; Value getProperty(const std::string& propertyName) const;
/** Return properties dictionary for tile GID. /** Return properties dictionary for tile GID.
* *
@ -207,7 +207,7 @@ public:
int getLayerCount() const { return _layerCount; } int getLayerCount() const { return _layerCount; }
std::string_view getResourceFile() const { return _tmxFile; } const std::string& getResourceFile() const { return _tmxFile; }
CC_CONSTRUCTOR_ACCESS : CC_CONSTRUCTOR_ACCESS :
/** /**
@ -221,10 +221,10 @@ public:
virtual ~FastTMXTiledMap(); virtual ~FastTMXTiledMap();
/** initializes a TMX Tiled Map with a TMX file */ /** initializes a TMX Tiled Map with a TMX file */
bool initWithTMXFile(std::string_view tmxFile); bool initWithTMXFile(const std::string& tmxFile);
/** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */
bool initWithXML(std::string_view tmxString, std::string_view resourcePath); bool initWithXML(const std::string& tmxString, const std::string& resourcePath);
protected: protected:
FastTMXLayer* parseLayer(TMXLayerInfo* layerInfo, TMXMapInfo* mapInfo); FastTMXLayer* parseLayer(TMXLayerInfo* layerInfo, TMXMapInfo* mapInfo);

View File

@ -520,9 +520,9 @@ void FontAtlas::setLineHeight(float newHeight)
_lineHeight = newHeight; _lineHeight = newHeight;
} }
std::string_view FontAtlas::getFontName() const std::string FontAtlas::getFontName() const
{ {
std::string_view fontName = _fontFreeType ? _fontFreeType->getFontName() : ""sv; std::string fontName = _fontFreeType ? _fontFreeType->getFontName() : "";
if (fontName.empty()) if (fontName.empty())
return fontName; return fontName;
auto idx = fontName.rfind('/'); auto idx = fontName.rfind('/');

View File

@ -86,7 +86,7 @@ public:
float getLineHeight() const { return _lineHeight; } float getLineHeight() const { return _lineHeight; }
void setLineHeight(float newHeight); void setLineHeight(float newHeight);
std::string_view getFontName() const; std::string getFontName() const;
Texture2D* getTexture(int slot); Texture2D* getTexture(int slot);
const Font* getFont() const { return _font; } const Font* getFont() const { return _font; }

View File

@ -36,7 +36,7 @@
NS_CC_BEGIN NS_CC_BEGIN
hlookup::string_map<FontAtlas*> FontAtlasCache::_atlasMap; std::unordered_map<std::string, FontAtlas*> FontAtlasCache::_atlasMap;
#define ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE 255 #define ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE 255
void FontAtlasCache::purgeCachedData() void FontAtlasCache::purgeCachedData()
@ -80,7 +80,8 @@ FontAtlas* FontAtlasCache::getFontAtlasTTF(const _ttfConfig* config)
auto tempAtlas = font->newFontAtlas(); auto tempAtlas = font->newFontAtlas();
if (tempAtlas) if (tempAtlas)
{ {
return _atlasMap.emplace(atlasName, tempAtlas).first->second; _atlasMap[atlasName] = tempAtlas;
return _atlasMap[atlasName];
} }
} }
} }
@ -90,17 +91,16 @@ FontAtlas* FontAtlasCache::getFontAtlasTTF(const _ttfConfig* config)
return nullptr; return nullptr;
} }
FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName) FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName)
{ {
return getFontAtlasFNT(fontFileName, Rect::ZERO, false); return getFontAtlasFNT(fontFileName, Rect::ZERO, false);
} }
FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, std::string_view subTextureKey) FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, const std::string& subTextureKey)
{ {
const auto realFontFilename = FileUtils::getInstance()->getNewFilename( const auto realFontFilename = FileUtils::getInstance()->getNewFilename(
fontFileName); // resolves real file path, to prevent storing multiple atlases for the same file. fontFileName); // resolves real file path, to prevent storing multiple atlases for the same file.
std::string atlasName{subTextureKey}; std::string atlasName = subTextureKey + " " + realFontFilename;
atlasName.append(" ", 1).append(realFontFilename);
const auto it = _atlasMap.find(atlasName); const auto it = _atlasMap.find(atlasName);
if (it == _atlasMap.end()) if (it == _atlasMap.end())
@ -123,7 +123,7 @@ FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, std::s
return nullptr; return nullptr;
} }
FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated) FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated)
{ {
const auto realFontFilename = FileUtils::getInstance()->getNewFilename( const auto realFontFilename = FileUtils::getInstance()->getNewFilename(
fontFileName); // resolves real file path, to prevent storing multiple atlases for the same file. fontFileName); // resolves real file path, to prevent storing multiple atlases for the same file.
@ -153,14 +153,14 @@ FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, const
return nullptr; return nullptr;
} }
FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, const Vec2& imageOffset) FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, const Vec2& imageOffset)
{ {
return getFontAtlasFNT(fontFileName, Rect(imageOffset.x, imageOffset.y, 0, 0), false); return getFontAtlasFNT(fontFileName, Rect(imageOffset.x, imageOffset.y, 0, 0), false);
} }
FontAtlas* FontAtlasCache::getFontAtlasCharMap(std::string_view plistFile) FontAtlas* FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile)
{ {
std::string_view atlasName = plistFile; const std::string& atlasName = plistFile;
auto it = _atlasMap.find(atlasName); auto it = _atlasMap.find(atlasName);
if (it == _atlasMap.end()) if (it == _atlasMap.end())
@ -172,8 +172,8 @@ FontAtlas* FontAtlasCache::getFontAtlasCharMap(std::string_view plistFile)
auto tempAtlas = font->newFontAtlas(); auto tempAtlas = font->newFontAtlas();
if (tempAtlas) if (tempAtlas)
{ {
hlookup::set_item(_atlasMap, atlasName, tempAtlas); // _atlasMap[atlasName] = tempAtlas; _atlasMap[atlasName] = tempAtlas;
return tempAtlas; return _atlasMap[atlasName];
} }
} }
} }
@ -210,7 +210,7 @@ FontAtlas* FontAtlasCache::getFontAtlasCharMap(Texture2D* texture, int itemWidth
return nullptr; return nullptr;
} }
FontAtlas* FontAtlasCache::getFontAtlasCharMap(std::string_view charMapFile, FontAtlas* FontAtlasCache::getFontAtlasCharMap(const std::string& charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
int startCharMap) int startCharMap)
@ -263,7 +263,7 @@ bool FontAtlasCache::releaseFontAtlas(FontAtlas* atlas)
return false; return false;
} }
void FontAtlasCache::reloadFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated) void FontAtlasCache::reloadFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated)
{ {
char keyPrefix[ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE]; char keyPrefix[ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE];
snprintf(keyPrefix, ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE, "%.2f %.2f ", imageRect.origin.x, imageRect.origin.y); snprintf(keyPrefix, ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE, "%.2f %.2f ", imageRect.origin.x, imageRect.origin.y);
@ -288,12 +288,12 @@ void FontAtlasCache::reloadFontAtlasFNT(std::string_view fontFileName, const Rec
} }
} }
void FontAtlasCache::reloadFontAtlasFNT(std::string_view fontFileName, const Vec2& imageOffset) void FontAtlasCache::reloadFontAtlasFNT(const std::string& fontFileName, const Vec2& imageOffset)
{ {
reloadFontAtlasFNT(fontFileName, Rect(imageOffset.x, imageOffset.y, 0, 0), false); reloadFontAtlasFNT(fontFileName, Rect(imageOffset.x, imageOffset.y, 0, 0), false);
} }
void FontAtlasCache::unloadFontAtlasTTF(std::string_view fontFileName) void FontAtlasCache::unloadFontAtlasTTF(const std::string& fontFileName)
{ {
auto item = _atlasMap.begin(); auto item = _atlasMap.begin();
while (item != _atlasMap.end()) while (item != _atlasMap.end())

View File

@ -43,17 +43,17 @@ class CC_DLL FontAtlasCache
public: public:
static FontAtlas* getFontAtlasTTF(const _ttfConfig* config); static FontAtlas* getFontAtlasTTF(const _ttfConfig* config);
static FontAtlas* getFontAtlasFNT(std::string_view fontFileName); static FontAtlas* getFontAtlasFNT(const std::string& fontFileName);
static FontAtlas* getFontAtlasFNT(std::string_view fontFileName, std::string_view subTextureKey); static FontAtlas* getFontAtlasFNT(const std::string& fontFileName, const std::string& subTextureKey);
static FontAtlas* getFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated); static FontAtlas* getFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated);
CC_DEPRECATED_ATTRIBUTE static FontAtlas* getFontAtlasFNT(std::string_view fontFileName, const Vec2& imageOffset); CC_DEPRECATED_ATTRIBUTE static FontAtlas* getFontAtlasFNT(const std::string& fontFileName, const Vec2& imageOffset);
static FontAtlas* getFontAtlasCharMap(std::string_view charMapFile, static FontAtlas* getFontAtlasCharMap(const std::string& charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
int startCharMap); int startCharMap);
static FontAtlas* getFontAtlasCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); static FontAtlas* getFontAtlasCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
static FontAtlas* getFontAtlasCharMap(std::string_view plistFile); static FontAtlas* getFontAtlasCharMap(const std::string& plistFile);
static bool releaseFontAtlas(FontAtlas* atlas); static bool releaseFontAtlas(FontAtlas* atlas);
@ -66,19 +66,19 @@ public:
CAUTION : All component use this font texture should be reset font name, though the file name is same! CAUTION : All component use this font texture should be reset font name, though the file name is same!
otherwise, it will cause program crash! otherwise, it will cause program crash!
*/ */
static void reloadFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated); static void reloadFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated);
CC_DEPRECATED_ATTRIBUTE static void reloadFontAtlasFNT(std::string_view fontFileName, CC_DEPRECATED_ATTRIBUTE static void reloadFontAtlasFNT(const std::string& fontFileName,
const Vec2& imageOffset = Vec2::ZERO); const Vec2& imageOffset = Vec2::ZERO);
/** Unload all texture atlas texture create by special file name. /** Unload all texture atlas texture create by special file name.
CAUTION : All component use this font texture should be reset font name, though the file name is same! CAUTION : All component use this font texture should be reset font name, though the file name is same!
otherwise, it will cause program crash! otherwise, it will cause program crash!
*/ */
static void unloadFontAtlasTTF(std::string_view fontFileName); static void unloadFontAtlasTTF(const std::string& fontFileName);
private: private:
static hlookup::string_map<FontAtlas*> _atlasMap; static std::unordered_map<std::string, FontAtlas*> _atlasMap;
}; };
NS_CC_END NS_CC_END

View File

@ -33,7 +33,7 @@
NS_CC_BEGIN NS_CC_BEGIN
FontCharMap* FontCharMap::create(std::string_view plistFile) FontCharMap* FontCharMap::create(const std::string& plistFile)
{ {
std::string pathStr = FileUtils::getInstance()->fullPathForFilename(plistFile); std::string pathStr = FileUtils::getInstance()->fullPathForFilename(plistFile);
std::string relPathStr = pathStr.substr(0, pathStr.find_last_of('/')) + "/"; std::string relPathStr = pathStr.substr(0, pathStr.find_last_of('/')) + "/";
@ -64,7 +64,7 @@ FontCharMap* FontCharMap::create(std::string_view plistFile)
return tempFont; return tempFont;
} }
FontCharMap* FontCharMap::create(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) FontCharMap* FontCharMap::create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{ {
Texture2D* tempTexture = Director::getInstance()->getTextureCache()->addImage(charMapFile); Texture2D* tempTexture = Director::getInstance()->getTextureCache()->addImage(charMapFile);

View File

@ -38,9 +38,9 @@ class Texture2D;
class FontCharMap : public Font class FontCharMap : public Font
{ {
public: public:
static FontCharMap* create(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); static FontCharMap* create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
static FontCharMap* create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); static FontCharMap* create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
static FontCharMap* create(std::string_view plistFile); static FontCharMap* create(const std::string& plistFile);
virtual int* getHorizontalKerningForTextUTF32(const std::u32string& text, int& outNumLetters) const override; virtual int* getHorizontalKerningForTextUTF32(const std::u32string& text, int& outNumLetters) const override;
virtual FontAtlas* newFontAtlas() override; virtual FontAtlas* newFontAtlas() override;

View File

@ -56,15 +56,15 @@ struct _FontDefHashElement;
// //
// FNTConfig Cache - free functions // FNTConfig Cache - free functions
// //
static StringMap<BMFontConfiguration*>* s_configurations = nullptr; static Map<std::string, BMFontConfiguration*>* s_configurations = nullptr;
BMFontConfiguration* FNTConfigLoadFile(std::string_view fntFile) BMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile)
{ {
BMFontConfiguration* ret = nullptr; BMFontConfiguration* ret = nullptr;
if (s_configurations == nullptr) if (s_configurations == nullptr)
{ {
s_configurations = new StringMap<BMFontConfiguration*>(); s_configurations = new Map<std::string, BMFontConfiguration*>();
} }
ret = s_configurations->at(fntFile); ret = s_configurations->at(fntFile);
@ -84,7 +84,7 @@ BMFontConfiguration* FNTConfigLoadFile(std::string_view fntFile)
// BitmapFontConfiguration // BitmapFontConfiguration
// //
BMFontConfiguration* BMFontConfiguration::create(std::string_view FNTfile) BMFontConfiguration* BMFontConfiguration::create(const std::string& FNTfile)
{ {
BMFontConfiguration* ret = new BMFontConfiguration(); BMFontConfiguration* ret = new BMFontConfiguration();
if (ret->initWithFNTfile(FNTfile)) if (ret->initWithFNTfile(FNTfile))
@ -96,7 +96,7 @@ BMFontConfiguration* BMFontConfiguration::create(std::string_view FNTfile)
return nullptr; return nullptr;
} }
bool BMFontConfiguration::initWithFNTfile(std::string_view FNTfile) bool BMFontConfiguration::initWithFNTfile(const std::string& FNTfile)
{ {
_characterSet = this->parseConfigFile(FNTfile); _characterSet = this->parseConfigFile(FNTfile);
@ -141,7 +141,7 @@ void BMFontConfiguration::purgeFontDefDictionary()
_fontDefDictionary.clear(); _fontDefDictionary.clear();
} }
std::set<unsigned int>* BMFontConfiguration::parseConfigFile(std::string_view controlFile) std::set<unsigned int>* BMFontConfiguration::parseConfigFile(const std::string& controlFile)
{ {
std::string data = FileUtils::getInstance()->getStringFromFile(controlFile); std::string data = FileUtils::getInstance()->getStringFromFile(controlFile);
if (data.empty()) if (data.empty())
@ -156,7 +156,7 @@ std::set<unsigned int>* BMFontConfiguration::parseConfigFile(std::string_view co
} }
if (data[0] == 0) if (data[0] == 0)
{ {
CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.data()); CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str());
return nullptr; return nullptr;
} }
auto contents = data.c_str(); auto contents = data.c_str();
@ -223,7 +223,7 @@ std::set<unsigned int>* BMFontConfiguration::parseConfigFile(std::string_view co
std::set<unsigned int>* BMFontConfiguration::parseBinaryConfigFile(unsigned char* pData, std::set<unsigned int>* BMFontConfiguration::parseBinaryConfigFile(unsigned char* pData,
uint32_t size, uint32_t size,
std::string_view controlFile) const std::string& controlFile)
{ {
/* based on http://www.angelcode.com/products/bmfont/doc/file_format.html file format */ /* based on http://www.angelcode.com/products/bmfont/doc/file_format.html file format */
@ -399,7 +399,7 @@ std::set<unsigned int>* BMFontConfiguration::parseBinaryConfigFile(unsigned char
return validCharsString; return validCharsString;
} }
void BMFontConfiguration::parseImageFileName(const char* line, std::string_view fntFile) void BMFontConfiguration::parseImageFileName(const char* line, const std::string& fntFile)
{ {
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
// line to parse: // line to parse:
@ -528,7 +528,7 @@ void BMFontConfiguration::parseKerningEntry(const char* line)
_kerningDictionary[key] = amount; _kerningDictionary[key] = amount;
} }
FontFNT* FontFNT::create(std::string_view fntFilePath, const Rect& imageRect, bool imageRotated) FontFNT* FontFNT::create(const std::string& fntFilePath, const Rect& imageRect, bool imageRotated)
{ {
const auto newConf = FNTConfigLoadFile(fntFilePath); const auto newConf = FNTConfigLoadFile(fntFilePath);
if (!newConf) if (!newConf)
@ -545,7 +545,7 @@ FontFNT* FontFNT::create(std::string_view fntFilePath, const Rect& imageRect, bo
return tempFont; return tempFont;
} }
FontFNT* FontFNT::create(std::string_view fntFilePath, std::string_view subTextureKey) FontFNT* FontFNT::create(const std::string& fntFilePath, const std::string& subTextureKey)
{ {
const auto newConf = FNTConfigLoadFile(fntFilePath); const auto newConf = FNTConfigLoadFile(fntFilePath);
if (!newConf) if (!newConf)
@ -567,7 +567,7 @@ FontFNT* FontFNT::create(std::string_view fntFilePath, std::string_view subTextu
return tempFont; return tempFont;
} }
FontFNT* FontFNT::create(std::string_view fntFilePath) FontFNT* FontFNT::create(const std::string& fntFilePath)
{ {
const auto newConf = FNTConfigLoadFile(fntFilePath); const auto newConf = FNTConfigLoadFile(fntFilePath);
if (!newConf) if (!newConf)
@ -590,7 +590,7 @@ FontFNT* FontFNT::create(std::string_view fntFilePath)
return tempFont; return tempFont;
} }
FontFNT* FontFNT::create(std::string_view fntFilePath, const Vec2& imageOffset) FontFNT* FontFNT::create(const std::string& fntFilePath, const Vec2& imageOffset)
{ {
return create(fntFilePath, Rect(imageOffset.x, imageOffset.y, 0, 0), false); return create(fntFilePath, Rect(imageOffset.x, imageOffset.y, 0, 0), false);
} }
@ -762,11 +762,11 @@ FontAtlas* FontFNT::newFontAtlas()
return tempAtlas; return tempAtlas;
} }
void FontFNT::reloadBMFontResource(std::string_view fntFilePath) void FontFNT::reloadBMFontResource(const std::string& fntFilePath)
{ {
if (s_configurations == nullptr) if (s_configurations == nullptr)
{ {
s_configurations = new StringMap<BMFontConfiguration*>(); s_configurations = new Map<std::string, BMFontConfiguration*>();
} }
BMFontConfiguration* ret = s_configurations->at(fntFilePath); BMFontConfiguration* ret = s_configurations->at(fntFilePath);

View File

@ -115,27 +115,27 @@ public:
std::string description() const; std::string description() const;
/** allocates a BMFontConfiguration with a FNT file */ /** allocates a BMFontConfiguration with a FNT file */
static BMFontConfiguration* create(std::string_view FNTfile); static BMFontConfiguration* create(const std::string& FNTfile);
/** initializes a BitmapFontConfiguration with a FNT file */ /** initializes a BitmapFontConfiguration with a FNT file */
bool initWithFNTfile(std::string_view FNTfile); bool initWithFNTfile(const std::string& FNTfile);
std::string_view getAtlasName() { return _atlasName; } const std::string& getAtlasName() { return _atlasName; }
void setAtlasName(std::string_view atlasName) { _atlasName = atlasName; } void setAtlasName(const std::string& atlasName) { _atlasName = atlasName; }
std::set<unsigned int>* getCharacterSet() const; std::set<unsigned int>* getCharacterSet() const;
protected: protected:
virtual std::set<unsigned int>* parseConfigFile(std::string_view controlFile); virtual std::set<unsigned int>* parseConfigFile(const std::string& controlFile);
virtual std::set<unsigned int>* parseBinaryConfigFile(unsigned char* pData, virtual std::set<unsigned int>* parseBinaryConfigFile(unsigned char* pData,
uint32_t size, uint32_t size,
std::string_view controlFile); const std::string& controlFile);
private: private:
unsigned int parseCharacterDefinition(const char* line); unsigned int parseCharacterDefinition(const char* line);
void parseInfoArguments(const char* line); void parseInfoArguments(const char* line);
void parseCommonArguments(const char* line); void parseCommonArguments(const char* line);
void parseImageFileName(const char* line, std::string_view fntFile); void parseImageFileName(const char* line, const std::string& fntFile);
void parseKerningEntry(const char* line); void parseKerningEntry(const char* line);
void purgeKerningDictionary(); void purgeKerningDictionary();
void purgeFontDefDictionary(); void purgeFontDefDictionary();
@ -145,11 +145,12 @@ class CC_DLL FontFNT : public Font
{ {
public: public:
static FontFNT* create(std::string_view fntFilePath, const Rect& imageRect, bool imageRotated); static FontFNT* create(const std::string& fntFilePath, const Rect& imageRect, bool imageRotated);
static FontFNT* create(std::string_view fntFilePath, std::string_view subTextureKey); static FontFNT* create(const std::string& fntFilePath, const std::string& subTextureKey);
static FontFNT* create(std::string_view fntFilePath); static FontFNT* create(const std::string& fntFilePath);
CC_DEPRECATED_ATTRIBUTE static FontFNT* create(std::string_view fntFilePath, const Vec2& imageOffset = Vec2::ZERO); CC_DEPRECATED_ATTRIBUTE static FontFNT* create(const std::string& fntFilePath,
const Vec2& imageOffset = Vec2::ZERO);
/** Purges the cached data. /** Purges the cached data.
Removes from memory the cached configurations and the atlas name dictionary. Removes from memory the cached configurations and the atlas name dictionary.
@ -163,7 +164,7 @@ public:
int getOriginalFontSize() const; int getOriginalFontSize() const;
static void reloadBMFontResource(std::string_view fntFilePath); static void reloadBMFontResource(const std::string& fntFilePath);
protected: protected:
FontFNT(BMFontConfiguration* theContfig, const Rect& imageRect, bool imageRotated); FontFNT(BMFontConfiguration* theContfig, const Rect& imageRect, bool imageRotated);

View File

@ -653,7 +653,7 @@ std::string_view FontFreeType::getGlyphCollection() const
return glyphCollection; return glyphCollection;
} }
void FontFreeType::releaseFont(std::string_view fontName) void FontFreeType::releaseFont(const std::string& fontName)
{ {
auto item = s_cacheFontData.begin(); auto item = s_cacheFontData.begin();
while (s_cacheFontData.end() != item) while (s_cacheFontData.end() != item)

View File

@ -101,12 +101,12 @@ public:
int getFontAscender() const; int getFontAscender() const;
const char* getFontFamily() const; const char* getFontFamily() const;
std::string_view getFontName() const { return _fontName; } const std::string& getFontName() const { return _fontName; }
virtual FontAtlas* newFontAtlas() override; virtual FontAtlas* newFontAtlas() override;
virtual int getFontMaxHeight() const override { return _lineHeight; } virtual int getFontMaxHeight() const override { return _lineHeight; }
static void releaseFont(std::string_view fontName); static void releaseFont(const std::string& fontName);
static FT_Library getFTLibrary(); static FT_Library getFTLibrary();

View File

@ -240,8 +240,8 @@ Label* Label::create()
return ret; return ret;
} }
Label* Label::createWithSystemFont(std::string_view text, Label* Label::createWithSystemFont(const std::string& text,
std::string_view font, const std::string& font,
float fontSize, float fontSize,
const Vec2& dimensions /* = Vec2::ZERO */, const Vec2& dimensions /* = Vec2::ZERO */,
TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */,
@ -259,8 +259,8 @@ Label* Label::createWithSystemFont(std::string_view text,
return ret; return ret;
} }
Label* Label::createWithTTF(std::string_view text, Label* Label::createWithTTF(const std::string& text,
std::string_view fontFile, const std::string& fontFile,
float fontSize, float fontSize,
const Vec2& dimensions /* = Vec2::ZERO */, const Vec2& dimensions /* = Vec2::ZERO */,
TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */,
@ -279,7 +279,7 @@ Label* Label::createWithTTF(std::string_view text,
} }
Label* Label::createWithTTF(const TTFConfig& ttfConfig, Label* Label::createWithTTF(const TTFConfig& ttfConfig,
std::string_view text, const std::string& text,
TextHAlignment hAlignment /* = TextHAlignment::CENTER */, TextHAlignment hAlignment /* = TextHAlignment::CENTER */,
int maxLineWidth /* = 0 */) int maxLineWidth /* = 0 */)
{ {
@ -295,8 +295,8 @@ Label* Label::createWithTTF(const TTFConfig& ttfConfig,
return nullptr; return nullptr;
} }
Label* Label::createWithBMFont(std::string_view bmfontPath, Label* Label::createWithBMFont(const std::string& bmfontPath,
std::string_view text, const std::string& text,
const TextHAlignment& hAlignment, const TextHAlignment& hAlignment,
int maxLineWidth) int maxLineWidth)
{ {
@ -315,8 +315,8 @@ Label* Label::createWithBMFont(std::string_view bmfontPath,
return nullptr; return nullptr;
} }
Label* Label::createWithBMFont(std::string_view bmfontPath, Label* Label::createWithBMFont(const std::string& bmfontPath,
std::string_view text, const std::string& text,
const TextHAlignment& hAlignment, const TextHAlignment& hAlignment,
int maxLineWidth, int maxLineWidth,
const Rect& imageRect, const Rect& imageRect,
@ -337,11 +337,11 @@ Label* Label::createWithBMFont(std::string_view bmfontPath,
return nullptr; return nullptr;
} }
Label* Label::createWithBMFont(std::string_view bmfontPath, Label* Label::createWithBMFont(const std::string& bmfontPath,
std::string_view text, const std::string& text,
const TextHAlignment& hAlignment, const TextHAlignment& hAlignment,
int maxLineWidth, int maxLineWidth,
std::string_view subTextureKey) const std::string& subTextureKey)
{ {
auto ret = new Label(hAlignment); auto ret = new Label(hAlignment);
@ -358,8 +358,8 @@ Label* Label::createWithBMFont(std::string_view bmfontPath,
return nullptr; return nullptr;
} }
Label* Label::createWithBMFont(std::string_view bmfontPath, Label* Label::createWithBMFont(const std::string& bmfontPath,
std::string_view text, const std::string& text,
const TextHAlignment& hAlignment, const TextHAlignment& hAlignment,
int maxLineWidth, int maxLineWidth,
const Vec2& imageOffset) const Vec2& imageOffset)
@ -368,7 +368,7 @@ Label* Label::createWithBMFont(std::string_view bmfontPath,
false); false);
} }
Label* Label::createWithCharMap(std::string_view plistFile) Label* Label::createWithCharMap(const std::string& plistFile)
{ {
auto ret = new Label(); auto ret = new Label();
@ -396,7 +396,7 @@ Label* Label::createWithCharMap(Texture2D* texture, int itemWidth, int itemHeigh
return nullptr; return nullptr;
} }
Label* Label::createWithCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) Label* Label::createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{ {
auto ret = new Label(); auto ret = new Label();
@ -410,7 +410,7 @@ Label* Label::createWithCharMap(std::string_view charMapFile, int itemWidth, int
return nullptr; return nullptr;
} }
bool Label::setCharMap(std::string_view plistFile) bool Label::setCharMap(const std::string& plistFile)
{ {
auto newAtlas = FontAtlasCache::getFontAtlasCharMap(plistFile); auto newAtlas = FontAtlasCache::getFontAtlasCharMap(plistFile);
@ -426,8 +426,8 @@ bool Label::setCharMap(std::string_view plistFile)
return true; return true;
} }
bool Label::initWithTTF(std::string_view text, bool Label::initWithTTF(const std::string& text,
std::string_view fontFilePath, const std::string& fontFilePath,
float fontSize, float fontSize,
const Vec2& dimensions, const Vec2& dimensions,
TextHAlignment /*hAlignment*/, TextHAlignment /*hAlignment*/,
@ -447,7 +447,7 @@ bool Label::initWithTTF(std::string_view text,
} }
bool Label::initWithTTF(const TTFConfig& ttfConfig, bool Label::initWithTTF(const TTFConfig& ttfConfig,
std::string_view text, const std::string& text,
TextHAlignment /*hAlignment*/, TextHAlignment /*hAlignment*/,
int maxLineWidth) int maxLineWidth)
{ {
@ -476,7 +476,7 @@ bool Label::setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int st
return true; return true;
} }
bool Label::setCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) bool Label::setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{ {
auto newAtlas = FontAtlasCache::getFontAtlasCharMap(charMapFile, itemWidth, itemHeight, startCharMap); auto newAtlas = FontAtlasCache::getFontAtlasCharMap(charMapFile, itemWidth, itemHeight, startCharMap);
@ -841,7 +841,7 @@ bool Label::setTTFConfig(const TTFConfig& ttfConfig)
return setTTFConfigInternal(ttfConfig); return setTTFConfigInternal(ttfConfig);
} }
bool Label::setBMFontFilePath(std::string_view bmfontFilePath, float fontSize) bool Label::setBMFontFilePath(const std::string& bmfontFilePath, float fontSize)
{ {
FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath); FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath);
@ -875,7 +875,10 @@ bool Label::setBMFontFilePath(std::string_view bmfontFilePath, float fontSize)
return true; return true;
} }
bool Label::setBMFontFilePath(std::string_view bmfontFilePath, const Rect& imageRect, bool imageRotated, float fontSize) bool Label::setBMFontFilePath(const std::string& bmfontFilePath,
const Rect& imageRect,
bool imageRotated,
float fontSize)
{ {
FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath, imageRect, imageRotated); FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath, imageRect, imageRotated);
@ -911,7 +914,7 @@ bool Label::setBMFontFilePath(std::string_view bmfontFilePath, const Rect& image
return true; return true;
} }
bool Label::setBMFontFilePath(std::string_view bmfontFilePath, std::string_view subTextureKey, float fontSize) bool Label::setBMFontFilePath(const std::string& bmfontFilePath, const std::string& subTextureKey, float fontSize)
{ {
FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath, subTextureKey); FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath, subTextureKey);
@ -946,7 +949,7 @@ bool Label::setBMFontFilePath(std::string_view bmfontFilePath, std::string_view
return true; return true;
} }
bool Label::setBMFontFilePath(std::string_view bmfontFilePath, const Vec2& imageOffset, float fontSize) bool Label::setBMFontFilePath(const std::string& bmfontFilePath, const Vec2& imageOffset, float fontSize)
{ {
return setBMFontFilePath(bmfontFilePath, Rect(imageOffset.x, imageOffset.y, 0, 0), false); return setBMFontFilePath(bmfontFilePath, Rect(imageOffset.x, imageOffset.y, 0, 0), false);
} }
@ -2102,7 +2105,7 @@ void Label::drawSelf(bool visibleByCamera, Renderer* renderer, uint32_t flags)
} }
} }
void Label::setSystemFontName(std::string_view systemFont) void Label::setSystemFontName(const std::string& systemFont)
{ {
if (systemFont != _systemFont) if (systemFont != _systemFont)
{ {

View File

@ -166,8 +166,8 @@ public:
* *
* @return An automatically released Label object. * @return An automatically released Label object.
*/ */
static Label* createWithSystemFont(std::string_view text, static Label* createWithSystemFont(const std::string& text,
std::string_view font, const std::string& font,
float fontSize, float fontSize,
const Vec2& dimensions = Vec2::ZERO, const Vec2& dimensions = Vec2::ZERO,
TextHAlignment hAlignment = TextHAlignment::LEFT, TextHAlignment hAlignment = TextHAlignment::LEFT,
@ -185,8 +185,8 @@ public:
* *
* @return An automatically released Label object. * @return An automatically released Label object.
*/ */
static Label* createWithTTF(std::string_view text, static Label* createWithTTF(const std::string& text,
std::string_view fontFilePath, const std::string& fontFilePath,
float fontSize, float fontSize,
const Vec2& dimensions = Vec2::ZERO, const Vec2& dimensions = Vec2::ZERO,
TextHAlignment hAlignment = TextHAlignment::LEFT, TextHAlignment hAlignment = TextHAlignment::LEFT,
@ -204,7 +204,7 @@ public:
* @see TTFConfig setTTFConfig setMaxLineWidth * @see TTFConfig setTTFConfig setMaxLineWidth
*/ */
static Label* createWithTTF(const TTFConfig& ttfConfig, static Label* createWithTTF(const TTFConfig& ttfConfig,
std::string_view text, const std::string& text,
TextHAlignment hAlignment = TextHAlignment::LEFT, TextHAlignment hAlignment = TextHAlignment::LEFT,
int maxLineWidth = 0); int maxLineWidth = 0);
@ -219,8 +219,8 @@ public:
* @return An automatically released Label object. * @return An automatically released Label object.
* @see setBMFontFilePath setMaxLineWidth * @see setBMFontFilePath setMaxLineWidth
*/ */
static Label* createWithBMFont(std::string_view bmfontPath, static Label* createWithBMFont(const std::string& bmfontPath,
std::string_view text, const std::string& text,
const TextHAlignment& hAlignment = TextHAlignment::LEFT, const TextHAlignment& hAlignment = TextHAlignment::LEFT,
int maxLineWidth = 0); int maxLineWidth = 0);
@ -237,8 +237,8 @@ public:
* @return An automatically released Label object. * @return An automatically released Label object.
* @see setBMFontFilePath setMaxLineWidth * @see setBMFontFilePath setMaxLineWidth
*/ */
static Label* createWithBMFont(std::string_view bmfontPath, static Label* createWithBMFont(const std::string& bmfontPath,
std::string_view text, const std::string& text,
const TextHAlignment& hAlignment, const TextHAlignment& hAlignment,
int maxLineWidth, int maxLineWidth,
const Rect& imageRect, const Rect& imageRect,
@ -256,11 +256,11 @@ public:
* @return An automatically released Label object. * @return An automatically released Label object.
* @see setBMFontFilePath setMaxLineWidth * @see setBMFontFilePath setMaxLineWidth
*/ */
static Label* createWithBMFont(std::string_view bmfontPath, static Label* createWithBMFont(const std::string& bmfontPath,
std::string_view text, const std::string& text,
const TextHAlignment& hAlignment, const TextHAlignment& hAlignment,
int maxLineWidth, int maxLineWidth,
std::string_view subTextureKey); const std::string& subTextureKey);
/** /**
* Allocates and initializes a Label, with a bitmap font file. * Allocates and initializes a Label, with a bitmap font file.
@ -274,8 +274,8 @@ public:
* @return An automatically released Label object. * @return An automatically released Label object.
* @see setBMFontFilePath setMaxLineWidth * @see setBMFontFilePath setMaxLineWidth
*/ */
CC_DEPRECATED_ATTRIBUTE static Label* createWithBMFont(std::string_view bmfontPath, CC_DEPRECATED_ATTRIBUTE static Label* createWithBMFont(const std::string& bmfontPath,
std::string_view text, const std::string& text,
const TextHAlignment& hAlignment, const TextHAlignment& hAlignment,
int maxLineWidth, int maxLineWidth,
const Vec2& imageOffset); const Vec2& imageOffset);
@ -290,7 +290,7 @@ public:
* *
* @return An automatically released Label object. * @return An automatically released Label object.
*/ */
static Label* createWithCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); static Label* createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
/** /**
* Allocates and initializes a Label, with char map configuration. * Allocates and initializes a Label, with char map configuration.
@ -311,7 +311,7 @@ public:
* *
* @return An automatically released Label object. * @return An automatically released Label object.
*/ */
static Label* createWithCharMap(std::string_view plistFile); static Label* createWithCharMap(const std::string& plistFile);
// end of creators group // end of creators group
/// @} /// @}
@ -332,31 +332,33 @@ public:
virtual const TTFConfig& getTTFConfig() const { return _fontConfig; } virtual const TTFConfig& getTTFConfig() const { return _fontConfig; }
/** Sets a new bitmap font to Label */ /** Sets a new bitmap font to Label */
virtual bool setBMFontFilePath(std::string_view bmfontFilePath, float fontSize = 0); virtual bool setBMFontFilePath(const std::string& bmfontFilePath, float fontSize = 0);
/** Sets a new bitmap font to Label */ /** Sets a new bitmap font to Label */
virtual bool setBMFontFilePath(std::string_view bmfontFilePath, virtual bool setBMFontFilePath(const std::string& bmfontFilePath,
const Rect& imageRect, const Rect& imageRect,
bool imageRotated, bool imageRotated,
float fontSize = 0); float fontSize = 0);
/** Sets a new bitmap font to Label */ /** Sets a new bitmap font to Label */
virtual bool setBMFontFilePath(std::string_view bmfontFilePath, std::string_view subTextureKey, float fontSize = 0); virtual bool setBMFontFilePath(const std::string& bmfontFilePath,
const std::string& subTextureKey,
float fontSize = 0);
/** Sets a new bitmap font to Label */ /** Sets a new bitmap font to Label */
CC_DEPRECATED_ATTRIBUTE virtual bool setBMFontFilePath(std::string_view bmfontFilePath, CC_DEPRECATED_ATTRIBUTE virtual bool setBMFontFilePath(const std::string& bmfontFilePath,
const Vec2& imageOffset, const Vec2& imageOffset,
float fontSize = 0); float fontSize = 0);
/** Returns the bitmap font used by the Label.*/ /** Returns the bitmap font used by the Label.*/
std::string_view getBMFontFilePath() const { return _bmFontPath; } const std::string& getBMFontFilePath() const { return _bmFontPath; }
/** /**
* Sets a new char map configuration to Label. * Sets a new char map configuration to Label.
* *
* @see `createWithCharMap(std::string_view,int,int,int)` * @see `createWithCharMap(const std::string&,int,int,int)`
*/ */
virtual bool setCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); virtual bool setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
/** /**
* Sets a new char map configuration to Label. * Sets a new char map configuration to Label.
@ -368,9 +370,9 @@ public:
/** /**
* Sets a new char map configuration to Label. * Sets a new char map configuration to Label.
* *
* @see `createWithCharMap(std::string_view)` * @see `createWithCharMap(const std::string&)`
*/ */
virtual bool setCharMap(std::string_view plistFile); virtual bool setCharMap(const std::string& plistFile);
/** /**
* Sets a new system font to Label. * Sets a new system font to Label.
@ -378,10 +380,10 @@ public:
* @param font A font file or a font family name. * @param font A font file or a font family name.
* @warning * @warning
*/ */
virtual void setSystemFontName(std::string_view font); virtual void setSystemFontName(const std::string& font);
/** Returns the system font used by the Label.*/ /** Returns the system font used by the Label.*/
virtual std::string_view getSystemFontName() const { return _systemFont; } virtual const std::string& getSystemFontName() const { return _systemFont; }
/* Sets the system font size of Label.*/ /* Sets the system font size of Label.*/
virtual void setSystemFontSize(float fontSize); virtual void setSystemFontSize(float fontSize);
@ -401,7 +403,7 @@ public:
virtual void setString(std::string_view text) override; virtual void setString(std::string_view text) override;
/** Return the text the Label is currently displaying.*/ /** Return the text the Label is currently displaying.*/
virtual std::string_view getString() const override { return _utf8Text; } virtual const std::string& getString() const override { return _utf8Text; }
/** /**
* Return the number of lines of text. * Return the number of lines of text.
@ -714,15 +716,15 @@ public:
*/ */
virtual ~Label(); virtual ~Label();
bool initWithTTF(std::string_view text, bool initWithTTF(const std::string& text,
std::string_view fontFilePath, const std::string& fontFilePath,
float fontSize, float fontSize,
const Vec2& dimensions = Vec2::ZERO, const Vec2& dimensions = Vec2::ZERO,
TextHAlignment hAlignment = TextHAlignment::LEFT, TextHAlignment hAlignment = TextHAlignment::LEFT,
TextVAlignment vAlignment = TextVAlignment::TOP); TextVAlignment vAlignment = TextVAlignment::TOP);
bool initWithTTF(const TTFConfig& ttfConfig, bool initWithTTF(const TTFConfig& ttfConfig,
std::string_view text, const std::string& text,
TextHAlignment hAlignment = TextHAlignment::LEFT, TextHAlignment hAlignment = TextHAlignment::LEFT,
int maxLineWidth = 0); int maxLineWidth = 0);

View File

@ -40,8 +40,8 @@ NS_CC_BEGIN
// CCLabelAtlas - Creation & Init // CCLabelAtlas - Creation & Init
LabelAtlas* LabelAtlas::create(std::string_view string, LabelAtlas* LabelAtlas::create(const std::string& string,
std::string_view charMapFile, const std::string& charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
int startCharMap) int startCharMap)
@ -56,8 +56,8 @@ LabelAtlas* LabelAtlas::create(std::string_view string,
return nullptr; return nullptr;
} }
bool LabelAtlas::initWithString(std::string_view string, bool LabelAtlas::initWithString(const std::string& string,
std::string_view charMapFile, const std::string& charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
int startCharMap) int startCharMap)
@ -66,7 +66,7 @@ bool LabelAtlas::initWithString(std::string_view string,
return initWithString(string, texture, itemWidth, itemHeight, startCharMap); return initWithString(string, texture, itemWidth, itemHeight, startCharMap);
} }
bool LabelAtlas::initWithString(std::string_view string, bool LabelAtlas::initWithString(const std::string& string,
Texture2D* texture, Texture2D* texture,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
@ -81,7 +81,7 @@ bool LabelAtlas::initWithString(std::string_view string,
return false; return false;
} }
LabelAtlas* LabelAtlas::create(std::string_view string, std::string_view fntFile) LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& fntFile)
{ {
LabelAtlas* ret = new LabelAtlas(); LabelAtlas* ret = new LabelAtlas();
@ -97,7 +97,7 @@ LabelAtlas* LabelAtlas::create(std::string_view string, std::string_view fntFile
return ret; return ret;
} }
LabelAtlas* LabelAtlas::create(std::string_view string, LabelAtlas* LabelAtlas::create(const std::string& string,
Texture2D* texture, Texture2D* texture,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
@ -117,7 +117,7 @@ LabelAtlas* LabelAtlas::create(std::string_view string,
return ret; return ret;
} }
bool LabelAtlas::initWithString(std::string_view theString, std::string_view fntFile) bool LabelAtlas::initWithString(const std::string& theString, const std::string& fntFile)
{ {
std::string pathStr = FileUtils::getInstance()->fullPathForFilename(fntFile); std::string pathStr = FileUtils::getInstance()->fullPathForFilename(fntFile);
std::string relPathStr = pathStr.substr(0, pathStr.find_last_of('/')) + "/"; std::string relPathStr = pathStr.substr(0, pathStr.find_last_of('/')) + "/";
@ -128,8 +128,8 @@ bool LabelAtlas::initWithString(std::string_view theString, std::string_view fnt
std::string textureFilename = relPathStr + dict["textureFilename"].asString(); std::string textureFilename = relPathStr + dict["textureFilename"].asString();
unsigned int width = static_cast<unsigned int>(dict["itemWidth"].asInt() / CC_CONTENT_SCALE_FACTOR()); unsigned int width = dict["itemWidth"].asInt() / CC_CONTENT_SCALE_FACTOR();
unsigned int height = static_cast<unsigned int>(dict["itemHeight"].asInt() / CC_CONTENT_SCALE_FACTOR()); unsigned int height = dict["itemHeight"].asInt() / CC_CONTENT_SCALE_FACTOR();
unsigned int startChar = dict["firstChar"].asInt(); unsigned int startChar = dict["firstChar"].asInt();
this->initWithString(theString, textureFilename, width, height, startChar); this->initWithString(theString, textureFilename, width, height, startChar);
@ -156,8 +156,8 @@ void LabelAtlas::updateAtlasValues()
float itemHeightInPixels = _itemHeight * CC_CONTENT_SCALE_FACTOR(); float itemHeightInPixels = _itemHeight * CC_CONTENT_SCALE_FACTOR();
if (_ignoreContentScaleFactor) if (_ignoreContentScaleFactor)
{ {
itemWidthInPixels = static_cast<float>(_itemWidth); itemWidthInPixels = _itemWidth;
itemHeightInPixels = static_cast<float>(_itemHeight); itemHeightInPixels = _itemHeight;
} }
CCASSERT(n <= _textureAtlas->getCapacity(), "updateAtlasValues: Invalid String length"); CCASSERT(n <= _textureAtlas->getCapacity(), "updateAtlasValues: Invalid String length");
@ -239,7 +239,7 @@ void LabelAtlas::setString(std::string_view label)
_quadsToDraw = len; _quadsToDraw = len;
} }
std::string_view LabelAtlas::getString() const const std::string& LabelAtlas::getString() const
{ {
return _string; return _string;
} }

View File

@ -58,8 +58,8 @@ class CC_DLL LabelAtlas : public AtlasNode, public LabelProtocol
public: public:
/** Creates the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the /** Creates the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the
* starting char of the atlas. */ * starting char of the atlas. */
static LabelAtlas* create(std::string_view string, static LabelAtlas* create(const std::string& string,
std::string_view charMapFile, const std::string& charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
int startCharMap); int startCharMap);
@ -68,13 +68,13 @@ public:
* Creates the LabelAtlas with a string and a configuration file. * Creates the LabelAtlas with a string and a configuration file.
* @since v2.0 * @since v2.0
*/ */
static LabelAtlas* create(std::string_view string, std::string_view fntFile); static LabelAtlas* create(const std::string& string, const std::string& fntFile);
/** /**
* Creates the LabelAtlas with a string, a texture, the width and height of each element and the starting char of * Creates the LabelAtlas with a string, a texture, the width and height of each element and the starting char of
* the atlas. * the atlas.
*/ */
static LabelAtlas* create(std::string_view string, static LabelAtlas* create(const std::string& string,
Texture2D* texture, Texture2D* texture,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
@ -82,8 +82,8 @@ public:
/** Initializes the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and /** Initializes the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and
* the starting char of the atlas. */ * the starting char of the atlas. */
bool initWithString(std::string_view string, bool initWithString(const std::string& string,
std::string_view charMapFile, const std::string& charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
int startCharMap); int startCharMap);
@ -92,14 +92,14 @@ public:
* Initializes the LabelAtlas with a string and a configuration file. * Initializes the LabelAtlas with a string and a configuration file.
* @since v2.0 * @since v2.0
*/ */
bool initWithString(std::string_view string, std::string_view fntFile); bool initWithString(const std::string& string, const std::string& fntFile);
/** Initializes the LabelAtlas with a string, a texture, the width and height in points of each element and the /** Initializes the LabelAtlas with a string, a texture, the width and height in points of each element and the
* starting char of the atlas */ * starting char of the atlas */
bool initWithString(std::string_view string, Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); bool initWithString(const std::string& string, Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
virtual void setString(std::string_view label) override; virtual void setString(std::string_view label) override;
virtual std::string_view getString() const override; virtual const std::string& getString() const override;
virtual void updateAtlasValues() override; virtual void updateAtlasValues() override;
/** /**

View File

@ -109,7 +109,7 @@ int Label::getFirstWordLen(const std::u32string& utf32Text, int startIndex, int
break; break;
} }
nextLetterX += static_cast<int>(letterDef.xAdvance * _bmfontScale + _additionalKerning); nextLetterX += letterDef.xAdvance * _bmfontScale + _additionalKerning;
len++; len++;
} }
@ -139,9 +139,9 @@ void Label::updateBMFontScale()
auto font = _fontAtlas->getFont(); auto font = _fontAtlas->getFont();
if (_currentLabelType == LabelType::BMFONT) if (_currentLabelType == LabelType::BMFONT)
{ {
FontFNT* bmFont = (FontFNT*)font; FontFNT* bmFont = (FontFNT*)font;
auto originalFontSize = bmFont->getOriginalFontSize(); float originalFontSize = bmFont->getOriginalFontSize();
_bmfontScale = _bmFontSize * CC_CONTENT_SCALE_FACTOR() / originalFontSize; _bmfontScale = _bmFontSize * CC_CONTENT_SCALE_FACTOR() / originalFontSize;
} }
else else
{ {
@ -242,7 +242,7 @@ bool Label::multilineTextWrap(const std::function<int(const std::u32string&, int
{ {
float newLetterWidth = 0.f; float newLetterWidth = 0.f;
if (_horizontalKernings && letterIndex < textLen - 1) if (_horizontalKernings && letterIndex < textLen - 1)
newLetterWidth = static_cast<float>(_horizontalKernings[letterIndex + 1]); newLetterWidth = _horizontalKernings[letterIndex + 1];
newLetterWidth += letterDef.xAdvance * _bmfontScale + _additionalKerning; newLetterWidth += letterDef.xAdvance * _bmfontScale + _additionalKerning;
nextLetterX += newLetterWidth; nextLetterX += newLetterWidth;

View File

@ -175,7 +175,7 @@ void Menu::addChild(Node* child, int zOrder, int tag)
Layer::addChild(child, zOrder, tag); Layer::addChild(child, zOrder, tag);
} }
void Menu::addChild(Node* child, int zOrder, std::string_view name) void Menu::addChild(Node* child, int zOrder, const std::string& name)
{ {
CCASSERT(dynamic_cast<MenuItem*>(child) != nullptr, "Menu only supports MenuItem objects as children"); CCASSERT(dynamic_cast<MenuItem*>(child) != nullptr, "Menu only supports MenuItem objects as children");
Layer::addChild(child, zOrder, name); Layer::addChild(child, zOrder, name);

View File

@ -148,7 +148,7 @@ public:
virtual void addChild(Node* child) override; virtual void addChild(Node* child) override;
virtual void addChild(Node* child, int zOrder) override; virtual void addChild(Node* child, int zOrder) override;
virtual void addChild(Node* child, int zOrder, int tag) override; virtual void addChild(Node* child, int zOrder, int tag) override;
virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void addChild(Node* child, int zOrder, const std::string& name) override;
virtual void onEnter() override; virtual void onEnter() override;
virtual void onExit() override; virtual void onExit() override;

View File

@ -180,13 +180,13 @@ bool MenuItemLabel::initWithLabel(Node* label, const ccMenuCallback& callback)
MenuItemLabel::~MenuItemLabel() {} MenuItemLabel::~MenuItemLabel() {}
void MenuItemLabel::setString(std::string_view label) void MenuItemLabel::setString(const std::string& label)
{ {
dynamic_cast<LabelProtocol*>(_label)->setString(label); dynamic_cast<LabelProtocol*>(_label)->setString(label);
this->setContentSize(_label->getContentSize()); this->setContentSize(_label->getContentSize());
} }
std::string_view MenuItemLabel::getString() const std::string MenuItemLabel::getString() const
{ {
auto label = dynamic_cast<LabelProtocol*>(_label); auto label = dynamic_cast<LabelProtocol*>(_label);
return label->getString(); return label->getString();
@ -259,8 +259,8 @@ void MenuItemLabel::setEnabled(bool enabled)
// CCMenuItemAtlasFont // CCMenuItemAtlasFont
// //
MenuItemAtlasFont* MenuItemAtlasFont::create(std::string_view value, MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value,
std::string_view charMapFile, const std::string& charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
char startCharMap) char startCharMap)
@ -269,8 +269,8 @@ MenuItemAtlasFont* MenuItemAtlasFont::create(std::string_view value,
(const ccMenuCallback&)nullptr); (const ccMenuCallback&)nullptr);
} }
MenuItemAtlasFont* MenuItemAtlasFont::create(std::string_view value, MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value,
std::string_view charMapFile, const std::string& charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
char startCharMap, char startCharMap,
@ -282,8 +282,8 @@ MenuItemAtlasFont* MenuItemAtlasFont::create(std::string_view value,
return ret; return ret;
} }
bool MenuItemAtlasFont::initWithString(std::string_view value, bool MenuItemAtlasFont::initWithString(const std::string& value,
std::string_view charMapFile, const std::string& charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
char startCharMap, char startCharMap,
@ -312,7 +312,7 @@ int MenuItemFont::getFontSize()
return _globalFontSize; return _globalFontSize;
} }
void MenuItemFont::setFontName(std::string_view name) void MenuItemFont::setFontName(const std::string& name)
{ {
if (_globalFontNameRelease) if (_globalFontNameRelease)
{ {
@ -322,12 +322,12 @@ void MenuItemFont::setFontName(std::string_view name)
_globalFontNameRelease = true; _globalFontNameRelease = true;
} }
std::string_view MenuItemFont::getFontName() const std::string& MenuItemFont::getFontName()
{ {
return _globalFontName; return _globalFontName;
} }
MenuItemFont* MenuItemFont::create(std::string_view value, const ccMenuCallback& callback) MenuItemFont* MenuItemFont::create(const std::string& value, const ccMenuCallback& callback)
{ {
MenuItemFont* ret = new MenuItemFont(); MenuItemFont* ret = new MenuItemFont();
ret->initWithString(value, callback); ret->initWithString(value, callback);
@ -335,7 +335,7 @@ MenuItemFont* MenuItemFont::create(std::string_view value, const ccMenuCallback&
return ret; return ret;
} }
MenuItemFont* MenuItemFont::create(std::string_view value) MenuItemFont* MenuItemFont::create(const std::string& value)
{ {
MenuItemFont* ret = new MenuItemFont(); MenuItemFont* ret = new MenuItemFont();
ret->initWithString(value, (const ccMenuCallback&)nullptr); ret->initWithString(value, (const ccMenuCallback&)nullptr);
@ -350,7 +350,7 @@ MenuItemFont::~MenuItemFont()
CCLOGINFO("In the destructor of MenuItemFont (%p).", this); CCLOGINFO("In the destructor of MenuItemFont (%p).", this);
} }
bool MenuItemFont::initWithString(std::string_view value, const ccMenuCallback& callback) bool MenuItemFont::initWithString(const std::string& value, const ccMenuCallback& callback)
{ {
CCASSERT(!value.empty(), "Value length must be greater than 0"); CCASSERT(!value.empty(), "Value length must be greater than 0");
@ -377,14 +377,14 @@ int MenuItemFont::getFontSizeObj() const
return _fontSize; return _fontSize;
} }
void MenuItemFont::setFontNameObj(std::string_view name) void MenuItemFont::setFontNameObj(const std::string& name)
{ {
_fontName = name; _fontName = name;
dynamic_cast<Label*>(_label)->setSystemFontName(_fontName); dynamic_cast<Label*>(_label)->setSystemFontName(_fontName);
this->setContentSize(dynamic_cast<Label*>(_label)->getContentSize()); this->setContentSize(dynamic_cast<Label*>(_label)->getContentSize());
} }
std::string_view MenuItemFont::getFontNameObj() const const std::string& MenuItemFont::getFontNameObj() const
{ {
return _fontName; return _fontName;
} }
@ -600,21 +600,21 @@ bool MenuItemImage::init()
return initWithNormalImage("", "", "", (const ccMenuCallback&)nullptr); return initWithNormalImage("", "", "", (const ccMenuCallback&)nullptr);
} }
MenuItemImage* MenuItemImage::create(std::string_view normalImage, std::string_view selectedImage) MenuItemImage* MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage)
{ {
return MenuItemImage::create(normalImage, selectedImage, "", (const ccMenuCallback&)nullptr); return MenuItemImage::create(normalImage, selectedImage, "", (const ccMenuCallback&)nullptr);
} }
MenuItemImage* MenuItemImage::create(std::string_view normalImage, MenuItemImage* MenuItemImage::create(const std::string& normalImage,
std::string_view selectedImage, const std::string& selectedImage,
const ccMenuCallback& callback) const ccMenuCallback& callback)
{ {
return MenuItemImage::create(normalImage, selectedImage, "", callback); return MenuItemImage::create(normalImage, selectedImage, "", callback);
} }
MenuItemImage* MenuItemImage::create(std::string_view normalImage, MenuItemImage* MenuItemImage::create(const std::string& normalImage,
std::string_view selectedImage, const std::string& selectedImage,
std::string_view disabledImage, const std::string& disabledImage,
const ccMenuCallback& callback) const ccMenuCallback& callback)
{ {
MenuItemImage* ret = new MenuItemImage(); MenuItemImage* ret = new MenuItemImage();
@ -627,9 +627,9 @@ MenuItemImage* MenuItemImage::create(std::string_view normalImage,
return nullptr; return nullptr;
} }
MenuItemImage* MenuItemImage::create(std::string_view normalImage, MenuItemImage* MenuItemImage::create(const std::string& normalImage,
std::string_view selectedImage, const std::string& selectedImage,
std::string_view disabledImage) const std::string& disabledImage)
{ {
MenuItemImage* ret = new MenuItemImage(); MenuItemImage* ret = new MenuItemImage();
if (ret->initWithNormalImage(normalImage, selectedImage, disabledImage, (const ccMenuCallback&)nullptr)) if (ret->initWithNormalImage(normalImage, selectedImage, disabledImage, (const ccMenuCallback&)nullptr))
@ -641,9 +641,9 @@ MenuItemImage* MenuItemImage::create(std::string_view normalImage,
return nullptr; return nullptr;
} }
bool MenuItemImage::initWithNormalImage(std::string_view normalImage, bool MenuItemImage::initWithNormalImage(const std::string& normalImage,
std::string_view selectedImage, const std::string& selectedImage,
std::string_view disabledImage, const std::string& disabledImage,
const ccMenuCallback& callback) const ccMenuCallback& callback)
{ {
Node* normalSprite = nullptr; Node* normalSprite = nullptr;

View File

@ -137,10 +137,10 @@ public:
static MenuItemLabel* create(Node* label); static MenuItemLabel* create(Node* label);
/** Sets a new string to the inner label. */ /** Sets a new string to the inner label. */
void setString(std::string_view label); void setString(const std::string& label);
/** Get the inner string of the inner label. */ /** Get the inner string of the inner label. */
std::string_view getString() const; std::string getString() const;
/** Gets the color that will be used when the item is disabled. */ /** Gets the color that will be used when the item is disabled. */
const Color3B& getDisabledColor() const { return _disabledColor; } const Color3B& getDisabledColor() const { return _disabledColor; }
@ -196,14 +196,14 @@ class CC_DLL MenuItemAtlasFont : public MenuItemLabel
{ {
public: public:
/** Creates a menu item from a string and atlas with a target/selector. */ /** Creates a menu item from a string and atlas with a target/selector. */
static MenuItemAtlasFont* create(std::string_view value, static MenuItemAtlasFont* create(const std::string& value,
std::string_view charMapFile, const std::string& charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
char startCharMap); char startCharMap);
/** Creates a menu item from a string and atlas. Use it with MenuItemToggle. */ /** Creates a menu item from a string and atlas. Use it with MenuItemToggle. */
static MenuItemAtlasFont* create(std::string_view value, static MenuItemAtlasFont* create(const std::string& value,
std::string_view charMapFile, const std::string& charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
char startCharMap, char startCharMap,
@ -222,8 +222,8 @@ public:
virtual ~MenuItemAtlasFont() {} virtual ~MenuItemAtlasFont() {}
/** Initializes a menu item from a string and atlas with a target/selector. */ /** Initializes a menu item from a string and atlas with a target/selector. */
bool initWithString(std::string_view value, bool initWithString(const std::string& value,
std::string_view charMapFile, const std::string& charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
char startCharMap, char startCharMap,
@ -240,18 +240,18 @@ class CC_DLL MenuItemFont : public MenuItemLabel
{ {
public: public:
/** Creates a menu item from a string without target/selector. To be used with MenuItemToggle. */ /** Creates a menu item from a string without target/selector. To be used with MenuItemToggle. */
static MenuItemFont* create(std::string_view value = ""); static MenuItemFont* create(const std::string& value = "");
/** Creates a menu item from a string with a target/selector. */ /** Creates a menu item from a string with a target/selector. */
static MenuItemFont* create(std::string_view value, const ccMenuCallback& callback); static MenuItemFont* create(const std::string& value, const ccMenuCallback& callback);
/** Set default font size. */ /** Set default font size. */
static void setFontSize(int size); static void setFontSize(int size);
/** Get default font size. */ /** Get default font size. */
static int getFontSize(); static int getFontSize();
/** Set the default font name. */ /** Set the default font name. */
static void setFontName(std::string_view name); static void setFontName(const std::string& name);
/** Get the default font name. */ /** Get the default font name. */
static std::string_view getFontName(); static const std::string& getFontName();
/** Set font size. /** Set font size.
* c++ can not overload static and non-static member functions with the same parameter types. * c++ can not overload static and non-static member functions with the same parameter types.
@ -274,13 +274,13 @@ public:
* @js setFontName * @js setFontName
* @js NA * @js NA
*/ */
void setFontNameObj(std::string_view name); void setFontNameObj(const std::string& name);
/** Returns the name of the Font. /** Returns the name of the Font.
* @js getFontNameObj * @js getFontNameObj
* @js NA * @js NA
*/ */
std::string_view getFontNameObj() const; const std::string& getFontNameObj() const;
CC_CONSTRUCTOR_ACCESS : CC_CONSTRUCTOR_ACCESS :
/** /**
@ -294,7 +294,7 @@ public:
virtual ~MenuItemFont(); virtual ~MenuItemFont();
/** Initializes a menu item from a string with a target/selector. */ /** Initializes a menu item from a string with a target/selector. */
bool initWithString(std::string_view value, const ccMenuCallback& callback); bool initWithString(const std::string& value, const ccMenuCallback& callback);
protected: protected:
int _fontSize; int _fontSize;
@ -392,19 +392,19 @@ public:
/** Creates an MenuItemImage. */ /** Creates an MenuItemImage. */
static MenuItemImage* create(); static MenuItemImage* create();
/** Creates a menu item with a normal and selected image.*/ /** Creates a menu item with a normal and selected image.*/
static MenuItemImage* create(std::string_view normalImage, std::string_view selectedImage); static MenuItemImage* create(const std::string& normalImage, const std::string& selectedImage);
/** Creates a menu item with a normal,selected and disabled image.*/ /** Creates a menu item with a normal,selected and disabled image.*/
static MenuItemImage* create(std::string_view normalImage, static MenuItemImage* create(const std::string& normalImage,
std::string_view selectedImage, const std::string& selectedImage,
std::string_view disabledImage); const std::string& disabledImage);
/** Creates a menu item with a normal and selected image with a callable object. */ /** Creates a menu item with a normal and selected image with a callable object. */
static MenuItemImage* create(std::string_view normalImage, static MenuItemImage* create(const std::string& normalImage,
std::string_view selectedImage, const std::string& selectedImage,
const ccMenuCallback& callback); const ccMenuCallback& callback);
/** Creates a menu item with a normal,selected and disabled image with a callable object. */ /** Creates a menu item with a normal,selected and disabled image with a callable object. */
static MenuItemImage* create(std::string_view normalImage, static MenuItemImage* create(const std::string& normalImage,
std::string_view selectedImage, const std::string& selectedImage,
std::string_view disabledImage, const std::string& disabledImage,
const ccMenuCallback& callback); const ccMenuCallback& callback);
/** Sets the sprite frame for the normal image. */ /** Sets the sprite frame for the normal image. */
@ -429,9 +429,9 @@ public:
bool init(); bool init();
/** Initializes a menu item with a normal, selected and disabled image with a callable object. */ /** Initializes a menu item with a normal, selected and disabled image with a callable object. */
bool initWithNormalImage(std::string_view normalImage, bool initWithNormalImage(const std::string& normalImage,
std::string_view selectedImage, const std::string& selectedImage,
std::string_view disabledImage, const std::string& disabledImage,
const ccMenuCallback& callback); const ccMenuCallback& callback);
private: private:

View File

@ -52,7 +52,11 @@ MotionStreak::~MotionStreak()
CC_SAFE_FREE(_texCoords); CC_SAFE_FREE(_texCoords);
} }
MotionStreak* MotionStreak::create(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path) MotionStreak* MotionStreak::create(float fade,
float minSeg,
float stroke,
const Color3B& color,
const std::string& path)
{ {
MotionStreak* ret = new MotionStreak(); MotionStreak* ret = new MotionStreak();
if (ret->initWithFade(fade, minSeg, stroke, color, path)) if (ret->initWithFade(fade, minSeg, stroke, color, path))
@ -78,7 +82,7 @@ MotionStreak* MotionStreak::create(float fade, float minSeg, float stroke, const
return nullptr; return nullptr;
} }
bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path) bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path)
{ {
CCASSERT(!path.empty(), "Invalid filename"); CCASSERT(!path.empty(), "Invalid filename");

View File

@ -59,7 +59,7 @@ public:
float minSeg, float minSeg,
float strokeWidth, float strokeWidth,
const Color3B& strokeColor, const Color3B& strokeColor,
std::string_view imagePath); const std::string& imagePath);
/** Creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture. /** Creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture.
* *
* @param timeToFade The fade time, in seconds. * @param timeToFade The fade time, in seconds.
@ -163,7 +163,7 @@ public:
/** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename
*/ */
bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path); bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path);
/** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */ /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */
bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture); bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture);

View File

@ -56,7 +56,7 @@ THE SOFTWARE.
/* /*
* 4.5x faster than std::hash in release mode * 4.5x faster than std::hash in release mode
*/ */
#define CC_HASH_NODE_NAME(name) (!name.empty() ? XXH3_64bits(name.data(), name.length()) : 0) #define CC_HASH_NODE_NAME(name) (!name.empty() ? XXH3_64bits(name.c_str(), name.length()) : 0)
NS_CC_BEGIN NS_CC_BEGIN
@ -695,12 +695,12 @@ void Node::setTag(int tag)
_tag = tag; _tag = tag;
} }
std::string_view Node::getName() const const std::string& Node::getName() const
{ {
return _name; return _name;
} }
void Node::setName(std::string_view name) void Node::setName(const std::string& name)
{ {
updateParentChildrenIndexer(name); updateParentChildrenIndexer(name);
_name = name; _name = name;
@ -717,7 +717,7 @@ void Node::updateParentChildrenIndexer(int tag)
} }
} }
void Node::updateParentChildrenIndexer(std::string_view name) void Node::updateParentChildrenIndexer(const std::string& name)
{ {
uint64_t newHash = CC_HASH_NODE_NAME(name); uint64_t newHash = CC_HASH_NODE_NAME(name);
auto parentChildrenIndexer = getParentChildrenIndexer(); auto parentChildrenIndexer = getParentChildrenIndexer();
@ -817,7 +817,7 @@ Node* Node::getChildByTag(int tag) const
return nullptr; return nullptr;
} }
Node* Node::getChildByName(std::string_view name) const Node* Node::getChildByName(const std::string& name) const
{ {
// CCASSERT(!name.empty(), "Invalid name"); // CCASSERT(!name.empty(), "Invalid name");
auto hash = CC_HASH_NODE_NAME(name); auto hash = CC_HASH_NODE_NAME(name);
@ -837,7 +837,7 @@ Node* Node::getChildByName(std::string_view name) const
return nullptr; return nullptr;
} }
void Node::enumerateChildren(std::string_view name, std::function<bool(Node*)> callback) const void Node::enumerateChildren(const std::string& name, std::function<bool(Node*)> callback) const
{ {
CCASSERT(!name.empty(), "Invalid name"); CCASSERT(!name.empty(), "Invalid name");
CCASSERT(callback != nullptr, "Invalid callback function"); CCASSERT(callback != nullptr, "Invalid callback function");
@ -865,7 +865,7 @@ void Node::enumerateChildren(std::string_view name, std::function<bool(Node*)> c
} }
// Remove '//', '/..' if exist // Remove '//', '/..' if exist
auto newName = name.substr(subStrStartPos, subStrlength); std::string newName = name.substr(subStrStartPos, subStrlength);
const Node* target = this; const Node* target = this;
@ -886,15 +886,15 @@ void Node::enumerateChildren(std::string_view name, std::function<bool(Node*)> c
else else
{ {
// name is xxx // name is xxx
target->doEnumerate(std::string{newName}, callback); target->doEnumerate(newName, callback);
} }
} }
bool Node::doEnumerateRecursive(const Node* node, std::string_view name, std::function<bool(Node*)> callback) const bool Node::doEnumerateRecursive(const Node* node, const std::string& name, std::function<bool(Node*)> callback) const
{ {
bool ret = false; bool ret = false;
if (node->doEnumerate(std::string{name}, callback)) if (node->doEnumerate(name, callback))
{ {
// search itself // search itself
ret = true; ret = true;
@ -966,7 +966,7 @@ void Node::addChild(Node* child, int localZOrder, int tag)
addChildHelper(child, localZOrder, tag, "", true); addChildHelper(child, localZOrder, tag, "", true);
} }
void Node::addChild(Node* child, int localZOrder, std::string_view name) void Node::addChild(Node* child, int localZOrder, const std::string& name)
{ {
CCASSERT(child != nullptr, "Argument must be non-nil"); CCASSERT(child != nullptr, "Argument must be non-nil");
CCASSERT(child->_parent == nullptr, "child already added. It can't be added again"); CCASSERT(child->_parent == nullptr, "child already added. It can't be added again");
@ -974,7 +974,7 @@ void Node::addChild(Node* child, int localZOrder, std::string_view name)
addChildHelper(child, localZOrder, INVALID_TAG, name, false); addChildHelper(child, localZOrder, INVALID_TAG, name, false);
} }
void Node::addChildHelper(Node* child, int localZOrder, int tag, std::string_view name, bool setTag) void Node::addChildHelper(Node* child, int localZOrder, int tag, const std::string& name, bool setTag)
{ {
auto assertNotSelfChild([this, child]() -> bool { auto assertNotSelfChild([this, child]() -> bool {
for (Node* parent(getParent()); parent != nullptr; parent = parent->getParent()) for (Node* parent(getParent()); parent != nullptr; parent = parent->getParent())
@ -1088,7 +1088,7 @@ void Node::removeChildByTag(int tag, bool cleanup /* = true */)
} }
} }
void Node::removeChildByName(std::string_view name, bool cleanup) void Node::removeChildByName(const std::string& name, bool cleanup)
{ {
CCASSERT(!name.empty(), "Invalid name"); CCASSERT(!name.empty(), "Invalid name");
@ -1096,7 +1096,7 @@ void Node::removeChildByName(std::string_view name, bool cleanup)
if (child == nullptr) if (child == nullptr)
{ {
CCLOG("cocos2d: removeChildByName(name = %s): child not found!", name.data()); CCLOG("cocos2d: removeChildByName(name = %s): child not found!", name.c_str());
} }
else else
{ {
@ -1490,7 +1490,7 @@ bool Node::isScheduled(SEL_SCHEDULE selector) const
return _scheduler->isScheduled(selector, this); return _scheduler->isScheduled(selector, this);
} }
bool Node::isScheduled(std::string_view key) const bool Node::isScheduled(const std::string& key) const
{ {
return _scheduler->isScheduled(key, this); return _scheduler->isScheduled(key, this);
} }
@ -1547,12 +1547,12 @@ void Node::schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat,
_scheduler->schedule(selector, this, interval, repeat, delay, !_running); _scheduler->schedule(selector, this, interval, repeat, delay, !_running);
} }
void Node::schedule(const std::function<void(float)>& callback, std::string_view key) void Node::schedule(const std::function<void(float)>& callback, const std::string& key)
{ {
_scheduler->schedule(callback, this, 0, !_running, key); _scheduler->schedule(callback, this, 0, !_running, key);
} }
void Node::schedule(const std::function<void(float)>& callback, float interval, std::string_view key) void Node::schedule(const std::function<void(float)>& callback, float interval, const std::string& key)
{ {
_scheduler->schedule(callback, this, interval, !_running, key); _scheduler->schedule(callback, this, interval, !_running, key);
} }
@ -1561,7 +1561,7 @@ void Node::schedule(const std::function<void(float)>& callback,
float interval, float interval,
unsigned int repeat, unsigned int repeat,
float delay, float delay,
std::string_view key) const std::string& key)
{ {
_scheduler->schedule(callback, this, interval, repeat, delay, !_running, key); _scheduler->schedule(callback, this, interval, repeat, delay, !_running, key);
} }
@ -1571,7 +1571,7 @@ void Node::scheduleOnce(SEL_SCHEDULE selector, float delay)
this->schedule(selector, 0.0f, 0, delay); this->schedule(selector, 0.0f, 0, delay);
} }
void Node::scheduleOnce(const std::function<void(float)>& callback, float delay, std::string_view key) void Node::scheduleOnce(const std::function<void(float)>& callback, float delay, const std::string& key)
{ {
_scheduler->schedule(callback, this, 0, 0, delay, !_running, key); _scheduler->schedule(callback, this, 0, 0, delay, !_running, key);
} }
@ -1585,7 +1585,7 @@ void Node::unschedule(SEL_SCHEDULE selector)
_scheduler->unschedule(selector, this); _scheduler->unschedule(selector, this);
} }
void Node::unschedule(std::string_view key) void Node::unschedule(const std::string& key)
{ {
_scheduler->unschedule(key, this); _scheduler->unschedule(key, this);
} }
@ -1923,7 +1923,7 @@ void Node::updateTransform()
// MARK: components // MARK: components
Component* Node::getComponent(std::string_view name) Component* Node::getComponent(const std::string& name)
{ {
if (_componentContainer) if (_componentContainer)
return _componentContainer->get(name); return _componentContainer->get(name);
@ -1943,7 +1943,7 @@ bool Node::addComponent(Component* component)
return _componentContainer->add(component); return _componentContainer->add(component);
} }
bool Node::removeComponent(std::string_view name) bool Node::removeComponent(const std::string& name)
{ {
if (_componentContainer) if (_componentContainer)
return _componentContainer->remove(name); return _componentContainer->remove(name);

View File

@ -762,7 +762,7 @@ public:
* @param name A string to identify the node easily. Please refer to `setName(int)`. * @param name A string to identify the node easily. Please refer to `setName(int)`.
* *
*/ */
virtual void addChild(Node* child, int localZOrder, std::string_view name); virtual void addChild(Node* child, int localZOrder, const std::string& name);
/** /**
* Gets a child from the container with its tag. * Gets a child from the container with its tag.
* *
@ -796,7 +796,7 @@ public:
* *
* @since v3.2 * @since v3.2
*/ */
virtual Node* getChildByName(std::string_view name) const; virtual Node* getChildByName(const std::string& name) const;
/** /**
* Gets a child from the container with its name that can be cast to Type T. * Gets a child from the container with its name that can be cast to Type T.
* *
@ -805,7 +805,7 @@ public:
* @return a Node with the given name that can be cast to Type T. * @return a Node with the given name that can be cast to Type T.
*/ */
template <typename T> template <typename T>
T getChildByName(std::string_view name) const T getChildByName(const std::string& name) const
{ {
return static_cast<T>(getChildByName(name)); return static_cast<T>(getChildByName(name));
} }
@ -835,7 +835,7 @@ public:
* *
* @since v3.2 * @since v3.2
*/ */
virtual void enumerateChildren(std::string_view name, std::function<bool(Node* node)> callback) const; virtual void enumerateChildren(const std::string& name, std::function<bool(Node* node)> callback) const;
/** /**
* Returns the array of the node's children. * Returns the array of the node's children.
* *
@ -909,7 +909,7 @@ public:
* @param name A string that identifies a child node. * @param name A string that identifies a child node.
* @param cleanup True if all running actions and callbacks on the child node will be cleanup, false otherwise. * @param cleanup True if all running actions and callbacks on the child node will be cleanup, false otherwise.
*/ */
virtual void removeChildByName(std::string_view name, bool cleanup = true); virtual void removeChildByName(const std::string& name, bool cleanup = true);
/** /**
* Removes all children from the container with a cleanup. * Removes all children from the container with a cleanup.
* *
@ -989,13 +989,13 @@ public:
* *
* @since v3.2 * @since v3.2
*/ */
virtual std::string_view getName() const; virtual const std::string& getName() const;
/** Changes the name that is used to identify the node easily. /** Changes the name that is used to identify the node easily.
* @param name A string that identifies the node. * @param name A string that identifies the node.
* *
* @since v3.2 * @since v3.2
*/ */
virtual void setName(std::string_view name); virtual void setName(const std::string& name);
/** /**
* Returns a custom user data pointer. * Returns a custom user data pointer.
@ -1306,7 +1306,7 @@ public:
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
bool isScheduled(std::string_view key) const; bool isScheduled(const std::string& key) const;
/** /**
* Schedules the "update" method. * Schedules the "update" method.
@ -1385,7 +1385,7 @@ public:
* @param key The key of the lambda function. To be used if you want to unschedule it. * @param key The key of the lambda function. To be used if you want to unschedule it.
* @lua NA * @lua NA
*/ */
void scheduleOnce(const std::function<void(float)>& callback, float delay, std::string_view key); void scheduleOnce(const std::function<void(float)>& callback, float delay, const std::string& key);
/** /**
* Schedules a custom selector, the scheduled selector will be ticked every frame. * Schedules a custom selector, the scheduled selector will be ticked every frame.
@ -1403,7 +1403,7 @@ public:
* @param key The key of the lambda function. To be used if you want to unschedule it. * @param key The key of the lambda function. To be used if you want to unschedule it.
* @lua NA * @lua NA
*/ */
void schedule(const std::function<void(float)>& callback, std::string_view key); void schedule(const std::function<void(float)>& callback, const std::string& key);
/** /**
* Schedules a lambda function. The scheduled lambda function will be called every "interval" seconds * Schedules a lambda function. The scheduled lambda function will be called every "interval" seconds
@ -1413,7 +1413,7 @@ public:
* @param key The key of the lambda function. To be used if you want to unschedule it * @param key The key of the lambda function. To be used if you want to unschedule it
* @lua NA * @lua NA
*/ */
void schedule(const std::function<void(float)>& callback, float interval, std::string_view key); void schedule(const std::function<void(float)>& callback, float interval, const std::string& key);
/** /**
* Schedules a lambda function. * Schedules a lambda function.
@ -1430,7 +1430,7 @@ public:
float interval, float interval,
unsigned int repeat, unsigned int repeat,
float delay, float delay,
std::string_view key); const std::string& key);
/** /**
* Unschedules a custom selector. * Unschedules a custom selector.
@ -1447,7 +1447,7 @@ public:
* @param key The key of the lambda function to be unscheduled. * @param key The key of the lambda function to be unscheduled.
* @lua NA * @lua NA
*/ */
void unschedule(std::string_view key); void unschedule(const std::string& key);
/** /**
* Unschedule all scheduled selectors and lambda functions: custom selectors, and the 'update' selector and lambda * Unschedule all scheduled selectors and lambda functions: custom selectors, and the 'update' selector and lambda
@ -1633,7 +1633,7 @@ public:
* @param name A given name of component. * @param name A given name of component.
* @return The Component by name. * @return The Component by name.
*/ */
Component* getComponent(std::string_view name); Component* getComponent(const std::string& name);
/** /**
* Adds a component. * Adds a component.
@ -1649,7 +1649,7 @@ public:
* @param name A given name of component. * @param name A given name of component.
* @return True if removed success. * @return True if removed success.
*/ */
virtual bool removeComponent(std::string_view name); virtual bool removeComponent(const std::string& name);
/** /**
* Removes a component by its pointer. * Removes a component by its pointer.
@ -1854,7 +1854,7 @@ protected:
virtual void updateColor() {} virtual void updateColor() {}
bool doEnumerate(std::string name, std::function<bool(Node*)> callback) const; bool doEnumerate(std::string name, std::function<bool(Node*)> callback) const;
bool doEnumerateRecursive(const Node* node, std::string_view name, std::function<bool(Node*)> callback) const; bool doEnumerateRecursive(const Node* node, const std::string& name, std::function<bool(Node*)> callback) const;
// check whether this camera mask is visible by the current visiting camera // check whether this camera mask is visible by the current visiting camera
bool isVisitableByVisitingCamera() const; bool isVisitableByVisitingCamera() const;
@ -1865,10 +1865,10 @@ protected:
void updateRotation3D(); void updateRotation3D();
void updateParentChildrenIndexer(int tag); void updateParentChildrenIndexer(int tag);
void updateParentChildrenIndexer(std::string_view name); void updateParentChildrenIndexer(const std::string& name);
private: private:
void addChildHelper(Node* child, int localZOrder, int tag, std::string_view name, bool setTag); void addChildHelper(Node* child, int localZOrder, int tag, const std::string& name, bool setTag);
NodeIndexerMap_t* getParentChildrenIndexer(); NodeIndexerMap_t* getParentChildrenIndexer();

View File

@ -91,7 +91,7 @@ void ParallaxNode::addChild(Node* /*child*/, int /*zOrder*/, int /*tag*/)
CCASSERT(0, "ParallaxNode: use addChild:z:parallaxRatio:positionOffset instead"); CCASSERT(0, "ParallaxNode: use addChild:z:parallaxRatio:positionOffset instead");
} }
void ParallaxNode::addChild(Node* /*child*/, int /*zOrder*/, std::string_view /*name*/) void ParallaxNode::addChild(Node* /*child*/, int /*zOrder*/, const std::string& /*name*/)
{ {
CCASSERT(0, "ParallaxNode: use addChild:z:parallaxRatio:positionOffset instead"); CCASSERT(0, "ParallaxNode: use addChild:z:parallaxRatio:positionOffset instead");
} }

View File

@ -83,7 +83,7 @@ public:
// Overrides // Overrides
// //
virtual void addChild(Node* child, int zOrder, int tag) override; virtual void addChild(Node* child, int zOrder, int tag) override;
virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void addChild(Node* child, int zOrder, const std::string& name) override;
virtual void removeChild(Node* child, bool cleanup) override; virtual void removeChild(Node* child, bool cleanup) override;
virtual void removeAllChildrenWithCleanup(bool cleanup) override; virtual void removeAllChildrenWithCleanup(bool cleanup) override;
virtual void visit(Renderer* renderer, const Mat4& parentTransform, uint32_t parentFlags) override; virtual void visit(Renderer* renderer, const Mat4& parentTransform, uint32_t parentFlags) override;

View File

@ -108,7 +108,7 @@ ParticleBatchNode* ParticleBatchNode::createWithTexture(Texture2D* tex, int capa
* creation with File Image * creation with File Image
*/ */
ParticleBatchNode* ParticleBatchNode::create(std::string_view imageFile, int capacity /* = kParticleDefaultCapacity*/) ParticleBatchNode* ParticleBatchNode::create(const std::string& imageFile, int capacity /* = kParticleDefaultCapacity*/)
{ {
ParticleBatchNode* p = new ParticleBatchNode(); ParticleBatchNode* p = new ParticleBatchNode();
if (p->initWithFile(imageFile, capacity)) if (p->initWithFile(imageFile, capacity))
@ -140,7 +140,7 @@ bool ParticleBatchNode::initWithTexture(Texture2D* tex, int capacity)
/* /*
* init with FileImage * init with FileImage
*/ */
bool ParticleBatchNode::initWithFile(std::string_view fileImage, int capacity) bool ParticleBatchNode::initWithFile(const std::string& fileImage, int capacity)
{ {
Texture2D* tex = _director->getTextureCache()->addImage(fileImage); Texture2D* tex = _director->getTextureCache()->addImage(fileImage);
return initWithTexture(tex, capacity); return initWithTexture(tex, capacity);
@ -193,7 +193,7 @@ void ParticleBatchNode::addChild(Node* aChild, int zOrder, int tag)
addChildByTagOrName(child, zOrder, tag, "", true); addChildByTagOrName(child, zOrder, tag, "", true);
} }
void ParticleBatchNode::addChild(Node* aChild, int zOrder, std::string_view name) void ParticleBatchNode::addChild(Node* aChild, int zOrder, const std::string& name)
{ {
CCASSERT(aChild != nullptr, "Argument must be non-nullptr"); CCASSERT(aChild != nullptr, "Argument must be non-nullptr");
CCASSERT(dynamic_cast<ParticleSystem*>(aChild) != nullptr, CCASSERT(dynamic_cast<ParticleSystem*>(aChild) != nullptr,
@ -208,7 +208,7 @@ void ParticleBatchNode::addChild(Node* aChild, int zOrder, std::string_view name
void ParticleBatchNode::addChildByTagOrName(ParticleSystem* child, void ParticleBatchNode::addChildByTagOrName(ParticleSystem* child,
int zOrder, int zOrder,
int tag, int tag,
std::string_view name, const std::string& name,
bool setTag) bool setTag)
{ {
// If this is the 1st children, then copy blending function // If this is the 1st children, then copy blending function
@ -251,7 +251,7 @@ void ParticleBatchNode::addChildByTagOrName(ParticleSystem* child,
// faster // faster
// FIXME: or possibly using vertexZ for reordering, that would be fastest // FIXME: or possibly using vertexZ for reordering, that would be fastest
// this helper is almost equivalent to Node's addChild, but doesn't make use of the lazy sorting // this helper is almost equivalent to Node's addChild, but doesn't make use of the lazy sorting
int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag, std::string_view name, bool setTag) int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag, const std::string& name, bool setTag)
{ {
CCASSERT(child != nullptr, "Argument must be non-nil"); CCASSERT(child != nullptr, "Argument must be non-nil");
CCASSERT(child->getParent() == nullptr, "child already added. It can't be added again"); CCASSERT(child->getParent() == nullptr, "child already added. It can't be added again");

View File

@ -87,7 +87,7 @@ public:
* @param capacity A capacity of particles. * @param capacity A capacity of particles.
* @return An autoreleased ParticleBatchNode object. * @return An autoreleased ParticleBatchNode object.
*/ */
static ParticleBatchNode* create(std::string_view fileImage, int capacity = kParticleDefaultCapacity); static ParticleBatchNode* create(const std::string& fileImage, int capacity = kParticleDefaultCapacity);
/** Inserts a child into the ParticleBatchNode. /** Inserts a child into the ParticleBatchNode.
* *
@ -127,7 +127,7 @@ public:
using Node::addChild; using Node::addChild;
virtual void addChild(Node* child, int zOrder, int tag) override; virtual void addChild(Node* child, int zOrder, int tag) override;
virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void addChild(Node* child, int zOrder, const std::string& name) override;
virtual void removeChild(Node* child, bool cleanup) override; virtual void removeChild(Node* child, bool cleanup) override;
virtual void reorderChild(Node* child, int zOrder) override; virtual void reorderChild(Node* child, int zOrder) override;
virtual void draw(Renderer* renderer, const Mat4& transform, uint32_t flags) override; virtual void draw(Renderer* renderer, const Mat4& transform, uint32_t flags) override;
@ -163,15 +163,15 @@ public:
/** initializes the particle system with the name of a file on disk (for a list of supported formats look at the /** initializes the particle system with the name of a file on disk (for a list of supported formats look at the
* Texture2D class), a capacity of particles */ * Texture2D class), a capacity of particles */
bool initWithFile(std::string_view fileImage, int capacity); bool initWithFile(const std::string& fileImage, int capacity);
private: private:
void updateAllAtlasIndexes(); void updateAllAtlasIndexes();
void increaseAtlasCapacityTo(ssize_t quantity); void increaseAtlasCapacityTo(ssize_t quantity);
int searchNewPositionInChildrenForZ(int z); int searchNewPositionInChildrenForZ(int z);
void getCurrentIndex(int* oldIndex, int* newIndex, Node* child, int z); void getCurrentIndex(int* oldIndex, int* newIndex, Node* child, int z);
int addChildHelper(ParticleSystem* child, int z, int aTag, std::string_view name, bool setTag); int addChildHelper(ParticleSystem* child, int z, int aTag, const std::string& name, bool setTag);
void addChildByTagOrName(ParticleSystem* child, int z, int tag, std::string_view name, bool setTag); void addChildByTagOrName(ParticleSystem* child, int z, int tag, const std::string& name, bool setTag);
void updateBlendFunc(); void updateBlendFunc();
void updateProgramStateTexture(); void updateProgramStateTexture();

View File

@ -191,6 +191,11 @@ void ParticleData::release()
Vector<ParticleSystem*> ParticleSystem::__allInstances; Vector<ParticleSystem*> ParticleSystem::__allInstances;
float ParticleSystem::__totalParticleCountFactor = 1.0f; float ParticleSystem::__totalParticleCountFactor = 1.0f;
inline static const cocos2d::Value& optValue(const ValueMap& dictionary, const std::string& key)
{
return dictionary.find(key) != dictionary.cend() ? dictionary.at(key) : cocos2d::Value::Null;
}
ParticleSystem::ParticleSystem() ParticleSystem::ParticleSystem()
: _isBlendAdditive(false) : _isBlendAdditive(false)
, _isAutoRemoveOnFinish(false) , _isAutoRemoveOnFinish(false)
@ -245,7 +250,7 @@ ParticleSystem::ParticleSystem()
} }
// implementation ParticleSystem // implementation ParticleSystem
ParticleSystem* ParticleSystem::create(std::string_view plistFile) ParticleSystem* ParticleSystem::create(const std::string& plistFile)
{ {
ParticleSystem* ret = new ParticleSystem(); ParticleSystem* ret = new ParticleSystem();
if (ret->initWithFile(plistFile)) if (ret->initWithFile(plistFile))
@ -285,7 +290,7 @@ bool ParticleSystem::init()
return initWithTotalParticles(150); return initWithTotalParticles(150);
} }
bool ParticleSystem::initWithFile(std::string_view plistFile) bool ParticleSystem::initWithFile(const std::string& plistFile)
{ {
bool ret = false; bool ret = false;
_plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile); _plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile);
@ -294,7 +299,7 @@ bool ParticleSystem::initWithFile(std::string_view plistFile)
CCASSERT(!dict.empty(), "Particles: file not found"); CCASSERT(!dict.empty(), "Particles: file not found");
// FIXME: compute path from a path, should define a function somewhere to do it // FIXME: compute path from a path, should define a function somewhere to do it
auto listFilePath = plistFile; string listFilePath = plistFile;
if (listFilePath.find('/') != string::npos) if (listFilePath.find('/') != string::npos)
{ {
listFilePath = listFilePath.substr(0, listFilePath.rfind('/') + 1); listFilePath = listFilePath.substr(0, listFilePath.rfind('/') + 1);
@ -313,7 +318,7 @@ bool ParticleSystem::initWithDictionary(const ValueMap& dictionary)
return initWithDictionary(dictionary, ""); return initWithDictionary(dictionary, "");
} }
bool ParticleSystem::initWithDictionary(const ValueMap& dictionary, std::string_view dirname) bool ParticleSystem::initWithDictionary(const ValueMap& dictionary, const std::string& dirname)
{ {
bool ret = false; bool ret = false;
unsigned char* buffer = nullptr; unsigned char* buffer = nullptr;
@ -482,12 +487,12 @@ bool ParticleSystem::initWithDictionary(const ValueMap& dictionary, std::string_
if (!dirname.empty() && textureDir != dirname) if (!dirname.empty() && textureDir != dirname)
{ {
textureName = textureName.substr(rPos + 1); textureName = textureName.substr(rPos + 1);
textureName.insert(0, dirname); // textureName = dirname + textureName; textureName = dirname + textureName;
} }
} }
else if (!dirname.empty() && !textureName.empty()) else if (!dirname.empty() && !textureName.empty())
{ {
textureName.insert(0, dirname); // textureName = dirname + textureName; textureName = dirname + textureName;
} }
Texture2D* tex = nullptr; Texture2D* tex = nullptr;

View File

@ -237,7 +237,7 @@ public:
* @param plistFile Particle plist file name. * @param plistFile Particle plist file name.
* @return An autoreleased ParticleSystem object. * @return An autoreleased ParticleSystem object.
*/ */
static ParticleSystem* create(std::string_view plistFile); static ParticleSystem* create(const std::string& plistFile);
/** Create a system with a fixed number of particles. /** Create a system with a fixed number of particles.
* *
@ -761,7 +761,7 @@ public:
*/ */
virtual const BlendFunc& getBlendFunc() const override; virtual const BlendFunc& getBlendFunc() const override;
std::string_view getResourceFile() const { return _plistFile; } const std::string& getResourceFile() const { return _plistFile; }
/// @{ /// @{
/// @name implement Playable Protocol /// @name implement Playable Protocol
@ -793,7 +793,7 @@ public:
http://particledesigner.71squared.com/ http://particledesigner.71squared.com/
@since v0.99.3 @since v0.99.3
*/ */
bool initWithFile(std::string_view plistFile); bool initWithFile(const std::string& plistFile);
/** initializes a QuadParticleSystem from a Dictionary. /** initializes a QuadParticleSystem from a Dictionary.
@since v0.99.3 @since v0.99.3
@ -803,7 +803,7 @@ public:
/** initializes a particle system from a NSDictionary and the path from where to load the png /** initializes a particle system from a NSDictionary and the path from where to load the png
@since v2.1 @since v2.1
*/ */
bool initWithDictionary(const ValueMap& dictionary, std::string_view dirname); bool initWithDictionary(const ValueMap& dictionary, const std::string& dirname);
//! Initializes a system with a fixed number of particles //! Initializes a system with a fixed number of particles
virtual bool initWithTotalParticles(int numberOfParticles); virtual bool initWithTotalParticles(int numberOfParticles);

View File

@ -91,7 +91,7 @@ ParticleSystemQuad::~ParticleSystemQuad()
// implementation ParticleSystemQuad // implementation ParticleSystemQuad
ParticleSystemQuad* ParticleSystemQuad::create(std::string_view filename) ParticleSystemQuad* ParticleSystemQuad::create(const std::string& filename)
{ {
ParticleSystemQuad* ret = new ParticleSystemQuad(); ParticleSystemQuad* ret = new ParticleSystemQuad();
if (ret->initWithFile(filename)) if (ret->initWithFile(filename))

View File

@ -75,7 +75,7 @@ public:
* @param filename Particle plist file name. * @param filename Particle plist file name.
* @return An autoreleased ParticleSystemQuad object. * @return An autoreleased ParticleSystemQuad object.
*/ */
static ParticleSystemQuad* create(std::string_view filename); static ParticleSystemQuad* create(const std::string& filename);
/** Creates a Particle Emitter with a dictionary. /** Creates a Particle Emitter with a dictionary.
* *
* @param dictionary Particle dictionary. * @param dictionary Particle dictionary.

View File

@ -18,7 +18,7 @@ using namespace std;
NS_CC_BEGIN NS_CC_BEGIN
void PlistSpriteSheetLoader::load(std::string_view filePath, SpriteFrameCache& cache) void PlistSpriteSheetLoader::load(const std::string& filePath, SpriteFrameCache& cache)
{ {
CCASSERT(!filePath.empty(), "plist filename should not be nullptr"); CCASSERT(!filePath.empty(), "plist filename should not be nullptr");
@ -26,7 +26,7 @@ void PlistSpriteSheetLoader::load(std::string_view filePath, SpriteFrameCache& c
if (fullPath.empty()) if (fullPath.empty())
{ {
// return if plist file doesn't exist // return if plist file doesn't exist
CCLOG("cocos2d: SpriteFrameCache: can not find %s", filePath.data()); CCLOG("cocos2d: SpriteFrameCache: can not find %s", filePath.c_str());
return; return;
} }
@ -66,7 +66,7 @@ void PlistSpriteSheetLoader::load(std::string_view filePath, SpriteFrameCache& c
addSpriteFramesWithDictionary(dict, texturePath, filePath, cache); addSpriteFramesWithDictionary(dict, texturePath, filePath, cache);
} }
void PlistSpriteSheetLoader::load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) void PlistSpriteSheetLoader::load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache)
{ {
const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
@ -74,7 +74,9 @@ void PlistSpriteSheetLoader::load(std::string_view filePath, Texture2D* texture,
addSpriteFramesWithDictionary(dict, texture, filePath, cache); addSpriteFramesWithDictionary(dict, texture, filePath, cache);
} }
void PlistSpriteSheetLoader::load(std::string_view filePath, std::string_view textureFileName, SpriteFrameCache& cache) void PlistSpriteSheetLoader::load(const std::string& filePath,
const std::string& textureFileName,
SpriteFrameCache& cache)
{ {
CCASSERT(!textureFileName.empty(), "texture name should not be null"); CCASSERT(!textureFileName.empty(), "texture name should not be null");
const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
@ -96,7 +98,7 @@ void PlistSpriteSheetLoader::load(const Data& content, Texture2D* texture, Sprit
addSpriteFramesWithDictionary(dict, texture, "by#addSpriteFramesWithFileContent()", cache); addSpriteFramesWithDictionary(dict, texture, "by#addSpriteFramesWithFileContent()", cache);
} }
void PlistSpriteSheetLoader::reload(std::string_view filePath, SpriteFrameCache& cache) void PlistSpriteSheetLoader::reload(const std::string& filePath, SpriteFrameCache& cache)
{ {
const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
@ -149,7 +151,7 @@ void PlistSpriteSheetLoader::reload(std::string_view filePath, SpriteFrameCache&
void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary,
Texture2D* texture, Texture2D* texture,
std::string_view plist, const std::string& plist,
SpriteFrameCache& cache) SpriteFrameCache& cache)
{ {
/* /*
@ -176,15 +178,15 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary,
Vec2 textureSize; Vec2 textureSize;
// get the format // get the format
auto metaItr = dictionary.find("metadata"sv); auto metaItr = dictionary.find("metadata");
if (metaItr != dictionary.end()) if (metaItr != dictionary.end())
{ {
auto& metadataDict = metaItr->second.asValueMap(); auto& metadataDict = metaItr->second.asValueMap();
format = optValue(metadataDict, "format"sv).asInt(); format = metadataDict["format"].asInt();
if (metadataDict.find("size"sv) != metadataDict.end()) if (metadataDict.find("size") != metadataDict.end())
{ {
textureSize = SizeFromString(optValue(metadataDict, "size"sv).asString()); textureSize = SizeFromString(metadataDict["size"].asString());
} }
} }
@ -208,14 +210,14 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary,
if (format == 0) if (format == 0)
{ {
auto x = optValue(frameDict, "x"sv).asFloat(); auto x = frameDict["x"].asFloat();
auto y = optValue(frameDict, "y"sv).asFloat(); auto y = frameDict["y"].asFloat();
auto w = optValue(frameDict, "width"sv).asFloat(); auto w = frameDict["width"].asFloat();
auto h = optValue(frameDict, "height"sv).asFloat(); auto h = frameDict["height"].asFloat();
auto ox = optValue(frameDict, "offsetX"sv).asFloat(); auto ox = frameDict["offsetX"].asFloat();
auto oy = optValue(frameDict, "offsetY"sv).asFloat(); auto oy = frameDict["offsetY"].asFloat();
auto ow = optValue(frameDict, "originalWidth"sv).asInt(); auto ow = frameDict["originalWidth"].asInt();
auto oh = optValue(frameDict, "originalHeight"sv).asInt(); auto oh = frameDict["originalHeight"].asInt();
// check ow/oh // check ow/oh
if (!ow || !oh) if (!ow || !oh)
{ {
@ -232,17 +234,17 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary,
} }
else if (format == 1 || format == 2) else if (format == 1 || format == 2)
{ {
auto frame = RectFromString(optValue(frameDict, "frame"sv).asString()); auto frame = RectFromString(frameDict["frame"].asString());
auto rotated = false; auto rotated = false;
// rotation // rotation
if (format == 2) if (format == 2)
{ {
rotated = optValue(frameDict, "rotated"sv).asBool(); rotated = frameDict["rotated"].asBool();
} }
auto offset = PointFromString(optValue(frameDict, "offset"sv).asString()); auto offset = PointFromString(frameDict["offset"].asString());
auto sourceSize = SizeFromString(optValue(frameDict, "sourceSize"sv).asString()); auto sourceSize = SizeFromString(frameDict["sourceSize"].asString());
// create frame // create frame
spriteFrame = SpriteFrame::createWithTexture(texture, frame, rotated, offset, sourceSize); spriteFrame = SpriteFrame::createWithTexture(texture, frame, rotated, offset, sourceSize);
@ -250,14 +252,14 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary,
else if (format == 3) else if (format == 3)
{ {
// get values // get values
auto spriteSize = SizeFromString(optValue(frameDict, "spriteSize"sv).asString()); auto spriteSize = SizeFromString(frameDict["spriteSize"].asString());
auto spriteOffset = PointFromString(optValue(frameDict, "spriteOffset"sv).asString()); auto spriteOffset = PointFromString(frameDict["spriteOffset"].asString());
auto spriteSourceSize = SizeFromString(optValue(frameDict, "spriteSourceSize"sv).asString()); auto spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString());
auto textureRect = RectFromString(optValue(frameDict, "textureRect"sv).asString()); auto textureRect = RectFromString(frameDict["textureRect"].asString());
auto textureRotated = optValue(frameDict, "textureRotated"sv).asBool(); auto textureRotated = frameDict["textureRotated"].asBool();
// get aliases // get aliases
auto& aliases = optValue(frameDict, "aliases"sv).asValueVector(); auto& aliases = frameDict["aliases"].asValueVector();
for (const auto& value : aliases) for (const auto& value : aliases)
{ {
@ -280,9 +282,9 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary,
if (frameDict.find("vertices") != frameDict.end()) if (frameDict.find("vertices") != frameDict.end())
{ {
using cocos2d::utils::parseIntegerList; using cocos2d::utils::parseIntegerList;
auto vertices = parseIntegerList(optValue(frameDict, "vertices"sv).asString()); auto vertices = parseIntegerList(frameDict["vertices"].asString());
auto verticesUV = parseIntegerList(optValue(frameDict, "verticesUV"sv).asString()); auto verticesUV = parseIntegerList(frameDict["verticesUV"].asString());
auto indices = parseIntegerList(optValue(frameDict, "triangles"sv).asString()); auto indices = parseIntegerList(frameDict["triangles"].asString());
PolygonInfo info; PolygonInfo info;
initializePolygonInfo(textureSize, spriteSourceSize, vertices, verticesUV, indices, info); initializePolygonInfo(textureSize, spriteSourceSize, vertices, verticesUV, indices, info);
@ -290,7 +292,7 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary,
} }
if (frameDict.find("anchor") != frameDict.end()) if (frameDict.find("anchor") != frameDict.end())
{ {
spriteFrame->setAnchorPoint(PointFromString(optValue(frameDict, "anchor"sv).asString())); spriteFrame->setAnchorPoint(PointFromString(frameDict["anchor"].asString()));
} }
} }
@ -321,8 +323,8 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary,
} }
void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dict, void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dict,
std::string_view texturePath, const std::string& texturePath,
std::string_view plist, const std::string& plist,
SpriteFrameCache& cache) SpriteFrameCache& cache)
{ {
std::string pixelFormatName; std::string pixelFormatName;
@ -376,7 +378,7 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dict,
void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict,
Texture2D* texture, Texture2D* texture,
std::string_view plist, const std::string& plist,
SpriteFrameCache& cache) SpriteFrameCache& cache)
{ {
auto& framesDict = dict["frames"].asValueMap(); auto& framesDict = dict["frames"].asValueMap();
@ -399,8 +401,8 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict,
for (auto& iter : framesDict) for (auto& iter : framesDict)
{ {
const ValueMap& frameDict = iter.second.asValueMap(); ValueMap& frameDict = iter.second.asValueMap();
std::string_view spriteFrameName = iter.first; std::string spriteFrameName = iter.first;
cache.eraseFrame(spriteFrameName); cache.eraseFrame(spriteFrameName);
@ -409,14 +411,14 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict,
if (format == 0) if (format == 0)
{ {
const auto x = optValue(frameDict, "x"sv).asFloat(); const auto x = frameDict["x"].asFloat();
const auto y = optValue(frameDict, "y"sv).asFloat(); const auto y = frameDict["y"].asFloat();
const auto w = optValue(frameDict, "width"sv).asFloat(); const auto w = frameDict["width"].asFloat();
const auto h = optValue(frameDict, "height"sv).asFloat(); const auto h = frameDict["height"].asFloat();
const auto ox = optValue(frameDict, "offsetX"sv).asFloat(); const auto ox = frameDict["offsetX"].asFloat();
const auto oy = optValue(frameDict, "offsetY"sv).asFloat(); const auto oy = frameDict["offsetY"].asFloat();
auto ow = optValue(frameDict, "originalWidth"sv).asInt(); auto ow = frameDict["originalWidth"].asInt();
auto oh = optValue(frameDict, "originalHeight"sv).asInt(); auto oh = frameDict["originalHeight"].asInt();
// check ow/oh // check ow/oh
if (!ow || !oh) if (!ow || !oh)
{ {
@ -433,17 +435,17 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict,
} }
else if (format == 1 || format == 2) else if (format == 1 || format == 2)
{ {
auto frame = RectFromString(optValue(frameDict, "frame"sv).asString()); auto frame = RectFromString(frameDict["frame"].asString());
auto rotated = false; auto rotated = false;
// rotation // rotation
if (format == 2) if (format == 2)
{ {
rotated = optValue(frameDict, "rotated"sv).asBool(); rotated = frameDict["rotated"].asBool();
} }
auto offset = PointFromString(optValue(frameDict, "offset"sv).asString()); auto offset = PointFromString(frameDict["offset"].asString());
auto sourceSize = SizeFromString(optValue(frameDict, "sourceSize"sv).asString()); auto sourceSize = SizeFromString(frameDict["sourceSize"].asString());
// create frame // create frame
spriteFrame = SpriteFrame::createWithTexture(texture, frame, rotated, offset, sourceSize); spriteFrame = SpriteFrame::createWithTexture(texture, frame, rotated, offset, sourceSize);
@ -451,14 +453,14 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict,
else if (format == 3) else if (format == 3)
{ {
// get values // get values
const auto spriteSize = SizeFromString(optValue(frameDict, "spriteSize"sv).asString()); const auto spriteSize = SizeFromString(frameDict["spriteSize"].asString());
auto spriteOffset = PointFromString(optValue(frameDict, "spriteOffset"sv).asString()); auto spriteOffset = PointFromString(frameDict["spriteOffset"].asString());
auto spriteSourceSize = SizeFromString(optValue(frameDict, "spriteSourceSize"sv).asString()); auto spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString());
const auto textureRect = RectFromString(optValue(frameDict, "textureRect"sv).asString()); const auto textureRect = RectFromString(frameDict["textureRect"].asString());
const auto textureRotated = optValue(frameDict, "textureRotated"sv).asBool(); const auto textureRotated = frameDict["textureRotated"].asBool();
// get aliases // get aliases
const ValueVector& aliases = optValue(frameDict, "aliases"sv).asValueVector(); ValueVector& aliases = frameDict["aliases"].asValueVector();
for (const auto& value : aliases) for (const auto& value : aliases)
{ {

View File

@ -14,30 +14,30 @@ public:
static constexpr uint32_t FORMAT = SpriteSheetFormat::PLIST; static constexpr uint32_t FORMAT = SpriteSheetFormat::PLIST;
uint32_t getFormat() override { return FORMAT; } uint32_t getFormat() override { return FORMAT; }
void load(std::string_view filePath, SpriteFrameCache& cache) override; void load(const std::string& filePath, SpriteFrameCache& cache) override;
void load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) override; void load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) override;
void load(std::string_view filePath, std::string_view textureFileName, SpriteFrameCache& cache) override; void load(const std::string& filePath, const std::string& textureFileName, SpriteFrameCache& cache) override;
void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) override; void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) override;
void reload(std::string_view filePath, SpriteFrameCache& cache) override; void reload(const std::string& filePath, SpriteFrameCache& cache) override;
protected: protected:
/*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames.
*/ */
void addSpriteFramesWithDictionary(ValueMap& dictionary, void addSpriteFramesWithDictionary(ValueMap& dictionary,
Texture2D* texture, Texture2D* texture,
std::string_view plist, const std::string& plist,
SpriteFrameCache& cache); SpriteFrameCache& cache);
/*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames.
*/ */
void addSpriteFramesWithDictionary(ValueMap& dict, void addSpriteFramesWithDictionary(ValueMap& dict,
std::string_view texturePath, const std::string& texturePath,
std::string_view plist, const std::string& plist,
SpriteFrameCache& cache); SpriteFrameCache& cache);
void reloadSpriteFramesWithDictionary(ValueMap& dict, void reloadSpriteFramesWithDictionary(ValueMap& dict,
Texture2D* texture, Texture2D* texture,
std::string_view plist, const std::string& plist,
SpriteFrameCache& cache); SpriteFrameCache& cache);
}; };

View File

@ -357,7 +357,9 @@ void RenderTexture::visit(Renderer* renderer, const Mat4& parentTransform, uint3
// setOrderOfArrival(0); // setOrderOfArrival(0);
} }
bool RenderTexture::saveToFileAsNonPMA(std::string_view filename, bool isRGBA, SaveFileCallbackType callback) bool RenderTexture::saveToFileAsNonPMA(const std::string& filename,
bool isRGBA,
std::function<void(RenderTexture*, const std::string&)> callback)
{ {
std::string basename(filename); std::string basename(filename);
std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower); std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower);
@ -380,7 +382,9 @@ bool RenderTexture::saveToFileAsNonPMA(std::string_view filename, bool isRGBA, S
return saveToFileAsNonPMA(filename, Image::Format::JPG, false, callback); return saveToFileAsNonPMA(filename, Image::Format::JPG, false, callback);
} }
bool RenderTexture::saveToFile(std::string_view filename, bool isRGBA, SaveFileCallbackType callback) bool RenderTexture::saveToFile(const std::string& filename,
bool isRGBA,
std::function<void(RenderTexture*, const std::string&)> callback)
{ {
std::string basename(filename); std::string basename(filename);
std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower); std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower);
@ -403,10 +407,10 @@ bool RenderTexture::saveToFile(std::string_view filename, bool isRGBA, SaveFileC
return saveToFile(filename, Image::Format::JPG, false, callback); return saveToFile(filename, Image::Format::JPG, false, callback);
} }
bool RenderTexture::saveToFileAsNonPMA(std::string_view fileName, bool RenderTexture::saveToFileAsNonPMA(const std::string& fileName,
Image::Format format, Image::Format format,
bool isRGBA, bool isRGBA,
SaveFileCallbackType callback) std::function<void(RenderTexture*, const std::string&)> callback)
{ {
CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG, CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG,
"the image can only be saved as JPG or PNG format"); "the image can only be saved as JPG or PNG format");
@ -415,7 +419,7 @@ bool RenderTexture::saveToFileAsNonPMA(std::string_view fileName,
_saveFileCallback = callback; _saveFileCallback = callback;
std::string fullpath = FileUtils::getInstance()->getWritablePath().append(fileName); std::string fullpath = FileUtils::getInstance()->getWritablePath() + fileName;
_saveToFileCommand.init(_globalZOrder); _saveToFileCommand.init(_globalZOrder);
_saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA, true); _saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA, true);
@ -423,10 +427,10 @@ bool RenderTexture::saveToFileAsNonPMA(std::string_view fileName,
return true; return true;
} }
bool RenderTexture::saveToFile(std::string_view fileName, bool RenderTexture::saveToFile(const std::string& fileName,
Image::Format format, Image::Format format,
bool isRGBA, bool isRGBA,
std::function<void(RenderTexture*, std::string_view)> callback) std::function<void(RenderTexture*, const std::string&)> callback)
{ {
CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG, CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG,
"the image can only be saved as JPG or PNG format"); "the image can only be saved as JPG or PNG format");
@ -435,7 +439,7 @@ bool RenderTexture::saveToFile(std::string_view fileName,
_saveFileCallback = callback; _saveFileCallback = callback;
std::string fullpath = FileUtils::getInstance()->getWritablePath().append(fileName); std::string fullpath = FileUtils::getInstance()->getWritablePath() + fileName;
_saveToFileCommand.init(_globalZOrder); _saveToFileCommand.init(_globalZOrder);
_saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA, false); _saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA, false);
@ -443,7 +447,7 @@ bool RenderTexture::saveToFile(std::string_view fileName,
return true; return true;
} }
void RenderTexture::onSaveToFile(std::string_view filename, bool isRGBA, bool forceNonPMA) void RenderTexture::onSaveToFile(const std::string& filename, bool isRGBA, bool forceNonPMA)
{ {
auto callbackFunc = [&, filename, isRGBA, forceNonPMA](RefPtr<Image> image) { auto callbackFunc = [&, filename, isRGBA, forceNonPMA](RefPtr<Image> image) {
if (image) if (image)

View File

@ -61,7 +61,6 @@ class EventCustom;
class CC_DLL RenderTexture : public Node class CC_DLL RenderTexture : public Node
{ {
public: public:
using SaveFileCallbackType = std::function<void(RenderTexture*, std::string_view)>;
/** Initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats /** Initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats
* are valid ) and depthStencil format. * are valid ) and depthStencil format.
* *
@ -172,7 +171,9 @@ public:
* @param callback When the file is save finished,it will callback this function. * @param callback When the file is save finished,it will callback this function.
* @return Returns true if the operation is successful. * @return Returns true if the operation is successful.
*/ */
bool saveToFileAsNonPMA(std::string_view filename, bool isRGBA = true, SaveFileCallbackType = nullptr); bool saveToFileAsNonPMA(const std::string& filename,
bool isRGBA = true,
std::function<void(RenderTexture*, const std::string&)> callback = nullptr);
/** Saves the texture into a file using JPEG format. The file will be saved in the Documents folder. /** Saves the texture into a file using JPEG format. The file will be saved in the Documents folder.
* Returns true if the operation is successful. * Returns true if the operation is successful.
@ -182,7 +183,9 @@ public:
* @param callback When the file is save finished,it will callback this function. * @param callback When the file is save finished,it will callback this function.
* @return Returns true if the operation is successful. * @return Returns true if the operation is successful.
*/ */
bool saveToFile(std::string_view filename, bool isRGBA = true, SaveFileCallbackType = nullptr); bool saveToFile(const std::string& filename,
bool isRGBA = true,
std::function<void(RenderTexture*, const std::string&)> callback = nullptr);
/** saves the texture into a file in non-PMA. The format could be JPG or PNG. The file will be saved in the /** saves the texture into a file in non-PMA. The format could be JPG or PNG. The file will be saved in the
Documents folder. Returns true if the operation is successful. Documents folder. Returns true if the operation is successful.
@ -198,10 +201,10 @@ public:
* @param callback When the file is save finished,it will callback this function. * @param callback When the file is save finished,it will callback this function.
* @return Returns true if the operation is successful. * @return Returns true if the operation is successful.
*/ */
bool saveToFileAsNonPMA(std::string_view fileName, bool saveToFileAsNonPMA(const std::string& fileName,
Image::Format format, Image::Format format,
bool isRGBA, bool isRGBA,
SaveFileCallbackType callback); std::function<void(RenderTexture*, const std::string&)> callback);
/** saves the texture into a file. The format could be JPG or PNG. The file will be saved in the Documents folder. /** saves the texture into a file. The format could be JPG or PNG. The file will be saved in the Documents folder.
Returns true if the operation is successful. Returns true if the operation is successful.
@ -217,10 +220,10 @@ public:
* @param callback When the file is save finished,it will callback this function. * @param callback When the file is save finished,it will callback this function.
* @return Returns true if the operation is successful. * @return Returns true if the operation is successful.
*/ */
bool saveToFile(std::string_view filename, bool saveToFile(const std::string& filename,
Image::Format format, Image::Format format,
bool isRGBA = true, bool isRGBA = true,
SaveFileCallbackType callback = nullptr); std::function<void(RenderTexture*, const std::string&)> callback = nullptr);
/** Listen "come to background" message, and save render texture. /** Listen "come to background" message, and save render texture.
* It only has effect on Android. * It only has effect on Android.
@ -364,7 +367,7 @@ protected:
void onEnd(); void onEnd();
void clearColorAttachment(); void clearColorAttachment();
void onSaveToFile(std::string_view fileName, bool isRGBA = true, bool forceNonPMA = false); void onSaveToFile(const std::string& fileName, bool isRGBA = true, bool forceNonPMA = false);
bool _keepMatrix = false; bool _keepMatrix = false;
Rect _rtTextureRect; Rect _rtTextureRect;
@ -408,7 +411,7 @@ protected:
and the command and callback will be executed twice. and the command and callback will be executed twice.
*/ */
CallbackCommand _saveToFileCommand; CallbackCommand _saveToFileCommand;
std::function<void(RenderTexture*, std::string_view)> _saveFileCallback = nullptr; std::function<void(RenderTexture*, const std::string&)> _saveFileCallback = nullptr;
Mat4 _oldTransMatrix, _oldProjMatrix; Mat4 _oldTransMatrix, _oldProjMatrix;
Mat4 _transformMatrix, _projectionMatrix; Mat4 _transformMatrix, _projectionMatrix;

View File

@ -142,7 +142,7 @@ protected:
std::vector<Camera*> _cameras; // weak ref to Camera std::vector<Camera*> _cameras; // weak ref to Camera
Camera* _defaultCamera = nullptr; // weak ref, default camera created by scene, _cameras[0], Caution that the Camera* _defaultCamera = nullptr; // weak ref, default camera created by scene, _cameras[0], Caution that the
// default camera can not be added to _cameras before onEnter is called // default camera can not be added to _cameras before onEnter is called
bool _cameraOrderDirty = true; // order is dirty, need sort bool _cameraOrderDirty = true; // order is dirty, need sort
EventListenerCustom* _event; EventListenerCustom* _event;
std::vector<BaseLight*> _lights; std::vector<BaseLight*> _lights;

View File

@ -72,7 +72,7 @@ Sprite* Sprite::createWithTexture(Texture2D* texture, const Rect& rect, bool rot
return nullptr; return nullptr;
} }
Sprite* Sprite::create(std::string_view filename) Sprite* Sprite::create(const std::string& filename)
{ {
Sprite* sprite = new Sprite(); Sprite* sprite = new Sprite();
if (sprite->initWithFile(filename)) if (sprite->initWithFile(filename))
@ -96,7 +96,7 @@ Sprite* Sprite::create(const PolygonInfo& info)
return nullptr; return nullptr;
} }
Sprite* Sprite::create(std::string_view filename, const Rect& rect) Sprite* Sprite::create(const std::string& filename, const Rect& rect)
{ {
Sprite* sprite = new Sprite(); Sprite* sprite = new Sprite();
if (sprite->initWithFile(filename, rect)) if (sprite->initWithFile(filename, rect))
@ -120,13 +120,13 @@ Sprite* Sprite::createWithSpriteFrame(SpriteFrame* spriteFrame)
return nullptr; return nullptr;
} }
Sprite* Sprite::createWithSpriteFrameName(std::string_view spriteFrameName) Sprite* Sprite::createWithSpriteFrameName(const std::string& spriteFrameName)
{ {
SpriteFrame* frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); SpriteFrame* frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName);
#if COCOS2D_DEBUG > 0 #if COCOS2D_DEBUG > 0
char msg[256] = {0}; char msg[256] = {0};
sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.data()); sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.c_str());
CCASSERT(frame != nullptr, msg); CCASSERT(frame != nullptr, msg);
#endif #endif
@ -167,7 +167,7 @@ bool Sprite::initWithTexture(Texture2D* texture, const Rect& rect)
return initWithTexture(texture, rect, false); return initWithTexture(texture, rect, false);
} }
bool Sprite::initWithFile(std::string_view filename) bool Sprite::initWithFile(const std::string& filename)
{ {
if (filename.empty()) if (filename.empty())
{ {
@ -191,7 +191,7 @@ bool Sprite::initWithFile(std::string_view filename)
return false; return false;
} }
bool Sprite::initWithFile(std::string_view filename, const Rect& rect) bool Sprite::initWithFile(const std::string& filename, const Rect& rect)
{ {
CCASSERT(!filename.empty(), "Invalid filename"); CCASSERT(!filename.empty(), "Invalid filename");
if (filename.empty()) if (filename.empty())
@ -209,7 +209,7 @@ bool Sprite::initWithFile(std::string_view filename, const Rect& rect)
return false; return false;
} }
bool Sprite::initWithSpriteFrameName(std::string_view spriteFrameName) bool Sprite::initWithSpriteFrameName(const std::string& spriteFrameName)
{ {
CCASSERT(!spriteFrameName.empty(), "Invalid spriteFrameName"); CCASSERT(!spriteFrameName.empty(), "Invalid spriteFrameName");
if (spriteFrameName.empty()) if (spriteFrameName.empty())
@ -332,7 +332,7 @@ static unsigned char cc_2x2_white_image[] = {
#define CC_2x2_WHITE_IMAGE_KEY "/cc_2x2_white_image" #define CC_2x2_WHITE_IMAGE_KEY "/cc_2x2_white_image"
// MARK: texture // MARK: texture
void Sprite::setTexture(std::string_view filename) void Sprite::setTexture(const std::string& filename)
{ {
Texture2D* texture = _director->getTextureCache()->addImage(filename); Texture2D* texture = _director->getTextureCache()->addImage(filename);
setTexture(texture); setTexture(texture);
@ -1132,7 +1132,7 @@ void Sprite::addChild(Node* child, int zOrder, int tag)
Node::addChild(child, zOrder, tag); Node::addChild(child, zOrder, tag);
} }
void Sprite::addChild(Node* child, int zOrder, std::string_view name) void Sprite::addChild(Node* child, int zOrder, const std::string& name)
{ {
CCASSERT(child != nullptr, "Argument must be non-nullptr"); CCASSERT(child != nullptr, "Argument must be non-nullptr");
if (child == nullptr) if (child == nullptr)
@ -1539,7 +1539,7 @@ bool Sprite::isOpacityModifyRGB() const
// MARK: Frames // MARK: Frames
void Sprite::setSpriteFrame(std::string_view spriteFrameName) void Sprite::setSpriteFrame(const std::string& spriteFrameName)
{ {
CCASSERT(!spriteFrameName.empty(), "spriteFrameName must not be empty"); CCASSERT(!spriteFrameName.empty(), "spriteFrameName must not be empty");
if (spriteFrameName.empty()) if (spriteFrameName.empty())
@ -1590,7 +1590,7 @@ void Sprite::setSpriteFrame(SpriteFrame* spriteFrame)
setCenterRect(spriteFrame->getCenterRect()); setCenterRect(spriteFrame->getCenterRect());
} }
void Sprite::setDisplayFrameWithAnimationName(std::string_view animationName, unsigned int frameIndex) void Sprite::setDisplayFrameWithAnimationName(const std::string& animationName, unsigned int frameIndex)
{ {
CCASSERT(!animationName.empty(), "CCSprite#setDisplayFrameWithAnimationName. animationName must not be nullptr"); CCASSERT(!animationName.empty(), "CCSprite#setDisplayFrameWithAnimationName. animationName must not be nullptr");
if (animationName.empty()) if (animationName.empty())

View File

@ -129,7 +129,7 @@ public:
* @param filename A path to image file, e.g., "scene1/monster.png". * @param filename A path to image file, e.g., "scene1/monster.png".
* @return An autoreleased sprite object. * @return An autoreleased sprite object.
*/ */
static Sprite* create(std::string_view filename); static Sprite* create(const std::string& filename);
/** /**
* Creates a polygon sprite with a polygon info. * Creates a polygon sprite with a polygon info.
@ -149,7 +149,7 @@ public:
* @param rect A subrect of the image file. * @param rect A subrect of the image file.
* @return An autoreleased sprite object. * @return An autoreleased sprite object.
*/ */
static Sprite* create(std::string_view filename, const Rect& rect); static Sprite* create(const std::string& filename, const Rect& rect);
/** /**
* Creates a sprite with a Texture2D object. * Creates a sprite with a Texture2D object.
@ -191,7 +191,7 @@ public:
* @param spriteFrameName The name of sprite frame. * @param spriteFrameName The name of sprite frame.
* @return An autoreleased sprite object. * @return An autoreleased sprite object.
*/ */
static Sprite* createWithSpriteFrameName(std::string_view spriteFrameName); static Sprite* createWithSpriteFrameName(const std::string& spriteFrameName);
// end of creators group // end of creators group
/// @} /// @}
@ -233,7 +233,7 @@ public:
* @memberof Sprite * @memberof Sprite
* It will call `setTextureRect()` with the texture's content size. * It will call `setTextureRect()` with the texture's content size.
*/ */
virtual void setTexture(std::string_view filename); virtual void setTexture(const std::string& filename);
/** @overload /** @overload
* *
@ -304,7 +304,7 @@ public:
/** @{ /** @{
* Sets a new SpriteFrame to the Sprite. * Sets a new SpriteFrame to the Sprite.
*/ */
virtual void setSpriteFrame(std::string_view spriteFrameName); virtual void setSpriteFrame(const std::string& spriteFrameName);
virtual void setSpriteFrame(SpriteFrame* newFrame); virtual void setSpriteFrame(SpriteFrame* newFrame);
/** @} */ /** @} */
@ -326,7 +326,7 @@ public:
* Changes the display frame with animation name and index. * Changes the display frame with animation name and index.
* The animation name will be get from the AnimationCache. * The animation name will be get from the AnimationCache.
*/ */
virtual void setDisplayFrameWithAnimationName(std::string_view animationName, unsigned int frameIndex); virtual void setDisplayFrameWithAnimationName(const std::string& animationName, unsigned int frameIndex);
/// @} /// @}
/// @{ /// @{
@ -370,7 +370,7 @@ public:
virtual void reorderChild(Node* child, int zOrder) override; virtual void reorderChild(Node* child, int zOrder) override;
using Node::addChild; using Node::addChild;
virtual void addChild(Node* child, int zOrder, int tag) override; virtual void addChild(Node* child, int zOrder, int tag) override;
virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void addChild(Node* child, int zOrder, const std::string& name) override;
virtual void sortAllChildren() override; virtual void sortAllChildren() override;
virtual void setScale(float scale) override; virtual void setScale(float scale) override;
virtual void setPositionZ(float positionZ) override; virtual void setPositionZ(float positionZ) override;
@ -513,7 +513,7 @@ public:
/// @} /// @}
int getResourceType() const { return _fileType; } int getResourceType() const { return _fileType; }
std::string_view getResourceName() const { return _fileName; } const std::string& getResourceName() const { return _fileName; }
CC_CONSTRUCTOR_ACCESS : CC_CONSTRUCTOR_ACCESS :
/** /**
@ -588,7 +588,7 @@ public:
* @param spriteFrameName A key string that can fetched a valid SpriteFrame from SpriteFrameCache. * @param spriteFrameName A key string that can fetched a valid SpriteFrame from SpriteFrameCache.
* @return True if the sprite is initialized properly, false otherwise. * @return True if the sprite is initialized properly, false otherwise.
*/ */
virtual bool initWithSpriteFrameName(std::string_view spriteFrameName); virtual bool initWithSpriteFrameName(const std::string& spriteFrameName);
/** /**
* Initializes a sprite with an image filename. * Initializes a sprite with an image filename.
@ -601,7 +601,7 @@ public:
* @return True if the sprite is initialized properly, false otherwise. * @return True if the sprite is initialized properly, false otherwise.
* @lua init * @lua init
*/ */
virtual bool initWithFile(std::string_view filename); virtual bool initWithFile(const std::string& filename);
/** /**
* Initializes a sprite with an image filename, and a rect. * Initializes a sprite with an image filename, and a rect.
@ -615,7 +615,7 @@ public:
* @return True if the sprite is initialized properly, false otherwise. * @return True if the sprite is initialized properly, false otherwise.
* @lua init * @lua init
*/ */
virtual bool initWithFile(std::string_view filename, const Rect& rect); virtual bool initWithFile(const std::string& filename, const Rect& rect);
virtual void setVertexLayout(); virtual void setVertexLayout();

View File

@ -64,7 +64,7 @@ SpriteBatchNode* SpriteBatchNode::createWithTexture(Texture2D* tex, ssize_t capa
* creation with File Image * creation with File Image
*/ */
SpriteBatchNode* SpriteBatchNode::create(std::string_view fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/) SpriteBatchNode* SpriteBatchNode::create(const std::string& fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/)
{ {
SpriteBatchNode* batchNode = new SpriteBatchNode(); SpriteBatchNode* batchNode = new SpriteBatchNode();
if (batchNode->initWithFile(fileImage, capacity)) if (batchNode->initWithFile(fileImage, capacity))
@ -168,7 +168,7 @@ bool SpriteBatchNode::init()
/* /*
* init with FileImage * init with FileImage
*/ */
bool SpriteBatchNode::initWithFile(std::string_view fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/) bool SpriteBatchNode::initWithFile(const std::string& fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/)
{ {
Texture2D* texture2D = _director->getTextureCache()->addImage(fileImage); Texture2D* texture2D = _director->getTextureCache()->addImage(fileImage);
return initWithTexture(texture2D, capacity); return initWithTexture(texture2D, capacity);
@ -236,7 +236,7 @@ void SpriteBatchNode::addChild(Node* child, int zOrder, int tag)
appendChild(sprite); appendChild(sprite);
} }
void SpriteBatchNode::addChild(Node* child, int zOrder, std::string_view name) void SpriteBatchNode::addChild(Node* child, int zOrder, const std::string& name)
{ {
CCASSERT(child != nullptr, "child should not be null"); CCASSERT(child != nullptr, "child should not be null");
CCASSERT(dynamic_cast<Sprite*>(child) != nullptr, "CCSpriteBatchNode only supports Sprites as children"); CCASSERT(dynamic_cast<Sprite*>(child) != nullptr, "CCSpriteBatchNode only supports Sprites as children");

View File

@ -84,7 +84,7 @@ public:
* @param capacity The capacity of children. * @param capacity The capacity of children.
* @return Return an autorelease object. * @return Return an autorelease object.
*/ */
static SpriteBatchNode* create(std::string_view fileImage, ssize_t capacity = DEFAULT_CAPACITY); static SpriteBatchNode* create(const std::string& fileImage, ssize_t capacity = DEFAULT_CAPACITY);
/** Returns the TextureAtlas object. /** Returns the TextureAtlas object.
* *
@ -195,7 +195,7 @@ public:
using Node::addChild; using Node::addChild;
virtual void addChild(Node* child, int zOrder, int tag) override; virtual void addChild(Node* child, int zOrder, int tag) override;
virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void addChild(Node* child, int zOrder, const std::string& name) override;
virtual void reorderChild(Node* child, int zOrder) override; virtual void reorderChild(Node* child, int zOrder) override;
virtual void removeChild(Node* child, bool cleanup) override; virtual void removeChild(Node* child, bool cleanup) override;
@ -250,7 +250,7 @@ public:
* @js init * @js init
* @lua init * @lua init
*/ */
bool initWithFile(std::string_view fileImage, ssize_t capacity = DEFAULT_CAPACITY); bool initWithFile(const std::string& fileImage, ssize_t capacity = DEFAULT_CAPACITY);
bool init() override; bool init() override;
protected: protected:

View File

@ -35,7 +35,7 @@ NS_CC_BEGIN
// implementation of SpriteFrame // implementation of SpriteFrame
SpriteFrame* SpriteFrame::create(std::string_view filename, const Rect& rect) SpriteFrame* SpriteFrame::create(const std::string& filename, const Rect& rect)
{ {
SpriteFrame* spriteFrame = new SpriteFrame(); SpriteFrame* spriteFrame = new SpriteFrame();
spriteFrame->initWithTextureFilename(filename, rect); spriteFrame->initWithTextureFilename(filename, rect);
@ -70,7 +70,7 @@ SpriteFrame* SpriteFrame::createWithTexture(Texture2D* texture,
return nullptr; return nullptr;
} }
SpriteFrame* SpriteFrame::create(std::string_view filename, SpriteFrame* SpriteFrame::create(const std::string& filename,
const Rect& rect, const Rect& rect,
bool rotated, bool rotated,
const Vec2& offset, const Vec2& offset,
@ -94,7 +94,7 @@ bool SpriteFrame::initWithTexture(Texture2D* texture, const Rect& rect)
return initWithTexture(texture, rectInPixels, false, Vec2::ZERO, rectInPixels.size); return initWithTexture(texture, rectInPixels, false, Vec2::ZERO, rectInPixels.size);
} }
bool SpriteFrame::initWithTextureFilename(std::string_view filename, const Rect& rect) bool SpriteFrame::initWithTextureFilename(const std::string& filename, const Rect& rect)
{ {
Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS(rect); Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS(rect);
return initWithTextureFilename(filename, rectInPixels, false, Vec2::ZERO, rectInPixels.size); return initWithTextureFilename(filename, rectInPixels, false, Vec2::ZERO, rectInPixels.size);
@ -126,7 +126,7 @@ bool SpriteFrame::initWithTexture(Texture2D* texture,
return true; return true;
} }
bool SpriteFrame::initWithTextureFilename(std::string_view filename, bool SpriteFrame::initWithTextureFilename(const std::string& filename,
const Rect& rect, const Rect& rect,
bool rotated, bool rotated,
const Vec2& offset, const Vec2& offset,

View File

@ -66,7 +66,7 @@ public:
* @param rect A specified rect. * @param rect A specified rect.
* @return An autoreleased SpriteFrame object. * @return An autoreleased SpriteFrame object.
*/ */
static SpriteFrame* create(std::string_view filename, const Rect& rect); static SpriteFrame* create(const std::string& filename, const Rect& rect);
/** Create a SpriteFrame with a texture filename, rect, rotated, offset and originalSize in pixels. /** Create a SpriteFrame with a texture filename, rect, rotated, offset and originalSize in pixels.
The originalSize is the size in pixels of the frame before being trimmed. The originalSize is the size in pixels of the frame before being trimmed.
@ -78,7 +78,7 @@ public:
* @param originalSize A specified original size. * @param originalSize A specified original size.
* @return An autoreleased SpriteFrame object. * @return An autoreleased SpriteFrame object.
*/ */
static SpriteFrame* create(std::string_view filename, static SpriteFrame* create(const std::string& filename,
const Rect& rect, const Rect& rect,
bool rotated, bool rotated,
const Vec2& offset, const Vec2& offset,
@ -279,7 +279,7 @@ public:
/** Initializes a SpriteFrame with a texture filename, rect in points; /** Initializes a SpriteFrame with a texture filename, rect in points;
It is assumed that the frame was not trimmed. It is assumed that the frame was not trimmed.
*/ */
bool initWithTextureFilename(std::string_view filename, const Rect& rect); bool initWithTextureFilename(const std::string& filename, const Rect& rect);
/** Initializes a SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. /** Initializes a SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.
The originalSize is the size in points of the frame before being trimmed. The originalSize is the size in points of the frame before being trimmed.
@ -295,7 +295,7 @@ public:
@since v1.1 @since v1.1
*/ */
bool initWithTextureFilename(std::string_view filename, bool initWithTextureFilename(const std::string& filename,
const Rect& rect, const Rect& rect,
bool rotated, bool rotated,
const Vec2& offset, const Vec2& offset,

View File

@ -75,8 +75,8 @@ bool SpriteFrameCache::init()
SpriteFrameCache::~SpriteFrameCache() {} SpriteFrameCache::~SpriteFrameCache() {}
void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileName, void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFileName,
std::string_view textureFileName, const std::string& textureFileName,
uint32_t spriteSheetFormat) uint32_t spriteSheetFormat)
{ {
auto* loader = getSpriteSheetLoader(spriteSheetFormat); auto* loader = getSpriteSheetLoader(spriteSheetFormat);
@ -86,7 +86,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileN
} }
} }
void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileName, void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFileName,
Texture2D* texture, Texture2D* texture,
uint32_t spriteSheetFormat) uint32_t spriteSheetFormat)
{ {
@ -97,7 +97,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileN
} }
} }
void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileName, uint32_t spriteSheetFormat) void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFileName, uint32_t spriteSheetFormat)
{ {
auto* loader = getSpriteSheetLoader(spriteSheetFormat); auto* loader = getSpriteSheetLoader(spriteSheetFormat);
if (loader) if (loader)
@ -117,12 +117,12 @@ void SpriteFrameCache::addSpriteFramesWithFileContent(const Data& content,
} }
} }
bool SpriteFrameCache::isSpriteFramesWithFileLoaded(std::string_view plist) const bool SpriteFrameCache::isSpriteFramesWithFileLoaded(const std::string& plist) const
{ {
return isSpriteSheetInUse(plist) && isPlistFull(plist); return isSpriteSheetInUse(plist) && isPlistFull(plist);
} }
void SpriteFrameCache::addSpriteFrame(SpriteFrame* frame, std::string_view frameName) void SpriteFrameCache::addSpriteFrame(SpriteFrame* frame, const std::string& frameName)
{ {
CCASSERT(frame, "frame should not be nil"); CCASSERT(frame, "frame should not be nil");
@ -169,7 +169,7 @@ void SpriteFrameCache::removeUnusedSpriteFrames()
} }
} }
void SpriteFrameCache::removeSpriteFrameByName(std::string_view name) void SpriteFrameCache::removeSpriteFrameByName(const std::string& name)
{ {
// explicit nil handling // explicit nil handling
if (name.empty()) if (name.empty())
@ -178,7 +178,7 @@ void SpriteFrameCache::removeSpriteFrameByName(std::string_view name)
eraseFrame(name); eraseFrame(name);
} }
void SpriteFrameCache::removeSpriteFramesFromFile(std::string_view atlasPath) void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& atlasPath)
{ {
// const auto fullPath = FileUtils::getInstance()->fullPathForFilename(plist); // const auto fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
// auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); // auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
@ -193,7 +193,7 @@ void SpriteFrameCache::removeSpriteFramesFromFile(std::string_view atlasPath)
removeSpriteSheet(atlasPath); removeSpriteSheet(atlasPath);
} }
void SpriteFrameCache::removeSpriteFramesFromFileContent(std::string_view plist_content) void SpriteFrameCache::removeSpriteFramesFromFileContent(const std::string& plist_content)
{ {
auto dict = auto dict =
FileUtils::getInstance()->getValueMapFromData(plist_content.data(), static_cast<int>(plist_content.size())); FileUtils::getInstance()->getValueMapFromData(plist_content.data(), static_cast<int>(plist_content.size()));
@ -241,17 +241,17 @@ void SpriteFrameCache::removeSpriteFramesFromTexture(Texture2D* texture)
eraseFrames(keysToRemove); eraseFrames(keysToRemove);
} }
SpriteFrame* SpriteFrameCache::getSpriteFrameByName(std::string_view name) SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name)
{ {
auto* frame = findFrame(name); auto* frame = findFrame(name);
if (!frame) if (!frame)
{ {
CCLOG("cocos2d: SpriteFrameCache: Frame '%s' isn't found", name.data()); CCLOG("cocos2d: SpriteFrameCache: Frame '%s' isn't found", name.c_str());
} }
return frame; return frame;
} }
bool SpriteFrameCache::reloadTexture(std::string_view spriteSheetFileName) bool SpriteFrameCache::reloadTexture(const std::string& spriteSheetFileName)
{ {
CCASSERT(!spriteSheetFileName.empty(), "plist filename should not be nullptr"); CCASSERT(!spriteSheetFileName.empty(), "plist filename should not be nullptr");
@ -283,18 +283,16 @@ bool SpriteFrameCache::reloadTexture(std::string_view spriteSheetFileName)
} }
void SpriteFrameCache::insertFrame(const std::shared_ptr<SpriteSheet>& spriteSheet, void SpriteFrameCache::insertFrame(const std::shared_ptr<SpriteSheet>& spriteSheet,
std::string_view frameName, const std::string& frameName,
SpriteFrame* spriteFrame) SpriteFrame* spriteFrame)
{ {
spriteSheet->frames.emplace(frameName); spriteSheet->frames.insert(frameName);
_spriteFrames.insert(frameName, spriteFrame); // add SpriteFrame _spriteFrames.insert(frameName, spriteFrame); // add SpriteFrame
_spriteSheets[spriteSheet->path] = spriteSheet; _spriteSheets[spriteSheet->path] = spriteSheet;
hlookup::set_item(_spriteFrameToSpriteSheetMap, frameName, _spriteFrameToSpriteSheetMap[frameName] = spriteSheet; // insert index frameName->plist
spriteSheet); // _spriteFrameToSpriteSheetMap[frameName] = spriteSheet; // insert
// index frameName->plist
} }
bool SpriteFrameCache::eraseFrame(std::string_view frameName) bool SpriteFrameCache::eraseFrame(const std::string& frameName)
{ {
_spriteFrames.erase(frameName); // drop SpriteFrame _spriteFrames.erase(frameName); // drop SpriteFrame
const auto itFrame = _spriteFrameToSpriteSheetMap.find(frameName); const auto itFrame = _spriteFrameToSpriteSheetMap.find(frameName);
@ -332,7 +330,7 @@ bool SpriteFrameCache::eraseFrames(const std::vector<std::string>& frames)
return ret; return ret;
} }
bool SpriteFrameCache::removeSpriteSheet(std::string_view spriteSheetFileName) bool SpriteFrameCache::removeSpriteSheet(const std::string& spriteSheetFileName)
{ {
auto it = _spriteSheets.find(spriteSheetFileName); auto it = _spriteSheets.find(spriteSheetFileName);
if (it == _spriteSheets.end()) if (it == _spriteSheets.end())
@ -358,18 +356,18 @@ void SpriteFrameCache::clear()
_spriteFrames.clear(); _spriteFrames.clear();
} }
bool SpriteFrameCache::hasFrame(std::string_view frame) const bool SpriteFrameCache::hasFrame(const std::string& frame) const
{ {
return _spriteFrameToSpriteSheetMap.find(frame) != _spriteFrameToSpriteSheetMap.end(); return _spriteFrameToSpriteSheetMap.find(frame) != _spriteFrameToSpriteSheetMap.end();
} }
bool SpriteFrameCache::isSpriteSheetInUse(std::string_view spriteSheetFileName) const bool SpriteFrameCache::isSpriteSheetInUse(const std::string& spriteSheetFileName) const
{ {
const auto spriteSheetItr = _spriteSheets.find(spriteSheetFileName); const auto spriteSheetItr = _spriteSheets.find(spriteSheetFileName);
return spriteSheetItr != _spriteSheets.end() && !spriteSheetItr->second->frames.empty(); return spriteSheetItr != _spriteSheets.end() && !spriteSheetItr->second->frames.empty();
} }
SpriteFrame* SpriteFrameCache::findFrame(std::string_view frame) SpriteFrame* SpriteFrameCache::findFrame(const std::string& frame)
{ {
return _spriteFrames.at(frame); return _spriteFrames.at(frame);
} }
@ -379,7 +377,7 @@ void SpriteFrameCache::addSpriteFrameCapInset(SpriteFrame* spriteFrame, const Re
texture->addSpriteFrameCapInset(spriteFrame, capInsets); texture->addSpriteFrameCapInset(spriteFrame, capInsets);
} }
StringMap<SpriteFrame*>& SpriteFrameCache::getSpriteFrames() Map<std::string, SpriteFrame*>& SpriteFrameCache::getSpriteFrames()
{ {
return _spriteFrames; return _spriteFrames;
} }

View File

@ -117,7 +117,7 @@ public:
/** Adds multiple Sprite Frames from a plist file. /** Adds multiple Sprite Frames from a plist file.
* A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png. * A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png.
* If you want to use another texture, you should use the addSpriteFramesWithFile(std::string_view plist, const * If you want to use another texture, you should use the addSpriteFramesWithFile(const std::string& plist, const
* std::string& textureFileName) method. * std::string& textureFileName) method.
* @js addSpriteFrames * @js addSpriteFrames
* @lua addSpriteFrames * @lua addSpriteFrames
@ -125,7 +125,7 @@ public:
* @param spriteSheetFileName file name. * @param spriteSheetFileName file name.
* @param spriteSheetFormat * @param spriteSheetFormat
*/ */
void addSpriteFramesWithFile(std::string_view spriteSheetFileName, void addSpriteFramesWithFile(const std::string& spriteSheetFileName,
uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST); uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST);
/** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames.
@ -137,8 +137,8 @@ public:
* @param textureFileName Texture file name. * @param textureFileName Texture file name.
* @param spriteSheetFormat * @param spriteSheetFormat
*/ */
void addSpriteFramesWithFile(std::string_view spriteSheetFileName, void addSpriteFramesWithFile(const std::string& spriteSheetFileName,
std::string_view textureFileName, const std::string& textureFileName,
uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST); uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST);
/** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames.
@ -149,7 +149,7 @@ public:
* @param texture Texture pointer. * @param texture Texture pointer.
* @param spriteSheetFormat * @param spriteSheetFormat
*/ */
void addSpriteFramesWithFile(std::string_view spriteSheetFileName, void addSpriteFramesWithFile(const std::string& spriteSheetFileName,
Texture2D* texture, Texture2D* texture,
uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST); uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST);
@ -172,7 +172,7 @@ public:
* @param frame A certain sprite frame. * @param frame A certain sprite frame.
* @param frameName The name of the sprite frame. * @param frameName The name of the sprite frame.
*/ */
void addSpriteFrame(SpriteFrame* frame, std::string_view frameName); void addSpriteFrame(SpriteFrame* frame, const std::string& frameName);
/** Check if multiple Sprite Frames from a plist file have been loaded. /** Check if multiple Sprite Frames from a plist file have been loaded.
* @js NA * @js NA
@ -181,7 +181,7 @@ public:
* @param plist Plist file name. * @param plist Plist file name.
* @return True if the file is loaded. * @return True if the file is loaded.
*/ */
bool isSpriteFramesWithFileLoaded(std::string_view plist) const; bool isSpriteFramesWithFileLoaded(const std::string& plist) const;
/** Purges the dictionary of loaded sprite frames. /** Purges the dictionary of loaded sprite frames.
* Call this method if you receive the "Memory Warning". * Call this method if you receive the "Memory Warning".
@ -202,7 +202,7 @@ public:
* *
* @param name The name of the sprite frame that needs to removed. * @param name The name of the sprite frame that needs to removed.
*/ */
void removeSpriteFrameByName(std::string_view name); void removeSpriteFrameByName(const std::string& name);
/** Removes multiple Sprite Frames from a plist file. /** Removes multiple Sprite Frames from a plist file.
* Sprite Frames stored in this file will be removed. * Sprite Frames stored in this file will be removed.
@ -211,7 +211,7 @@ public:
* *
* @param plist The name of the plist that needs to removed. * @param plist The name of the plist that needs to removed.
*/ */
void removeSpriteFramesFromFile(std::string_view plist); void removeSpriteFramesFromFile(const std::string& plist);
/** Removes multiple Sprite Frames from a plist file content. /** Removes multiple Sprite Frames from a plist file content.
* Sprite Frames stored in this file will be removed. * Sprite Frames stored in this file will be removed.
@ -220,7 +220,7 @@ public:
* @param plist_content The string of the plist content that needs to removed. * @param plist_content The string of the plist content that needs to removed.
* @js NA * @js NA
*/ */
void removeSpriteFramesFromFileContent(std::string_view plist_content); void removeSpriteFramesFromFileContent(const std::string& plist_content);
/** Removes all Sprite Frames associated with the specified textures. /** Removes all Sprite Frames associated with the specified textures.
* It is convenient to call this method when a specific texture needs to be removed. * It is convenient to call this method when a specific texture needs to be removed.
@ -239,22 +239,22 @@ public:
* @param name A certain sprite frame name. * @param name A certain sprite frame name.
* @return The sprite frame. * @return The sprite frame.
*/ */
SpriteFrame* getSpriteFrameByName(std::string_view name); SpriteFrame* getSpriteFrameByName(const std::string& name);
bool reloadTexture(std::string_view spriteSheetFileName); bool reloadTexture(const std::string& spriteSheetFileName);
SpriteFrame* findFrame(std::string_view frame); SpriteFrame* findFrame(const std::string& frame);
/** Record SpriteFrame with plist and frame name, add frame name /** Record SpriteFrame with plist and frame name, add frame name
* and plist to index * and plist to index
*/ */
void insertFrame(const std::shared_ptr<SpriteSheet>& spriteSheet, void insertFrame(const std::shared_ptr<SpriteSheet>& spriteSheet,
std::string_view frameName, const std::string& frameName,
SpriteFrame* frameObj); SpriteFrame* frameObj);
/** Delete frame from cache, rebuild index /** Delete frame from cache, rebuild index
*/ */
bool eraseFrame(std::string_view frameName); bool eraseFrame(const std::string& frameName);
void addSpriteFrameCapInset(SpriteFrame* spriteFrame, const Rect& capInsets, Texture2D* texture); void addSpriteFrameCapInset(SpriteFrame* spriteFrame, const Rect& capInsets, Texture2D* texture);
@ -277,35 +277,30 @@ protected:
bool eraseFrames(const std::vector<std::string>& frame); bool eraseFrames(const std::vector<std::string>& frame);
/** Delete frame from index and SpriteFrame is kept. /** Delete frame from index and SpriteFrame is kept.
*/ */
bool removeSpriteSheet(std::string_view spriteSheetFileName); bool removeSpriteSheet(const std::string& spriteSheetFileName);
/** Clear index and all SpriteFrames. /** Clear index and all SpriteFrames.
*/ */
void clear(); void clear();
inline bool hasFrame(std::string_view frame) const; inline bool hasFrame(const std::string& frame) const;
inline bool isSpriteSheetInUse(std::string_view spriteSheetFileName) const; inline bool isSpriteSheetInUse(const std::string& spriteSheetFileName) const;
inline StringMap<SpriteFrame*>& getSpriteFrames(); inline Map<std::string, SpriteFrame*>& getSpriteFrames();
void markPlistFull(std::string_view spriteSheetFileName, bool full) void markPlistFull(const std::string& spriteSheetFileName, bool full)
{ {
// _spriteSheets[spriteSheetFileName]->full = full; _spriteSheets[spriteSheetFileName]->full = full;
auto it = _spriteSheets.find(spriteSheetFileName);
if (it != _spriteSheets.end())
{
it.value()->full = full;
}
} }
bool isPlistFull(std::string_view spriteSheetFileName) const bool isPlistFull(const std::string& spriteSheetFileName) const
{ {
auto it = _spriteSheets.find(spriteSheetFileName); auto&& it = _spriteSheets.find(spriteSheetFileName);
return it == _spriteSheets.end() ? false : it->second->full; return it == _spriteSheets.end() ? false : it->second->full;
} }
private: private:
StringMap<SpriteFrame*> _spriteFrames; Map<std::string, SpriteFrame*> _spriteFrames;
hlookup::string_map<std::shared_ptr<SpriteSheet>> _spriteSheets; std::unordered_map<std::string, std::shared_ptr<SpriteSheet>> _spriteSheets;
hlookup::string_map<std::shared_ptr<SpriteSheet>> _spriteFrameToSpriteSheetMap; std::unordered_map<std::string, std::shared_ptr<SpriteSheet>> _spriteFrameToSpriteSheetMap;
std::map<uint32_t, std::shared_ptr<ISpriteSheetLoader>> _spriteSheetLoaders; std::map<uint32_t, std::shared_ptr<ISpriteSheetLoader>> _spriteSheetLoaders;
}; };

View File

@ -65,20 +65,20 @@ class SpriteSheet
public: public:
std::string path; std::string path;
uint32_t format; uint32_t format;
hlookup::string_set frames; std::set<std::string> frames;
bool full = false; bool full = false;
}; };
class ISpriteSheetLoader class ISpriteSheetLoader
{ {
public: public:
virtual ~ISpriteSheetLoader() = default; virtual ~ISpriteSheetLoader() = default;
virtual uint32_t getFormat() = 0; virtual uint32_t getFormat() = 0;
virtual void load(std::string_view filePath, SpriteFrameCache& cache) = 0; virtual void load(const std::string& filePath, SpriteFrameCache& cache) = 0;
virtual void load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) = 0; virtual void load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) = 0;
virtual void load(std::string_view filePath, std::string_view textureFileName, SpriteFrameCache& cache) = 0; virtual void load(const std::string& filePath, const std::string& textureFileName, SpriteFrameCache& cache) = 0;
virtual void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) = 0; virtual void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) = 0;
virtual void reload(std::string_view filePath, SpriteFrameCache& cache) = 0; virtual void reload(const std::string& filePath, SpriteFrameCache& cache) = 0;
}; };
class SpriteSheetLoader : public ISpriteSheetLoader class SpriteSheetLoader : public ISpriteSheetLoader
@ -92,12 +92,12 @@ public:
const std::vector<int>& triangleIndices, const std::vector<int>& triangleIndices,
PolygonInfo& polygonInfo); PolygonInfo& polygonInfo);
uint32_t getFormat() override = 0; uint32_t getFormat() override = 0;
void load(std::string_view filePath, SpriteFrameCache& cache) override = 0; void load(const std::string& filePath, SpriteFrameCache& cache) override = 0;
void load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) override = 0; void load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) override = 0;
void load(std::string_view filePath, std::string_view textureFileName, SpriteFrameCache& cache) override = 0; void load(const std::string& filePath, const std::string& textureFileName, SpriteFrameCache& cache) override = 0;
void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) override = 0; void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) override = 0;
void reload(std::string_view filePath, SpriteFrameCache& cache) override = 0; void reload(const std::string& filePath, SpriteFrameCache& cache) override = 0;
}; };
// end of _2d group // end of _2d group

View File

@ -40,7 +40,7 @@ TMXObjectGroup::~TMXObjectGroup()
CCLOGINFO("deallocing TMXObjectGroup: %p", this); CCLOGINFO("deallocing TMXObjectGroup: %p", this);
} }
ValueMap TMXObjectGroup::getObject(std::string_view objectName) const ValueMap TMXObjectGroup::getObject(const std::string& objectName) const
{ {
if (!_objects.empty()) if (!_objects.empty())
{ {
@ -59,7 +59,7 @@ ValueMap TMXObjectGroup::getObject(std::string_view objectName) const
return ValueMap(); return ValueMap();
} }
Value TMXObjectGroup::getProperty(std::string_view propertyName) const Value TMXObjectGroup::getProperty(const std::string& propertyName) const
{ {
if (_properties.find(propertyName) != _properties.end()) if (_properties.find(propertyName) != _properties.end())
return _properties.at(propertyName); return _properties.at(propertyName);

View File

@ -60,13 +60,13 @@ public:
* *
* @return The group name. * @return The group name.
*/ */
std::string_view getGroupName() const { return _groupName; } const std::string& getGroupName() const { return _groupName; }
/** Set the group name. /** Set the group name.
* *
* @param groupName A string,it is used to set the group name. * @param groupName A string,it is used to set the group name.
*/ */
void setGroupName(std::string_view groupName) { _groupName = groupName; } void setGroupName(const std::string& groupName) { _groupName = groupName; }
/** Return the value for the specific property name. /** Return the value for the specific property name.
* *
@ -74,14 +74,14 @@ public:
* @return Return the value for the specific property name. * @return Return the value for the specific property name.
* @js NA * @js NA
*/ */
Value getProperty(std::string_view propertyName) const; Value getProperty(const std::string& propertyName) const;
/** Return the dictionary for the specific object name. /** Return the dictionary for the specific object name.
* It will return the 1st object found on the array for the given name. * It will return the 1st object found on the array for the given name.
* *
* @return Return the dictionary for the specific object name. * @return Return the dictionary for the specific object name.
*/ */
ValueMap getObject(std::string_view objectName) const; ValueMap getObject(const std::string& objectName) const;
/** Gets the offset position of child objects. /** Gets the offset position of child objects.
* *

View File

@ -92,7 +92,7 @@ Rect TMXTilesetInfo::getRectForGID(uint32_t gid)
// implementation TMXMapInfo // implementation TMXMapInfo
TMXMapInfo* TMXMapInfo::create(std::string_view tmxFile) TMXMapInfo* TMXMapInfo::create(const std::string& tmxFile)
{ {
TMXMapInfo* ret = new TMXMapInfo(); TMXMapInfo* ret = new TMXMapInfo();
if (ret->initWithTMXFile(tmxFile)) if (ret->initWithTMXFile(tmxFile))
@ -104,7 +104,7 @@ TMXMapInfo* TMXMapInfo::create(std::string_view tmxFile)
return nullptr; return nullptr;
} }
TMXMapInfo* TMXMapInfo::createWithXML(std::string_view tmxString, std::string_view resourcePath) TMXMapInfo* TMXMapInfo::createWithXML(const std::string& tmxString, const std::string& resourcePath)
{ {
TMXMapInfo* ret = new TMXMapInfo(); TMXMapInfo* ret = new TMXMapInfo();
if (ret->initWithXML(tmxString, resourcePath)) if (ret->initWithXML(tmxString, resourcePath))
@ -116,7 +116,7 @@ TMXMapInfo* TMXMapInfo::createWithXML(std::string_view tmxString, std::string_vi
return nullptr; return nullptr;
} }
void TMXMapInfo::internalInit(std::string_view tmxFileName, std::string_view resourcePath) void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string& resourcePath)
{ {
if (!tmxFileName.empty()) if (!tmxFileName.empty())
{ {
@ -138,13 +138,13 @@ void TMXMapInfo::internalInit(std::string_view tmxFileName, std::string_view res
_currentFirstGID = -1; _currentFirstGID = -1;
} }
bool TMXMapInfo::initWithXML(std::string_view tmxString, std::string_view resourcePath) bool TMXMapInfo::initWithXML(const std::string& tmxString, const std::string& resourcePath)
{ {
internalInit("", resourcePath); internalInit("", resourcePath);
return parseXMLString(tmxString); return parseXMLString(tmxString);
} }
bool TMXMapInfo::initWithTMXFile(std::string_view tmxFile) bool TMXMapInfo::initWithTMXFile(const std::string& tmxFile)
{ {
internalInit(tmxFile, ""); internalInit(tmxFile, "");
return parseXMLFile(_TMXFileName); return parseXMLFile(_TMXFileName);
@ -171,7 +171,7 @@ TMXMapInfo::~TMXMapInfo()
CCLOGINFO("deallocing TMXMapInfo: %p", this); CCLOGINFO("deallocing TMXMapInfo: %p", this);
} }
bool TMXMapInfo::parseXMLString(std::string_view xmlString) bool TMXMapInfo::parseXMLString(const std::string& xmlString)
{ {
size_t len = xmlString.size(); size_t len = xmlString.size();
if (len <= 0) if (len <= 0)
@ -186,10 +186,10 @@ bool TMXMapInfo::parseXMLString(std::string_view xmlString)
parser.setDelegator(this); parser.setDelegator(this);
return parser.parse(xmlString.data(), len); return parser.parse(xmlString.c_str(), len);
} }
bool TMXMapInfo::parseXMLFile(std::string_view xmlFilename) bool TMXMapInfo::parseXMLFile(const std::string& xmlFilename)
{ {
SAXParser parser; SAXParser parser;
@ -265,7 +265,7 @@ void TMXMapInfo::startElement(void* /*ctx*/, const char* name, const char** atts
tmxMapInfo->setStaggerIndex(TMXStaggerIndex_Even); tmxMapInfo->setStaggerIndex(TMXStaggerIndex_Even);
} }
auto hexSideLength = attributeDict["hexsidelength"].asInt(); float hexSideLength = attributeDict["hexsidelength"].asFloat();
tmxMapInfo->setHexSideLength(hexSideLength); tmxMapInfo->setHexSideLength(hexSideLength);
Vec2 s; Vec2 s;
@ -348,7 +348,7 @@ void TMXMapInfo::startElement(void* /*ctx*/, const char* name, const char** atts
TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
Vec2 layerSize = layer->_layerSize; Vec2 layerSize = layer->_layerSize;
uint32_t gid = static_cast<uint32_t>(attributeDict["gid"].asUnsignedInt()); uint32_t gid = static_cast<uint32_t>(attributeDict["gid"].asUnsignedInt());
int tilesAmount = static_cast<int>(layerSize.width * layerSize.height); int tilesAmount = layerSize.width * layerSize.height;
if (_xmlTileIndex < tilesAmount) if (_xmlTileIndex < tilesAmount)
{ {
@ -443,7 +443,7 @@ void TMXMapInfo::startElement(void* /*ctx*/, const char* name, const char** atts
TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
Vec2 layerSize = layer->_layerSize; Vec2 layerSize = layer->_layerSize;
int tilesAmount = static_cast<int>(layerSize.width * layerSize.height); int tilesAmount = layerSize.width * layerSize.height;
uint32_t* tiles = (uint32_t*)malloc(tilesAmount * sizeof(uint32_t)); uint32_t* tiles = (uint32_t*)malloc(tilesAmount * sizeof(uint32_t));
// set all value to 0 // set all value to 0
@ -688,10 +688,10 @@ void TMXMapInfo::endElement(void* /*ctx*/, const char* name)
TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
auto currentString = tmxMapInfo->getCurrentString(); std::string currentString = tmxMapInfo->getCurrentString();
unsigned char* buffer; unsigned char* buffer;
auto len = auto len =
base64Decode((unsigned char*)currentString.data(), (unsigned int)currentString.length(), &buffer); base64Decode((unsigned char*)currentString.c_str(), (unsigned int)currentString.length(), &buffer);
if (!buffer) if (!buffer)
{ {
CCLOG("cocos2d: TiledMap: decode data error"); CCLOG("cocos2d: TiledMap: decode data error");
@ -733,11 +733,10 @@ void TMXMapInfo::endElement(void* /*ctx*/, const char* name)
TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
tmxMapInfo->setStoringCharacters(false); tmxMapInfo->setStoringCharacters(false);
auto currentString = tmxMapInfo->getCurrentString(); std::string currentString = tmxMapInfo->getCurrentString();
vector<string> gidTokens; vector<string> gidTokens;
std::stringstream filestr; istringstream filestr(currentString);
filestr << currentString;
string sRow; string sRow;
while (getline(filestr, sRow, '\n')) while (getline(filestr, sRow, '\n'))
{ {
@ -811,7 +810,7 @@ void TMXMapInfo::textHandler(void* /*ctx*/, const char* ch, size_t len)
if (tmxMapInfo->isStoringCharacters()) if (tmxMapInfo->isStoringCharacters())
{ {
std::string currentString{tmxMapInfo->getCurrentString()}; std::string currentString = tmxMapInfo->getCurrentString();
currentString += text; currentString += text;
tmxMapInfo->setCurrentString(currentString); tmxMapInfo->setCurrentString(currentString);
} }

View File

@ -250,9 +250,9 @@ class CC_DLL TMXMapInfo : public Ref, public SAXDelegator
{ {
public: public:
/** creates a TMX Format with a tmx file */ /** creates a TMX Format with a tmx file */
static TMXMapInfo* create(std::string_view tmxFile); static TMXMapInfo* create(const std::string& tmxFile);
/** creates a TMX Format with an XML string and a TMX resource path */ /** creates a TMX Format with an XML string and a TMX resource path */
static TMXMapInfo* createWithXML(std::string_view tmxString, std::string_view resourcePath); static TMXMapInfo* createWithXML(const std::string& tmxString, const std::string& resourcePath);
/** /**
* @js ctor * @js ctor
@ -265,13 +265,13 @@ public:
virtual ~TMXMapInfo(); virtual ~TMXMapInfo();
/** initializes a TMX format with a tmx file */ /** initializes a TMX format with a tmx file */
bool initWithTMXFile(std::string_view tmxFile); bool initWithTMXFile(const std::string& tmxFile);
/** initializes a TMX format with an XML string and a TMX resource path */ /** initializes a TMX format with an XML string and a TMX resource path */
bool initWithXML(std::string_view tmxString, std::string_view resourcePath); bool initWithXML(const std::string& tmxString, const std::string& resourcePath);
/** initializes parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */ /** initializes parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */
bool parseXMLFile(std::string_view xmlFilename); bool parseXMLFile(const std::string& xmlFilename);
/* initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */ /* initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */
bool parseXMLString(std::string_view xmlString); bool parseXMLString(const std::string& xmlString);
ValueMapIntKey& getTileProperties() { return _tileProperties; }; ValueMapIntKey& getTileProperties() { return _tileProperties; };
void setTileProperties(const ValueMapIntKey& tileProperties) { _tileProperties = tileProperties; } void setTileProperties(const ValueMapIntKey& tileProperties) { _tileProperties = tileProperties; }
@ -353,14 +353,14 @@ public:
*/ */
void textHandler(void* ctx, const char* ch, size_t len) override; void textHandler(void* ctx, const char* ch, size_t len) override;
std::string_view getCurrentString() const { return _currentString; } const std::string& getCurrentString() const { return _currentString; }
void setCurrentString(std::string_view currentString) { _currentString = currentString; } void setCurrentString(const std::string& currentString) { _currentString = currentString; }
std::string_view getTMXFileName() const { return _TMXFileName; } const std::string& getTMXFileName() const { return _TMXFileName; }
void setTMXFileName(std::string_view fileName) { _TMXFileName = fileName; } void setTMXFileName(const std::string& fileName) { _TMXFileName = fileName; }
std::string_view getExternalTilesetFileName() const { return _externalTilesetFilename; } const std::string& getExternalTilesetFileName() const { return _externalTilesetFilename; }
protected: protected:
void internalInit(std::string_view tmxFileName, std::string_view resourcePath); void internalInit(const std::string& tmxFileName, const std::string& resourcePath);
/// map orientation /// map orientation
int _orientation; int _orientation;

View File

@ -109,10 +109,10 @@ TextFieldTTF::~TextFieldTTF() {}
// static constructor // static constructor
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(std::string_view placeholder, TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder,
const Vec2& dimensions, const Vec2& dimensions,
TextHAlignment alignment, TextHAlignment alignment,
std::string_view fontName, const std::string& fontName,
float fontSize) float fontSize)
{ {
TextFieldTTF* ret = new TextFieldTTF(); TextFieldTTF* ret = new TextFieldTTF();
@ -129,8 +129,8 @@ TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(std::string_view placeholde
return nullptr; return nullptr;
} }
TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(std::string_view placeholder, TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder,
std::string_view fontName, const std::string& fontName,
float fontSize) float fontSize)
{ {
TextFieldTTF* ret = new TextFieldTTF(); TextFieldTTF* ret = new TextFieldTTF();
@ -151,10 +151,10 @@ TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(std::string_view placeholde
// initialize // initialize
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
bool TextFieldTTF::initWithPlaceHolder(std::string_view placeholder, bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder,
const Vec2& dimensions, const Vec2& dimensions,
TextHAlignment alignment, TextHAlignment alignment,
std::string_view fontName, const std::string& fontName,
float fontSize) float fontSize)
{ {
setDimensions(dimensions.width, dimensions.height); setDimensions(dimensions.width, dimensions.height);
@ -162,7 +162,7 @@ bool TextFieldTTF::initWithPlaceHolder(std::string_view placeholder,
return initWithPlaceHolder(placeholder, fontName, fontSize); return initWithPlaceHolder(placeholder, fontName, fontSize);
} }
bool TextFieldTTF::initWithPlaceHolder(std::string_view placeholder, std::string_view fontName, float fontSize) bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize)
{ {
_placeHolder = placeholder; _placeHolder = placeholder;
@ -366,7 +366,7 @@ void TextFieldTTF::deleteBackward()
} }
} }
std::string_view TextFieldTTF::getContentText() const std::string& TextFieldTTF::getContentText()
{ {
return _inputText; return _inputText;
} }
@ -573,9 +573,9 @@ void TextFieldTTF::setString(std::string_view text)
_charCount = charCount; _charCount = charCount;
} }
void TextFieldTTF::appendString(std::string_view text) void TextFieldTTF::appendString(const std::string& text)
{ {
insertText(text.data(), text.length()); insertText(text.c_str(), text.length());
} }
void TextFieldTTF::makeStringSupportCursor(std::string& displayText) void TextFieldTTF::makeStringSupportCursor(std::string& displayText)
@ -677,13 +677,13 @@ void TextFieldTTF::controlKey(EventKeyboard::KeyCode keyCode)
} }
} }
std::string_view TextFieldTTF::getString() const const std::string& TextFieldTTF::getString() const
{ {
return _inputText; return _inputText;
} }
// place holder text property // place holder text property
void TextFieldTTF::setPlaceHolder(std::string_view text) void TextFieldTTF::setPlaceHolder(const std::string& text)
{ {
_placeHolder = text; _placeHolder = text;
if (_inputText.empty() && !_isAttachWithIME) if (_inputText.empty() && !_isAttachWithIME)
@ -693,7 +693,7 @@ void TextFieldTTF::setPlaceHolder(std::string_view text)
} }
} }
std::string_view TextFieldTTF::getPlaceHolder() const const std::string& TextFieldTTF::getPlaceHolder() const
{ {
return _placeHolder; return _placeHolder;
} }
@ -733,7 +733,7 @@ void TextFieldTTF::setSecureTextEntry(bool value)
} }
} }
void TextFieldTTF::setPasswordTextStyle(std::string_view text) void TextFieldTTF::setPasswordTextStyle(const std::string& text)
{ {
if (text.length() < 1) if (text.length() < 1)
{ {
@ -747,7 +747,7 @@ void TextFieldTTF::setPasswordTextStyle(std::string_view text)
} }
} }
std::string_view TextFieldTTF::getPasswordTextStyle() const const std::string& TextFieldTTF::getPasswordTextStyle() const
{ {
return _passwordStyleText; return _passwordStyleText;
} }

View File

@ -98,28 +98,28 @@ public:
/** Creates a TextFieldTTF from a fontname, alignment, dimension and font size. /** Creates a TextFieldTTF from a fontname, alignment, dimension and font size.
* @js NA * @js NA
*/ */
static TextFieldTTF* textFieldWithPlaceHolder(std::string_view placeholder, static TextFieldTTF* textFieldWithPlaceHolder(const std::string& placeholder,
const Vec2& dimensions, const Vec2& dimensions,
TextHAlignment alignment, TextHAlignment alignment,
std::string_view fontName, const std::string& fontName,
float fontSize); float fontSize);
/** Creates a TextFieldTTF from a fontname and font size. /** Creates a TextFieldTTF from a fontname and font size.
* @js NA * @js NA
*/ */
static TextFieldTTF* textFieldWithPlaceHolder(std::string_view placeholder, static TextFieldTTF* textFieldWithPlaceHolder(const std::string& placeholder,
std::string_view fontName, const std::string& fontName,
float fontSize); float fontSize);
/** Initializes the TextFieldTTF with a font name, alignment, dimension and font size. */ /** Initializes the TextFieldTTF with a font name, alignment, dimension and font size. */
bool initWithPlaceHolder(std::string_view placeholder, bool initWithPlaceHolder(const std::string& placeholder,
const Vec2& dimensions, const Vec2& dimensions,
TextHAlignment alignment, TextHAlignment alignment,
std::string_view fontName, const std::string& fontName,
float fontSize); float fontSize);
/** Initializes the TextFieldTTF with a font name and font size. */ /** Initializes the TextFieldTTF with a font name and font size. */
bool initWithPlaceHolder(std::string_view placeholder, std::string_view fontName, float fontSize); bool initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize);
/** /**
*@brief Open keyboard and receive input text. *@brief Open keyboard and receive input text.
@ -183,26 +183,26 @@ public:
* Append to input text of TextField. * Append to input text of TextField.
*@param text The append text of TextField. *@param text The append text of TextField.
*/ */
virtual void appendString(std::string_view text); virtual void appendString(const std::string& text);
/** /**
* Query the input text of TextField. * Query the input text of TextField.
*@return Get the input text of TextField. *@return Get the input text of TextField.
*/ */
virtual std::string_view getString() const override; virtual const std::string& getString() const override;
/** /**
* Change placeholder text. * Change placeholder text.
* place holder text displayed when there is no text in the text field. * place holder text displayed when there is no text in the text field.
*@param text The placeholder string. *@param text The placeholder string.
*/ */
virtual void setPlaceHolder(std::string_view text); virtual void setPlaceHolder(const std::string& text);
/** /**
* Query the placeholder string. * Query the placeholder string.
*@return The placeholder string. *@return The placeholder string.
*/ */
virtual std::string_view getPlaceHolder() const; virtual const std::string& getPlaceHolder() const;
/** /**
* Set enable secure text entry representation. * Set enable secure text entry representation.
@ -211,8 +211,8 @@ public:
* @js NA * @js NA
*/ */
virtual void setSecureTextEntry(bool value); virtual void setSecureTextEntry(bool value);
virtual void setPasswordTextStyle(std::string_view text); virtual void setPasswordTextStyle(const std::string& text);
std::string_view getPasswordTextStyle() const; const std::string& getPasswordTextStyle() const;
/** /**
* Query whether the currently display mode is secure text entry or not. * Query whether the currently display mode is secure text entry or not.
@ -260,7 +260,7 @@ protected:
virtual void didDetachWithIME() override; virtual void didDetachWithIME() override;
virtual void insertText(const char* text, size_t len) override; virtual void insertText(const char* text, size_t len) override;
virtual void deleteBackward() override; virtual void deleteBackward() override;
virtual std::string_view getContentText() override; virtual const std::string& getContentText() override;
virtual void controlKey(EventKeyboard::KeyCode keyCode) override; virtual void controlKey(EventKeyboard::KeyCode keyCode) override;
TextFieldDelegate* _delegate; TextFieldDelegate* _delegate;

View File

@ -36,7 +36,7 @@ NS_CC_BEGIN
// implementation TileMapAtlas // implementation TileMapAtlas
TileMapAtlas* TileMapAtlas::create(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight) TileMapAtlas* TileMapAtlas::create(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight)
{ {
TileMapAtlas* ret = new TileMapAtlas(); TileMapAtlas* ret = new TileMapAtlas();
if (ret->initWithTileFile(tile, mapFile, tileWidth, tileHeight)) if (ret->initWithTileFile(tile, mapFile, tileWidth, tileHeight))
@ -48,7 +48,7 @@ TileMapAtlas* TileMapAtlas::create(std::string_view tile, std::string_view mapFi
return nullptr; return nullptr;
} }
bool TileMapAtlas::initWithTileFile(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight) bool TileMapAtlas::initWithTileFile(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight)
{ {
this->loadTGAfile(mapFile); this->loadTGAfile(mapFile);
this->calculateItemsToRender(); this->calculateItemsToRender();
@ -100,7 +100,7 @@ void TileMapAtlas::calculateItemsToRender()
} }
} }
void TileMapAtlas::loadTGAfile(std::string_view file) void TileMapAtlas::loadTGAfile(const std::string& file)
{ {
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(file); std::string fullPath = FileUtils::getInstance()->fullPathForFilename(file);

View File

@ -59,7 +59,7 @@ public:
/** creates a TileMap with a tile file (atlas) with a map file and the width and height of each tile in points. /** creates a TileMap with a tile file (atlas) with a map file and the width and height of each tile in points.
The tile file will be loaded using the TextureMgr. The tile file will be loaded using the TextureMgr.
*/ */
static TileMapAtlas* create(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight); static TileMapAtlas* create(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight);
/** /**
* @js ctor * @js ctor
*/ */
@ -73,7 +73,7 @@ public:
/** initializes a TileMap with a tile file (atlas) with a map file and the width and height of each tile in points. /** initializes a TileMap with a tile file (atlas) with a map file and the width and height of each tile in points.
The file will be loaded using the TextureMgr. The file will be loaded using the TextureMgr.
*/ */
bool initWithTileFile(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight); bool initWithTileFile(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight);
/** /**
* Returns a tile from position x,y. * Returns a tile from position x,y.
*For the moment only channel R is used *For the moment only channel R is used
@ -100,7 +100,7 @@ public:
void setTGAInfo(struct sImageTGA* TGAInfo) { _TGAInfo = TGAInfo; } void setTGAInfo(struct sImageTGA* TGAInfo) { _TGAInfo = TGAInfo; }
protected: protected:
void loadTGAfile(std::string_view file); void loadTGAfile(const std::string& file);
void calculateItemsToRender(); void calculateItemsToRender();
void updateAtlasValueAt(const Vec2& pos, const Color3B& value, int index); void updateAtlasValueAt(const Vec2& pos, const Color3B& value, int index);
void updateAtlasValues(); void updateAtlasValues();

View File

@ -128,9 +128,9 @@ Animate3D* Animate3D::reverse() const
return animate; return animate;
} }
Node* findChildByNameRecursively(Node* node, std::string_view childName) Node* findChildByNameRecursively(Node* node, const std::string& childName)
{ {
std::string_view name = node->getName(); const std::string& name = node->getName();
if (name == childName) if (name == childName)
return node; return node;
@ -162,11 +162,11 @@ void Animate3D::startWithTarget(Node* target)
{ {
if (_animation) if (_animation)
{ {
auto& boneCurves = _animation->getBoneCurves(); const std::unordered_map<std::string, Animation3D::Curve*>& boneCurves = _animation->getBoneCurves();
for (const auto& iter : boneCurves) for (const auto& iter : boneCurves)
{ {
std::string_view boneName = iter.first; const std::string& boneName = iter.first;
auto skin = sprite->getSkeleton(); auto skin = sprite->getSkeleton();
if (skin) if (skin)
{ {
auto bone = skin->getBoneByName(boneName); auto bone = skin->getBoneByName(boneName);
@ -200,11 +200,11 @@ void Animate3D::startWithTarget(Node* target)
} }
else else
{ {
auto& boneCurves = _animation->getBoneCurves(); const std::unordered_map<std::string, Animation3D::Curve*>& boneCurves = _animation->getBoneCurves();
for (const auto& iter : boneCurves) for (const auto& iter : boneCurves)
{ {
std::string_view boneName = iter.first; const std::string& boneName = iter.first;
Node* node = nullptr; Node* node = nullptr;
if (target->getName() == boneName) if (target->getName() == boneName)
node = target; node = target;
else else

View File

@ -29,11 +29,11 @@
NS_CC_BEGIN NS_CC_BEGIN
Animation3D* Animation3D::create(std::string_view fileName, std::string_view animationName) Animation3D* Animation3D::create(const std::string& fileName, const std::string& animationName)
{ {
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName); std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName);
fullPath.append("#").append(animationName); std::string key = fullPath + "#" + animationName;
auto animation = Animation3DCache::getInstance()->getAnimation(fullPath); auto animation = Animation3DCache::getInstance()->getAnimation(key);
if (animation != nullptr) if (animation != nullptr)
return animation; return animation;
@ -50,7 +50,7 @@ Animation3D* Animation3D::create(std::string_view fileName, std::string_view ani
return animation; return animation;
} }
bool Animation3D::initWithFile(std::string_view filename, std::string_view animationName) bool Animation3D::initWithFile(const std::string& filename, const std::string& animationName)
{ {
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename); std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename);
@ -59,8 +59,8 @@ bool Animation3D::initWithFile(std::string_view filename, std::string_view anima
Animation3DData animationdata; Animation3DData animationdata;
if (bundle->load(fullPath) && bundle->loadAnimationData(animationName, &animationdata) && init(animationdata)) if (bundle->load(fullPath) && bundle->loadAnimationData(animationName, &animationdata) && init(animationdata))
{ {
fullPath.append("#").append(animationName); std::string key = fullPath + "#" + animationName;
Animation3DCache::getInstance()->addAnimation(fullPath, this); Animation3DCache::getInstance()->addAnimation(key, this);
Bundle3D::destroyBundle(bundle); Bundle3D::destroyBundle(bundle);
return true; return true;
} }
@ -70,7 +70,7 @@ bool Animation3D::initWithFile(std::string_view filename, std::string_view anima
return false; return false;
} }
Animation3D::Curve* Animation3D::getBoneCurveByName(std::string_view name) const Animation3D::Curve* Animation3D::getBoneCurveByName(const std::string& name) const
{ {
auto it = _boneCurves.find(name); auto it = _boneCurves.find(name);
if (it != _boneCurves.end()) if (it != _boneCurves.end())
@ -199,7 +199,7 @@ void Animation3DCache::destroyInstance()
CC_SAFE_DELETE(_cacheInstance); CC_SAFE_DELETE(_cacheInstance);
} }
Animation3D* Animation3DCache::getAnimation(std::string_view key) Animation3D* Animation3DCache::getAnimation(const std::string& key)
{ {
auto it = _animations.find(key); auto it = _animations.find(key);
if (it != _animations.end()) if (it != _animations.end())
@ -207,14 +207,14 @@ Animation3D* Animation3DCache::getAnimation(std::string_view key)
return nullptr; return nullptr;
} }
void Animation3DCache::addAnimation(std::string_view key, Animation3D* animation) void Animation3DCache::addAnimation(const std::string& key, Animation3D* animation)
{ {
const auto& it = _animations.find(key); const auto& it = _animations.find(key);
if (it != _animations.end()) if (it != _animations.end())
{ {
return; // already have this key return; // already have this key
} }
_animations.emplace(key, animation); //_animations[key] = animation; _animations[key] = animation;
animation->retain(); animation->retain();
} }

View File

@ -69,7 +69,7 @@ public:
}; };
/**read all animation or only the animation with given animationName? animationName == "" read the first.*/ /**read all animation or only the animation with given animationName? animationName == "" read the first.*/
static Animation3D* create(std::string_view filename, std::string_view animationName = ""); static Animation3D* create(const std::string& filename, const std::string& animationName = "");
/**get duration*/ /**get duration*/
float getDuration() const { return _duration; } float getDuration() const { return _duration; }
@ -79,10 +79,10 @@ public:
* *
* @lua NA * @lua NA
*/ */
Curve* getBoneCurveByName(std::string_view name) const; Curve* getBoneCurveByName(const std::string& name) const;
/**get the bone Curves set*/ /**get the bone Curves set*/
const hlookup::string_map<Curve*>& getBoneCurves() const { return _boneCurves; } const std::unordered_map<std::string, Curve*>& getBoneCurves() const { return _boneCurves; }
CC_CONSTRUCTOR_ACCESS : Animation3D(); CC_CONSTRUCTOR_ACCESS : Animation3D();
virtual ~Animation3D(); virtual ~Animation3D();
@ -90,10 +90,10 @@ public:
bool init(const Animation3DData& data); bool init(const Animation3DData& data);
/**init Animation3D with file name and animation name*/ /**init Animation3D with file name and animation name*/
bool initWithFile(std::string_view filename, std::string_view animationName); bool initWithFile(const std::string& filename, const std::string& animationName);
protected: protected:
hlookup::string_map<Curve*> _boneCurves; // bone curves map, key bone name, value AnimationCurve std::unordered_map<std::string, Curve*> _boneCurves; // bone curves map, key bone name, value AnimationCurve
float _duration; // animation duration float _duration; // animation duration
}; };
@ -109,10 +109,10 @@ public:
static void destroyInstance(); static void destroyInstance();
/**get animation by key*/ /**get animation by key*/
Animation3D* getAnimation(std::string_view key); Animation3D* getAnimation(const std::string& key);
/**add animation to cache*/ /**add animation to cache*/
void addAnimation(std::string_view key, Animation3D* animation); void addAnimation(const std::string& key, Animation3D* animation);
/**remove all animation*/ /**remove all animation*/
void removeAllAnimations(); void removeAllAnimations();
@ -125,7 +125,7 @@ protected:
static Animation3DCache* _cacheInstance; // cache instance static Animation3DCache* _cacheInstance; // cache instance
hlookup::string_map<Animation3D*> _animations; // cached animations std::unordered_map<std::string, Animation3D*> _animations; // cached animations
}; };
// end of 3d group // end of 3d group

View File

@ -53,7 +53,7 @@ BillBoard* BillBoard::createWithTexture(Texture2D* texture, Mode mode)
return nullptr; return nullptr;
} }
BillBoard* BillBoard::create(std::string_view filename, Mode mode) BillBoard* BillBoard::create(const std::string& filename, Mode mode)
{ {
BillBoard* billboard = new BillBoard(); BillBoard* billboard = new BillBoard();
if (billboard->initWithFile(filename)) if (billboard->initWithFile(filename))
@ -66,7 +66,7 @@ BillBoard* BillBoard::create(std::string_view filename, Mode mode)
return nullptr; return nullptr;
} }
BillBoard* BillBoard::create(std::string_view filename, const Rect& rect, Mode mode) BillBoard* BillBoard::create(const std::string& filename, const Rect& rect, Mode mode)
{ {
BillBoard* billboard = new BillBoard(); BillBoard* billboard = new BillBoard();
if (billboard->initWithFile(filename, rect)) if (billboard->initWithFile(filename, rect))

View File

@ -63,7 +63,7 @@ public:
* @param filename A path to image file, e.g., "scene1/monster.png" * @param filename A path to image file, e.g., "scene1/monster.png"
* @return An autoreleased BillBoard object. * @return An autoreleased BillBoard object.
*/ */
static BillBoard* create(std::string_view filename, Mode mode = Mode::VIEW_POINT_ORIENTED); static BillBoard* create(const std::string& filename, Mode mode = Mode::VIEW_POINT_ORIENTED);
/** /**
* Creates a BillBoard with an image filename and a rect. * Creates a BillBoard with an image filename and a rect.
@ -72,7 +72,7 @@ public:
* @param rect A subrect of the image file * @param rect A subrect of the image file
* @return An autoreleased BillBoard object * @return An autoreleased BillBoard object
*/ */
static BillBoard* create(std::string_view filename, const Rect& rect, Mode mode = Mode::VIEW_POINT_ORIENTED); static BillBoard* create(const std::string& filename, const Rect& rect, Mode mode = Mode::VIEW_POINT_ORIENTED);
/** /**
* Creates a BillBoard with a Texture2D object. * Creates a BillBoard with a Texture2D object.

View File

@ -169,7 +169,7 @@ void Bundle3D::clear()
} }
} }
bool Bundle3D::load(std::string_view path) bool Bundle3D::load(const std::string& path)
{ {
if (path.empty()) if (path.empty())
return false; return false;
@ -193,7 +193,7 @@ bool Bundle3D::load(std::string_view path)
} }
else else
{ {
CCLOG("warning: %s is invalid file formate", path.data()); CCLOG("warning: %s is invalid file formate", path.c_str());
} }
ret ? (_path = path) : (_path = ""); ret ? (_path = path) : (_path = "");
@ -204,7 +204,7 @@ bool Bundle3D::load(std::string_view path)
bool Bundle3D::loadObj(MeshDatas& meshdatas, bool Bundle3D::loadObj(MeshDatas& meshdatas,
MaterialDatas& materialdatas, MaterialDatas& materialdatas,
NodeDatas& nodedatas, NodeDatas& nodedatas,
std::string_view fullPath, const std::string& fullPath,
const char* mtl_basepath) const char* mtl_basepath)
{ {
meshdatas.resetData(); meshdatas.resetData();
@ -219,7 +219,7 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas,
std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials; std::vector<tinyobj::material_t> materials;
auto ret = tinyobj::LoadObj(shapes, materials, fullPath.data(), mtlPath.c_str()); auto ret = tinyobj::LoadObj(shapes, materials, fullPath.c_str(), mtlPath.c_str());
if (ret.empty()) if (ret.empty())
{ {
// fill data // fill data
@ -329,11 +329,11 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas,
return true; return true;
} }
CCLOG("warning: load %s file error: %s", fullPath.data(), ret.c_str()); CCLOG("warning: load %s file error: %s", fullPath.c_str(), ret.c_str());
return false; return false;
} }
bool Bundle3D::loadSkinData(std::string_view /*id*/, SkinData* skindata) bool Bundle3D::loadSkinData(const std::string& /*id*/, SkinData* skindata)
{ {
skindata->resetData(); skindata->resetData();
@ -347,7 +347,7 @@ bool Bundle3D::loadSkinData(std::string_view /*id*/, SkinData* skindata)
} }
} }
bool Bundle3D::loadAnimationData(std::string_view id, Animation3DData* animationdata) bool Bundle3D::loadAnimationData(const std::string& id, Animation3DData* animationdata)
{ {
animationdata->resetData(); animationdata->resetData();
@ -1062,7 +1062,7 @@ bool Bundle3D::loadMaterialsJson(MaterialDatas& materialdatas)
} }
return true; return true;
} }
bool Bundle3D::loadJson(std::string_view path) bool Bundle3D::loadJson(const std::string& path)
{ {
clear(); clear();
@ -1084,7 +1084,7 @@ bool Bundle3D::loadJson(std::string_view path)
return true; return true;
} }
bool Bundle3D::loadBinary(std::string_view path) bool Bundle3D::loadBinary(const std::string& path)
{ {
clear(); clear();
@ -1094,7 +1094,7 @@ bool Bundle3D::loadBinary(std::string_view path)
if (_binaryBuffer.isNull()) if (_binaryBuffer.isNull())
{ {
clear(); clear();
CCLOG("warning: Failed to read file: %s", path.data()); CCLOG("warning: Failed to read file: %s", path.c_str());
return false; return false;
} }
@ -1107,7 +1107,7 @@ bool Bundle3D::loadBinary(std::string_view path)
if (_binaryReader.read(sig, 1, 4) != 4 || memcmp(sig, identifier, 4) != 0) if (_binaryReader.read(sig, 1, 4) != 4 || memcmp(sig, identifier, 4) != 0)
{ {
clear(); clear();
CCLOG("warning: Invalid identifier: %s", path.data()); CCLOG("warning: Invalid identifier: %s", path.c_str());
return false; return false;
} }
@ -1127,7 +1127,7 @@ bool Bundle3D::loadBinary(std::string_view path)
if (_binaryReader.read(&_referenceCount, 4, 1) != 1) if (_binaryReader.read(&_referenceCount, 4, 1) != 1)
{ {
clear(); clear();
CCLOG("warning: Failed to read ref table size '%s'.", path.data()); CCLOG("warning: Failed to read ref table size '%s'.", path.c_str());
return false; return false;
} }
@ -1141,7 +1141,7 @@ bool Bundle3D::loadBinary(std::string_view path)
_binaryReader.read(&_references[i].offset, 4, 1) != 1) _binaryReader.read(&_references[i].offset, 4, 1) != 1)
{ {
clear(); clear();
CCLOG("warning: Failed to read ref number %u for bundle '%s'.", i, path.data()); CCLOG("warning: Failed to read ref number %u for bundle '%s'.", i, path.c_str());
CC_SAFE_DELETE_ARRAY(_references); CC_SAFE_DELETE_ARRAY(_references);
return false; return false;
} }
@ -1460,7 +1460,7 @@ bool loadMaterialDataJson_0_2(MaterialData* /*materialdata*/)
return true; return true;
} }
bool Bundle3D::loadAnimationDataJson(std::string_view id, Animation3DData* animationdata) bool Bundle3D::loadAnimationDataJson(const std::string& id, Animation3DData* animationdata)
{ {
std::string anim = ""; std::string anim = "";
if (_version == "1.2" || _version == "0.2") if (_version == "1.2" || _version == "0.2")
@ -1549,7 +1549,7 @@ bool Bundle3D::loadAnimationDataJson(std::string_view id, Animation3DData* anima
return true; return true;
} }
bool Bundle3D::loadAnimationDataBinary(std::string_view id, Animation3DData* animationdata) bool Bundle3D::loadAnimationDataBinary(const std::string& id, Animation3DData* animationdata)
{ {
if (_version == "0.1" || _version == "0.2" || _version == "0.3" || _version == "0.4") if (_version == "0.1" || _version == "0.2" || _version == "0.3" || _version == "0.4")
@ -1560,9 +1560,9 @@ bool Bundle3D::loadAnimationDataBinary(std::string_view id, Animation3DData* ani
else else
{ {
// if id is not a null string, we need to add a suffix of "animation" for seeding. // if id is not a null string, we need to add a suffix of "animation" for seeding.
std::string id_{id}; std::string id_ = id;
if (!id.empty()) if (id != "")
id_.append("animation"); id_ = id + "animation";
if (!seekToFirstType(BUNDLE_TYPE_ANIMATIONS, id_)) if (!seekToFirstType(BUNDLE_TYPE_ANIMATIONS, id_))
return false; return false;
@ -1998,7 +1998,7 @@ NodeData* Bundle3D::parseNodesRecursivelyBinary(bool& skeleton, bool singleSprit
return nodedata; return nodedata;
} }
backend::VertexFormat Bundle3D::parseGLDataType(std::string_view str, int size) backend::VertexFormat Bundle3D::parseGLDataType(const std::string& str, int size)
{ {
backend::VertexFormat ret = backend::VertexFormat::INT; backend::VertexFormat ret = backend::VertexFormat::INT;
if (str == "GL_BYTE") if (str == "GL_BYTE")
@ -2097,7 +2097,7 @@ backend::VertexFormat Bundle3D::parseGLDataType(std::string_view str, int size)
return ret; return ret;
} }
backend::SamplerAddressMode Bundle3D::parseSamplerAddressMode(std::string_view str) backend::SamplerAddressMode Bundle3D::parseSamplerAddressMode(const std::string& str)
{ {
if (str == "REPEAT") if (str == "REPEAT")
@ -2115,7 +2115,7 @@ backend::SamplerAddressMode Bundle3D::parseSamplerAddressMode(std::string_view s
} }
} }
NTextureData::Usage Bundle3D::parseGLTextureType(std::string_view str) NTextureData::Usage Bundle3D::parseGLTextureType(const std::string& str)
{ {
if (str == "AMBIENT") if (str == "AMBIENT")
{ {
@ -2163,7 +2163,7 @@ NTextureData::Usage Bundle3D::parseGLTextureType(std::string_view str)
return NTextureData::Usage::Unknown; return NTextureData::Usage::Unknown;
} }
} }
shaderinfos::VertexKey Bundle3D::parseGLProgramAttribute(std::string_view str) shaderinfos::VertexKey Bundle3D::parseGLProgramAttribute(const std::string& str)
{ {
if (str == "VERTEX_ATTRIB_POSITION") if (str == "VERTEX_ATTRIB_POSITION")
{ {
@ -2233,14 +2233,14 @@ shaderinfos::VertexKey Bundle3D::parseGLProgramAttribute(std::string_view str)
} }
} }
void Bundle3D::getModelRelativePath(std::string_view path) void Bundle3D::getModelRelativePath(const std::string& path)
{ {
ssize_t index = path.find_last_of('/'); ssize_t index = path.find_last_of('/');
std::string fullModelPath; std::string fullModelPath;
_modelPath = path.substr(0, index + 1); _modelPath = path.substr(0, index + 1);
} }
Reference* Bundle3D::seekToFirstType(unsigned int type, std::string_view id) Reference* Bundle3D::seekToFirstType(unsigned int type, const std::string& id)
{ {
// for each Reference // for each Reference
for (unsigned int i = 0; i < _referenceCount; ++i) for (unsigned int i = 0; i < _referenceCount; ++i)
@ -2266,7 +2266,7 @@ Reference* Bundle3D::seekToFirstType(unsigned int type, std::string_view id)
return nullptr; return nullptr;
} }
std::vector<Vec3> Bundle3D::getTrianglesList(std::string_view path) std::vector<Vec3> Bundle3D::getTrianglesList(const std::string& path)
{ {
std::vector<Vec3> trianglesList; std::vector<Vec3> trianglesList;

View File

@ -64,32 +64,32 @@ public:
* get define data type * get define data type
* @param str The type in string * @param str The type in string
*/ */
static backend::VertexFormat parseGLDataType(std::string_view str, int size); static backend::VertexFormat parseGLDataType(const std::string& str, int size);
/** /**
* get define data type * get define data type
* @param str The type in string * @param str The type in string
*/ */
static backend::SamplerAddressMode parseSamplerAddressMode(std::string_view str); static backend::SamplerAddressMode parseSamplerAddressMode(const std::string& str);
/** /**
* load a file. You must load a file first, then call loadMeshData, loadSkinData, and so on * load a file. You must load a file first, then call loadMeshData, loadSkinData, and so on
* @param path File to be loaded * @param path File to be loaded
* @return result of load * @return result of load
*/ */
virtual bool load(std::string_view path); virtual bool load(const std::string& path);
/** /**
* load skin data from bundle * load skin data from bundle
* @param id The ID of the skin, load the first Skin in the bundle if it is empty * @param id The ID of the skin, load the first Skin in the bundle if it is empty
*/ */
virtual bool loadSkinData(std::string_view id, SkinData* skindata); virtual bool loadSkinData(const std::string& id, SkinData* skindata);
/** /**
* load material data from bundle * load material data from bundle
* @param id The ID of the animation, load the first animation in the bundle if it is empty * @param id The ID of the animation, load the first animation in the bundle if it is empty
*/ */
virtual bool loadAnimationData(std::string_view id, Animation3DData* animationdata); virtual bool loadAnimationData(const std::string& id, Animation3DData* animationdata);
// since 3.3, to support reskin // since 3.3, to support reskin
virtual bool loadMeshDatas(MeshDatas& meshdatas); virtual bool loadMeshDatas(MeshDatas& meshdatas);
@ -102,21 +102,21 @@ public:
* load triangle list * load triangle list
* @param path the file path to load * @param path the file path to load
*/ */
static std::vector<Vec3> getTrianglesList(std::string_view path); static std::vector<Vec3> getTrianglesList(const std::string& path);
// load .obj file // load .obj file
static bool loadObj(MeshDatas& meshdatas, static bool loadObj(MeshDatas& meshdatas,
MaterialDatas& materialdatas, MaterialDatas& materialdatas,
NodeDatas& nodedatas, NodeDatas& nodedatas,
std::string_view fullPath, const std::string& fullPath,
const char* mtl_basepath = nullptr); const char* mtl_basepath = nullptr);
// calculate aabb // calculate aabb
static AABB calculateAABB(const std::vector<float>& vertex, int stride, const std::vector<unsigned short>& index); static AABB calculateAABB(const std::vector<float>& vertex, int stride, const std::vector<unsigned short>& index);
protected: protected:
bool loadJson(std::string_view path); bool loadJson(const std::string& path);
bool loadBinary(std::string_view path); bool loadBinary(const std::string& path);
bool loadMeshDatasJson(MeshDatas& meshdatas); bool loadMeshDatasJson(MeshDatas& meshdatas);
bool loadMeshDataJson_0_1(MeshDatas& meshdatas); bool loadMeshDataJson_0_1(MeshDatas& meshdatas);
bool loadMeshDataJson_0_2(MeshDatas& meshdatas); bool loadMeshDataJson_0_2(MeshDatas& meshdatas);
@ -137,8 +137,8 @@ protected:
bool loadMaterialDataJson(MaterialData* materialdata); bool loadMaterialDataJson(MaterialData* materialdata);
bool loadMaterialDataJson_0_1(MaterialData* materialdata); bool loadMaterialDataJson_0_1(MaterialData* materialdata);
bool loadMaterialDataJson_0_2(MaterialData* materialdata); bool loadMaterialDataJson_0_2(MaterialData* materialdata);
bool loadAnimationDataJson(std::string_view id, Animation3DData* animationdata); bool loadAnimationDataJson(const std::string& id, Animation3DData* animationdata);
bool loadAnimationDataBinary(std::string_view id, Animation3DData* animationdata); bool loadAnimationDataBinary(const std::string& id, Animation3DData* animationdata);
/** /**
* load nodes of json * load nodes of json
@ -156,26 +156,26 @@ protected:
* get define data type * get define data type
* @param str The type in string * @param str The type in string
*/ */
NTextureData::Usage parseGLTextureType(std::string_view str); NTextureData::Usage parseGLTextureType(const std::string& str);
/** /**
* get vertex attribute type * get vertex attribute type
* @param str The type in string * @param str The type in string
*/ */
shaderinfos::VertexKey parseGLProgramAttribute(std::string_view str); shaderinfos::VertexKey parseGLProgramAttribute(const std::string& str);
/* /*
* get model path * get model path
* @param str Full path of model file * @param str Full path of model file
*/ */
void getModelRelativePath(std::string_view path); void getModelRelativePath(const std::string& path);
/* /*
* set the read position in buffer to the target type * set the read position in buffer to the target type
* @param The data type * @param The data type
* @param The data id * @param The data id
*/ */
Reference* seekToFirstType(unsigned int type, std::string_view id = ""); Reference* seekToFirstType(unsigned int type, const std::string& id = "");
CC_CONSTRUCTOR_ACCESS : Bundle3D(); CC_CONSTRUCTOR_ACCESS : Bundle3D();
virtual ~Bundle3D(); virtual ~Bundle3D();

View File

@ -220,21 +220,21 @@ struct SkinData
rootBoneIndex = -1; rootBoneIndex = -1;
} }
void addSkinBoneNames(std::string_view name) void addSkinBoneNames(const std::string& name)
{ {
auto it = std::find(skinBoneNames.begin(), skinBoneNames.end(), name); auto it = std::find(skinBoneNames.begin(), skinBoneNames.end(), name);
if (it == skinBoneNames.end()) if (it == skinBoneNames.end())
skinBoneNames.push_back(std::string{name}); skinBoneNames.push_back(name);
} }
void addNodeBoneNames(std::string_view name) void addNodeBoneNames(const std::string& name)
{ {
auto it = std::find(nodeBoneNames.begin(), nodeBoneNames.end(), name); auto it = std::find(nodeBoneNames.begin(), nodeBoneNames.end(), name);
if (it == nodeBoneNames.end()) if (it == nodeBoneNames.end())
nodeBoneNames.push_back(std::string{name}); nodeBoneNames.push_back(name);
} }
int getSkinBoneNameIndex(std::string_view name) const int getSkinBoneNameIndex(const std::string& name) const
{ {
int i = 0; int i = 0;
for (const auto& iter : skinBoneNames) for (const auto& iter : skinBoneNames)
@ -246,7 +246,7 @@ struct SkinData
return -1; return -1;
} }
int getBoneNameIndex(std::string_view name) const int getBoneNameIndex(const std::string& name) const
{ {
int i = 0; int i = 0;
for (const auto& iter : skinBoneNames) for (const auto& iter : skinBoneNames)
@ -323,7 +323,7 @@ struct MaterialDatas
{ {
std::vector<NMaterialData> materials; std::vector<NMaterialData> materials;
void resetData() { materials.clear(); } void resetData() { materials.clear(); }
const NMaterialData* getMaterialData(std::string_view materialid) const const NMaterialData* getMaterialData(const std::string& materialid) const
{ {
for (const auto& it : materials) for (const auto& it : materials)
{ {

View File

@ -228,7 +228,7 @@ Mesh* Mesh::create(const std::vector<float>& vertices,
return create("", indexData); return create("", indexData);
} }
Mesh* Mesh::create(std::string_view name, MeshIndexData* indexData, MeshSkin* skin) Mesh* Mesh::create(const std::string& name, MeshIndexData* indexData, MeshSkin* skin)
{ {
auto state = new Mesh(); auto state = new Mesh();
state->autorelease(); state->autorelease();
@ -255,7 +255,7 @@ bool Mesh::isVisible() const
return _visible; return _visible;
} }
void Mesh::setTexture(std::string_view texPath) void Mesh::setTexture(const std::string& texPath)
{ {
_texFile = texPath; _texFile = texPath;
auto tex = Director::getInstance()->getTextureCache()->addImage(texPath); auto tex = Director::getInstance()->getTextureCache()->addImage(texPath);
@ -307,7 +307,7 @@ void Mesh::setTexture(Texture2D* tex, NTextureData::Usage usage, bool cacheFileN
} }
} }
void Mesh::setTexture(std::string_view texPath, NTextureData::Usage usage) void Mesh::setTexture(const std::string& texPath, NTextureData::Usage usage)
{ {
auto tex = Director::getInstance()->getTextureCache()->addImage(texPath); auto tex = Director::getInstance()->getTextureCache()->addImage(texPath);
setTexture(tex, usage); setTexture(tex, usage);
@ -350,7 +350,7 @@ void Mesh::setMaterial(Material* material)
if (_material->getTechnique()->getName().compare(technique->getName()) == 0) if (_material->getTechnique()->getName().compare(technique->getName()) == 0)
{ {
auto program = pass->getProgramState()->getProgram(); auto program = pass->getProgramState()->getProgram();
auto attributes = program->getActiveAttributes(); auto& attributes = program->getActiveAttributes();
auto meshVertexData = _meshIndexData->getMeshVertexData(); auto meshVertexData = _meshIndexData->getMeshVertexData();
auto attributeCount = meshVertexData->getMeshVertexAttribCount(); auto attributeCount = meshVertexData->getMeshVertexAttribCount();
CCASSERT(attributes.size() <= attributeCount, "missing attribute data"); CCASSERT(attributes.size() <= attributeCount, "missing attribute data");

View File

@ -83,7 +83,7 @@ public:
* create mesh * create mesh
* @lua NA * @lua NA
*/ */
static Mesh* create(std::string_view name, MeshIndexData* indexData, MeshSkin* skin = nullptr); static Mesh* create(const std::string& name, MeshIndexData* indexData, MeshSkin* skin = nullptr);
/** /**
* get vertex buffer * get vertex buffer
@ -109,7 +109,7 @@ public:
* call setTexture(texPath, NTextureData::Usage::Diffuse) * call setTexture(texPath, NTextureData::Usage::Diffuse)
* @param texPath texture path * @param texPath texture path
*/ */
void setTexture(std::string_view texPath); void setTexture(const std::string& texPath);
/** /**
* set texture (diffuse), which is responsible for the main appearance. It is also means main texture, you can also * set texture (diffuse), which is responsible for the main appearance. It is also means main texture, you can also
* call setTexture(texPath, NTextureData::Usage::Diffuse) * call setTexture(texPath, NTextureData::Usage::Diffuse)
@ -128,7 +128,7 @@ public:
* @param texPath texture path * @param texPath texture path
* @param usage Usage of this texture * @param usage Usage of this texture
*/ */
void setTexture(std::string_view texPath, NTextureData::Usage usage); void setTexture(const std::string& texPath, NTextureData::Usage usage);
/** /**
* Get texture (diffuse), which is responsible for the main appearance. It is also means main texture, you can also * Get texture (diffuse), which is responsible for the main appearance. It is also means main texture, you can also
* call getTexture(NTextureData::Usage::Diffuse) * call getTexture(NTextureData::Usage::Diffuse)
@ -168,7 +168,7 @@ public:
backend::ProgramState* getProgramState() const; backend::ProgramState* getProgramState() const;
/**name getter */ /**name getter */
std::string_view getName() const { return _name; } const std::string& getName() const { return _name; }
void setBlendFunc(const BlendFunc& blendFunc); void setBlendFunc(const BlendFunc& blendFunc);
const BlendFunc& getBlendFunc() const; const BlendFunc& getBlendFunc() const;
@ -225,7 +225,7 @@ public:
/**Mesh index data setter*/ /**Mesh index data setter*/
void setMeshIndexData(MeshIndexData* indexdata); void setMeshIndexData(MeshIndexData* indexdata);
/**name setter*/ /**name setter*/
void setName(std::string_view name) { _name = name; } void setName(const std::string& name) { _name = name; }
/** /**
* calculate the AABB of the mesh * calculate the AABB of the mesh

View File

@ -75,7 +75,7 @@ Bone3D* MeshSkin::getBoneByIndex(unsigned int index) const
return nullptr; return nullptr;
} }
Bone3D* MeshSkin::getBoneByName(std::string_view id) const Bone3D* MeshSkin::getBoneByName(const std::string& id) const
{ {
// search from skin bones // search from skin bones
for (const auto& it : _skinBones) for (const auto& it : _skinBones)

View File

@ -54,7 +54,7 @@ class CC_DLL MeshSkin : public Ref
public: public:
/**create a new meshskin if do not want to share meshskin*/ /**create a new meshskin if do not want to share meshskin*/
static MeshSkin* create(Skeleton3D* skeleton, std::string_view filename, std::string_view name); static MeshSkin* create(Skeleton3D* skeleton, const std::string& filename, const std::string& name);
static MeshSkin* create(Skeleton3D* skeleton, static MeshSkin* create(Skeleton3D* skeleton,
const std::vector<std::string>& boneNames, const std::vector<std::string>& boneNames,
@ -65,7 +65,7 @@ public:
/**get bone*/ /**get bone*/
Bone3D* getBoneByIndex(unsigned int index) const; Bone3D* getBoneByIndex(unsigned int index) const;
Bone3D* getBoneByName(std::string_view id) const; Bone3D* getBoneByName(const std::string& id) const;
/**get bone index*/ /**get bone index*/
int getBoneIndex(Bone3D* bone) const; int getBoneIndex(Bone3D* bone) const;

View File

@ -49,7 +49,7 @@ using namespace std;
NS_CC_BEGIN NS_CC_BEGIN
///////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////
MeshIndexData* MeshIndexData::create(std::string_view id, MeshIndexData* MeshIndexData::create(const std::string& id,
MeshVertexData* vertexData, MeshVertexData* vertexData,
backend::Buffer* indexbuffer, backend::Buffer* indexbuffer,
const AABB& aabb) const AABB& aabb)
@ -160,7 +160,7 @@ MeshVertexData* MeshVertexData::create(const MeshData& meshdata)
return vertexdata; return vertexdata;
} }
MeshIndexData* MeshVertexData::getMeshIndexDataById(std::string_view id) const MeshIndexData* MeshVertexData::getMeshIndexDataById(const std::string& id) const
{ {
for (auto it : _indexs) for (auto it : _indexs)
{ {

View File

@ -55,7 +55,7 @@ class CC_DLL MeshIndexData : public Ref
{ {
public: public:
/** create */ /** create */
static MeshIndexData* create(std::string_view id, static MeshIndexData* create(const std::string& id,
MeshVertexData* vertexData, MeshVertexData* vertexData,
backend::Buffer* indexbuffer, backend::Buffer* indexbuffer,
const AABB& aabb); const AABB& aabb);
@ -74,8 +74,8 @@ public:
const AABB& getAABB() const { return _aabb; } const AABB& getAABB() const { return _aabb; }
/** id setter and getter */ /** id setter and getter */
void setId(std::string_view id) { _id = id; } void setId(const std::string& id) { _id = id; }
std::string_view getId() const { return _id; } const std::string& getId() const { return _id; }
/**primitive type setter & getter*/ /**primitive type setter & getter*/
MeshCommand::PrimitiveType getPrimitiveType() const { return _primitiveType; } MeshCommand::PrimitiveType getPrimitiveType() const { return _primitiveType; }
@ -128,7 +128,7 @@ public:
/** get index data by index */ /** get index data by index */
MeshIndexData* getMeshIndexDataByIndex(int index) const { return _indexs.at(index); } MeshIndexData* getMeshIndexDataByIndex(int index) const { return _indexs.at(index); }
/** get index data by id */ /** get index data by id */
MeshIndexData* getMeshIndexDataById(std::string_view id) const; MeshIndexData* getMeshIndexDataById(const std::string& id) const;
ssize_t getSizePerVertex() const { return _sizePerVertex; } ssize_t getSizePerVertex() const { return _sizePerVertex; }

View File

@ -61,7 +61,7 @@ MotionStreak3D* MotionStreak3D::create(float fade,
float minSeg, float minSeg,
float stroke, float stroke,
const Color3B& color, const Color3B& color,
std::string_view path) const std::string& path)
{ {
MotionStreak3D* ret = new MotionStreak3D(); MotionStreak3D* ret = new MotionStreak3D();
if (ret && ret->initWithFade(fade, minSeg, stroke, color, path)) if (ret && ret->initWithFade(fade, minSeg, stroke, color, path))
@ -87,7 +87,7 @@ MotionStreak3D* MotionStreak3D::create(float fade, float minSeg, float stroke, c
return nullptr; return nullptr;
} }
bool MotionStreak3D::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path) bool MotionStreak3D::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path)
{ {
CCASSERT(!path.empty(), "Invalid filename"); CCASSERT(!path.empty(), "Invalid filename");

View File

@ -57,7 +57,11 @@ public:
* @param path The texture file name of stoke. * @param path The texture file name of stoke.
* @return An autoreleased MotionStreak3D object. * @return An autoreleased MotionStreak3D object.
*/ */
static MotionStreak3D* create(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path); static MotionStreak3D* create(float fade,
float minSeg,
float stroke,
const Color3B& color,
const std::string& path);
/** Creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture. /** Creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture.
* *
* @param fade The fade time, in seconds. * @param fade The fade time, in seconds.
@ -160,7 +164,7 @@ public:
/** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename
*/ */
bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path); bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path);
/** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */ /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */
bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture); bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture);

Some files were not shown because too many files have changed in this diff Show More