Merge branch 'vfs-support' of https://github.com/rh101/engine-x into vfs-support

This commit is contained in:
rh101 2021-04-23 00:01:47 +10:00
commit cd0c5bfcee
317 changed files with 10318 additions and 7084 deletions

View File

@ -26,7 +26,7 @@
# build engine library and all tests # build engine library and all tests
cmake_minimum_required(VERSION 3.6) cmake_minimum_required(VERSION 3.10)
project(engine-x) project(engine-x)

View File

@ -6,7 +6,8 @@ Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Copyright (c) 2017-2018 Xiamen Yaji Software
Copyright (c) 2019-2020 HALX99 Copyright (c) 2019-2020 HALX99
Copyright (c) 2020 c4games.com Copyright (c) 2020 C4games Ltd.
Copyright (c) 2021 Bytedance Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -42,7 +42,7 @@
### [Roadmap](issues/1) ### [Roadmap](issues/1)
### Quick Start ### Quick Start
Open [Wiki](https://github.com/c4games/engine-x/wiki) for additional information too. Open [Wiki](https://github.com/c4games/engine-x-wiki) for additional information too.
#### Common Requirement [Python](https://www.python.org/downloads/) #### Common Requirement [Python](https://www.python.org/downloads/)
* Python-2.7.17+, Python-3.7+ * Python-2.7.17+, Python-3.7+
@ -77,16 +77,13 @@ Open [Wiki](https://github.com/c4games/engine-x/wiki) for additional information
2. Execute follow command 2. Execute follow command
```sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer``` ```sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer```
3. Generate xcode project 3. Generate xcode project
```sh - for any device
# for any device ```cmake -S . -B build -GXcode -DCMAKE_TOOLCHAIN_FILE=cmake/ios.mini.cmake```
cmake -S . -B build -GXcode -DCMAKE_TOOLCHAIN_FILE=cmake/ios.mini.cmake - for arm64:
```cmake -S . -B build -GXcode -DCMAKE_TOOLCHAIN_FILE=cmake/ios.mini.cmake -DCMAKE_OSX_ARCHITECTURES=arm64```
- for simulator x86_64:
```cmake -S . -B build -GXcode -DCMAKE_TOOLCHAIN_FILE=cmake/ios.mini.cmake -DCMAKE_OSX_SYSROOT=iphonesimulator -DCMAKE_OSX_ARCHITECTURES=x86_64```
# for device combined armv7,arm64
# cmake -S . -B build -GXcode -DCMAKE_TOOLCHAIN_FILE=cmake/ios.mini.cmake "-DCMAKE_OSX_ARCHITECTURES=armv7;arm64"
# for simulator x86_64
# cmake -S . -B build -GXcode -DCMAKE_TOOLCHAIN_FILE=cmake/ios.mini.cmake -DCMAKE_OSX_SYSROOT=iphonesimulator -DCMAKE_OSX_ARCHITECTURES=x86_64
```
4. After cmake generate finish, you can open xcode project at ```build``` folder and run cpp-tests or other test targets. 4. After cmake generate finish, you can open xcode project at ```build``` folder and run cpp-tests or other test targets.
5. Notes 5. Notes
- **The code sign required to run ios app on device, just change bundle identifier until the auto manage signing solved** - **The code sign required to run ios app on device, just change bundle identifier until the auto manage signing solved**

View File

@ -54,7 +54,7 @@
#### Windows #### Windows
1. 安装CMake要求3.14以上 1. 安装CMake要求3.14以上
2. 确保Visual Studio 2019以正确安装 2. 确保 Visual Studio 2019 已正确安装
3. 执行下面的命令 3. 执行下面的命令
```bat ```bat
cd engine-x cd engine-x
@ -79,17 +79,14 @@
1. 确保已安装xcode11+和[cmake3.14+](https://github.com/Kitware/CMake/releases), 安装CMake命令行支持: ```sudo "/Applications/CMake.app/Contents/bin/cmake-gui" --install``` 1. 确保已安装xcode11+和[cmake3.14+](https://github.com/Kitware/CMake/releases), 安装CMake命令行支持: ```sudo "/Applications/CMake.app/Contents/bin/cmake-gui" --install```
2. 执行如下命令确保cmake能成功生成xcode工程: 2. 执行如下命令确保cmake能成功生成xcode工程:
```sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer``` ```sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer```
3. 生成xcode工程, 进入engine-x根目录执行如下命令: 3. 生成xcode工程, 进入engine-x根目录执行如下命令之一:
```sh - for any device:
# for device arm64 ```cmake -S . -B build -GXcode -DCMAKE_TOOLCHAIN_FILE=cmake/ios.mini.cmake```
cmake -S . -B build -GXcode -DCMAKE_TOOLCHAIN_FILE=cmake/ios.mini.cmake - for arm64:
```cmake -S . -B build -GXcode -DCMAKE_TOOLCHAIN_FILE=cmake/ios.mini.cmake -DCMAKE_OSX_ARCHITECTURES=arm64```
- for simulator x86_64:
```cmake -S . -B build -GXcode -DCMAKE_TOOLCHAIN_FILE=cmake/ios.mini.cmake -DCMAKE_OSX_SYSROOT=iphonesimulator -DCMAKE_OSX_ARCHITECTURES=x86_64```
# for device combined armv7,arm64
# cmake -S . -B build -GXcode -DCMAKE_TOOLCHAIN_FILE=cmake/ios.mini.cmake "-DCMAKE_OSX_ARCHITECTURES=armv7;arm64"
# for simulator x86_64
# cmake -S . -B build -GXcode -DCMAKE_TOOLCHAIN_FILE=cmake/ios.mini.cmake -DCMAKE_OSX_SYSROOT=iphonesimulator -DCMAKE_OSX_ARCHITECTURES=x86_64
```
4. 之后就可以用xcode打开, 选择cpp-tests编译运行 4. 之后就可以用xcode打开, 选择cpp-tests编译运行
### 注意 ### 注意

View File

@ -103,9 +103,13 @@ function(use_cocos2dx_compile_define target)
if(APPLE) if(APPLE)
target_compile_definitions(${target} PUBLIC __APPLE__) target_compile_definitions(${target} PUBLIC __APPLE__)
target_compile_definitions(${target} PUBLIC USE_FILE32API) target_compile_definitions(${target} PUBLIC USE_FILE32API)
if(IOS AND CC_FORCE_USE_GLES) if(CC_COMPAT_GL)
target_compile_definitions(${target} PUBLIC CC_FORCE_USE_GLES=1) target_compile_definitions(${target}
PUBLIC CC_COMPAT_GL=1
PUBLIC GL_SILENCE_DEPRECATION=1
)
endif() endif()
elseif(LINUX) elseif(LINUX)
target_compile_definitions(${target} PUBLIC LINUX) target_compile_definitions(${target} PUBLIC LINUX)
target_compile_definitions(${target} PUBLIC _GNU_SOURCE) target_compile_definitions(${target} PUBLIC _GNU_SOURCE)
@ -113,8 +117,8 @@ function(use_cocos2dx_compile_define target)
target_compile_definitions(${target} PUBLIC ANDROID) target_compile_definitions(${target} PUBLIC ANDROID)
target_compile_definitions(${target} PUBLIC USE_FILE32API) target_compile_definitions(${target} PUBLIC USE_FILE32API)
elseif(WINDOWS) elseif(WINDOWS)
if(CC_FORCE_USE_GLES) if(CC_COMPAT_GL)
target_compile_definitions(${target} PUBLIC CC_FORCE_USE_GLES=1) target_compile_definitions(${target} PUBLIC CC_COMPAT_GL=1)
endif() endif()
target_compile_definitions(${target} target_compile_definitions(${target}
PUBLIC WIN32 PUBLIC WIN32

View File

@ -81,6 +81,8 @@ macro(cocos2dx_depend)
find_library(CORE_GRAPHICS_LIBRARY CoreGraphics) find_library(CORE_GRAPHICS_LIBRARY CoreGraphics)
find_library(AV_FOUNDATION_LIBRARY AVFoundation) find_library(AV_FOUNDATION_LIBRARY AVFoundation)
find_library(WEBKIT_LIBRARY WebKit) find_library(WEBKIT_LIBRARY WebKit)
find_library(ZLIB z)
find_library(ICONVLIB iconv)
list(APPEND PLATFORM_SPECIFIC_LIBS list(APPEND PLATFORM_SPECIFIC_LIBS
${UIKIT_LIBRARY} ${UIKIT_LIBRARY}
${OPENGLES_LIBRARY} ${OPENGLES_LIBRARY}
@ -93,8 +95,8 @@ macro(cocos2dx_depend)
${AV_FOUNDATION_LIBRARY} ${AV_FOUNDATION_LIBRARY}
${WEBKIT_LIBRARY} ${WEBKIT_LIBRARY}
${COCOS_APPLE_LIBS} ${COCOS_APPLE_LIBS}
"/usr/lib/libz.dylib" ${ZLIB}
"/usr/lib/libiconv.dylib" ${ICONVLIB}
) )
endif() endif()
endif() endif()

View File

@ -8,9 +8,9 @@ CMake is an open-source, cross-platform family of tools designed to build, test
```sh ```sh
cmake --version cmake --version
``` ```
if the CMake version is lower than 3.6, please upgrade. if the CMake version is lower than 3.14, please upgrade.
2. You should use __out-of-source__ builds, this means you need to create a different directory than __cocos-re__ to execute the `cmake` command. 2. You should use **out-of-source** builds, this means you need to create a different directory than **engine-x** to execute the `cmake` command.
## Step by Step ## Step by Step
@ -29,33 +29,29 @@ Execute `make help` to see all build targets, `make <target>` build specified ta
```sh ```sh
cd engine-x cd engine-x
mkdir win32-build && cd win32-build mkdir win32-build
cmake .. -G"Visual Studio 16 2019" cmake -B win32-build -G"Visual Studio 16 2019"
# build
cmake --build win32-build --config Debug
``` ```
or open **engine-x.sln** in Explorer to use the generated project.
Execute `cmake --build .` to compile,
```
cmake --build . --config Debug
cmake --build . --config Release
```
or open __cocos-re.sln__ in Explorer to use the generated project.
### Generate macOS Project ### Generate macOS Project
```sh ```sh
cd engine-x cd engine-x
mkdir mac-build && cd mac-build mkdir mac-build
cmake .. -GXcode cmake -B mac-build -GXcode
open engine-x.xcodeproj open mac-build/engine-x.xcodeproj
``` ```
### Generate iOS Project ### Generate iOS Project
```sh ```sh
cd engine-x cd engine-x
mkdir ios-build && cd ios-build mkdir ios-build
cmake .. -GXcode -DCMAKE_TOOLCHAIN_FILE=cmake/ios.mini.cmake cmake -B ios-build -GXcode -DCMAKE_TOOLCHAIN_FILE=cmake/ios.mini.cmake
open engine-x.xcodeproj open ios-build/engine-x.xcodeproj
``` ```
#### How do I customize the generated Xcode project? #### How do I customize the generated Xcode project?

View File

@ -77,13 +77,13 @@ if __name__ == "__main__":
parser.add_argument("-m", dest="mode", default=None) parser.add_argument("-m", dest="mode", default=None)
(args, unkonw) = parser.parse_known_args(sys.argv) (args, unkonw) = parser.parse_known_args(sys.argv)
need_compile = True need_compile = False
# if args.luajit: # if args.luajit:
# print(" luajit mode '%s'" % (args.mode)) # print(" luajit mode '%s'" % (args.mode))
if args.mode == "Debug" and args.luajit: # if args.mode == "Debug" and args.luajit:
need_compile = False # need_compile = False
print(" -Skip luacompile in debug mode!") # print(" -Skip luacompile in debug mode!")
create_files = 0 create_files = 0

View File

@ -62,7 +62,7 @@ AtlasNode * AtlasNode::create(const std::string& tile, int tileWidth, int tileHe
bool AtlasNode::initWithTileFile(const std::string& 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::getInstance()->getTextureCache()->addImage(tile); Texture2D *texture = _director->getTextureCache()->addImage(tile);
return initWithTexture(texture, tileWidth, tileHeight, itemsToRender); return initWithTexture(texture, tileWidth, tileHeight, itemsToRender);
} }
@ -162,7 +162,7 @@ void AtlasNode::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
auto programState = _quadCommand.getPipelineDescriptor().programState; auto programState = _quadCommand.getPipelineDescriptor().programState;
const auto& projectionMat = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); const auto& projectionMat = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
programState->setUniform(_mvpMatrixLocation, projectionMat.m, sizeof(projectionMat.m)); programState->setUniform(_mvpMatrixLocation, projectionMat.m, sizeof(projectionMat.m));
_quadCommand.init(_globalZOrder, _textureAtlas->getTexture(), _blendFunc, _textureAtlas->getQuads(), _quadsToDraw, transform, flags); _quadCommand.init(_globalZOrder, _textureAtlas->getTexture(), _blendFunc, _textureAtlas->getQuads(), _quadsToDraw, transform, flags);

View File

@ -187,9 +187,9 @@ void Camera::setAdditionalProjection(const Mat4& mat)
bool Camera::initDefault() bool Camera::initDefault()
{ {
auto size = Director::getInstance()->getWinSize(); auto size = _director->getWinSize();
//create default camera //create default camera
auto projection = Director::getInstance()->getProjection(); auto projection = _director->getProjection();
switch (projection) switch (projection)
{ {
case Director::Projection::_2D: case Director::Projection::_2D:
@ -201,7 +201,7 @@ bool Camera::initDefault()
} }
case Director::Projection::_3D: case Director::Projection::_3D:
{ {
float zeye = Director::getInstance()->getZEye(); float zeye = _director->getZEye();
initPerspective(60, (float)size.width / size.height, 10, zeye + size.height / 2.0f); initPerspective(60, (float)size.width / size.height, 10, zeye + size.height / 2.0f);
Vec3 eye(size.width/2, size.height/2.0f, zeye), center(size.width/2, size.height/2, 0.0f), up(0.0f, 1.0f, 0.0f); Vec3 eye(size.width/2, size.height/2.0f, zeye), center(size.width/2, size.height/2, 0.0f), up(0.0f, 1.0f, 0.0f);
setPosition3D(eye); setPosition3D(eye);
@ -247,7 +247,7 @@ Vec2 Camera::project(const Vec3& src) const
{ {
Vec2 screenPos; Vec2 screenPos;
auto viewport = Director::getInstance()->getWinSize(); auto viewport = _director->getWinSize();
Vec4 clipPos; Vec4 clipPos;
getViewProjectionMatrix().transformVector(Vec4(src.x, src.y, src.z, 1.0f), &clipPos); getViewProjectionMatrix().transformVector(Vec4(src.x, src.y, src.z, 1.0f), &clipPos);
@ -264,7 +264,7 @@ Vec2 Camera::projectGL(const Vec3& src) const
{ {
Vec2 screenPos; Vec2 screenPos;
auto viewport = Director::getInstance()->getWinSize(); auto viewport = _director->getWinSize();
Vec4 clipPos; Vec4 clipPos;
getViewProjectionMatrix().transformVector(Vec4(src.x, src.y, src.z, 1.0f), &clipPos); getViewProjectionMatrix().transformVector(Vec4(src.x, src.y, src.z, 1.0f), &clipPos);
@ -280,14 +280,14 @@ Vec2 Camera::projectGL(const Vec3& src) const
Vec3 Camera::unproject(const Vec3& src) const Vec3 Camera::unproject(const Vec3& src) const
{ {
Vec3 dst; Vec3 dst;
unproject(Director::getInstance()->getWinSize(), &src, &dst); unproject(_director->getWinSize(), &src, &dst);
return dst; return dst;
} }
Vec3 Camera::unprojectGL(const Vec3& src) const Vec3 Camera::unprojectGL(const Vec3& src) const
{ {
Vec3 dst; Vec3 dst;
unprojectGL(Director::getInstance()->getWinSize(), &src, &dst); unprojectGL(_director->getWinSize(), &src, &dst);
return dst; return dst;
} }
@ -427,7 +427,7 @@ void Camera::apply()
void Camera::applyViewport() void Camera::applyViewport()
{ {
Director::getInstance()->getRenderer()->setViewPort(_defaultViewport.x, _defaultViewport.y, _defaultViewport.w, _defaultViewport.h); _director->getRenderer()->setViewPort(_defaultViewport.x, _defaultViewport.y, _defaultViewport.w, _defaultViewport.h);
} }
int Camera::getRenderOrder() const int Camera::getRenderOrder() const

View File

@ -146,10 +146,9 @@ void ClippingNode::visit(Renderer *renderer, const Mat4 &parentTransform, uint32
// IMPORTANT: // IMPORTANT:
// To ease the migration to v3.0, we still support the Mat4 stack, // To ease the migration to v3.0, we still support the Mat4 stack,
// but it is deprecated and your code should not rely on it // but it is deprecated and your code should not rely on it
Director* director = Director::getInstance(); CCASSERT(nullptr != _director, "Director is null when setting matrix stack");
CCASSERT(nullptr != director, "Director is null when setting matrix stack"); _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
//Add group command //Add group command
@ -225,7 +224,7 @@ void ClippingNode::visit(Renderer *renderer, const Mat4 &parentTransform, uint32
renderer->popGroup(); renderer->popGroup();
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); _director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
} }
void ClippingNode::setCameraMask(unsigned short mask, bool applyChildren) void ClippingNode::setCameraMask(unsigned short mask, bool applyChildren)

View File

@ -62,7 +62,7 @@ void ClippingRectangleNode::onBeforeVisitScissor()
{ {
if (_clippingEnabled) if (_clippingEnabled)
{ {
auto renderer = Director::getInstance()->getRenderer(); auto renderer = _director->getRenderer();
_oldScissorTest = renderer->getScissorTest(); _oldScissorTest = renderer->getScissorTest();
renderer->setScissorTest(true); renderer->setScissorTest(true);
@ -76,7 +76,7 @@ void ClippingRectangleNode::onBeforeVisitScissor()
} }
const Point pos = convertToWorldSpace(Point(_clippingRegion.origin.x, _clippingRegion.origin.y)); const Point pos = convertToWorldSpace(Point(_clippingRegion.origin.x, _clippingRegion.origin.y));
GLView* glView = Director::getInstance()->getOpenGLView(); GLView* glView = _director->getOpenGLView();
glView->setScissorInPoints(pos.x, glView->setScissorInPoints(pos.x,
pos.y, pos.y,
_clippingRegion.size.width * scaleX, _clippingRegion.size.width * scaleX,
@ -87,7 +87,7 @@ void ClippingRectangleNode::onBeforeVisitScissor()
void ClippingRectangleNode::onAfterVisitScissor() void ClippingRectangleNode::onAfterVisitScissor()
{ {
if (_clippingEnabled) if (_clippingEnabled)
Director::getInstance()->getRenderer()->setScissorTest(_oldScissorTest); _director->getRenderer()->setScissorTest(_oldScissorTest);
} }
void ClippingRectangleNode::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) void ClippingRectangleNode::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags)

View File

@ -74,7 +74,7 @@ bool FastTMXLayer::initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo
if( tilesetInfo ) if( tilesetInfo )
{ {
_texture = Director::getInstance()->getTextureCache()->addImage(tilesetInfo->_sourceImage); _texture = _director->getTextureCache()->addImage(tilesetInfo->_sourceImage);
_texture->retain(); _texture->retain();
} }
@ -135,7 +135,7 @@ void FastTMXLayer::draw(Renderer *renderer, const Mat4& transform, uint32_t flag
if( flags != 0 || _dirty || _quadsDirty) if( flags != 0 || _dirty || _quadsDirty)
{ {
Size s = Director::getInstance()->getVisibleSize(); Size s = _director->getVisibleSize();
const Vec2 &anchor = getAnchorPoint(); const Vec2 &anchor = getAnchorPoint();
auto rect = Rect(Camera::getVisitingCamera()->getPositionX() - s.width * (anchor.x == 0.0f ? 0.5f : anchor.x), auto rect = Rect(Camera::getVisitingCamera()->getPositionX() - s.width * (anchor.x == 0.0f ? 0.5f : anchor.x),
Camera::getVisitingCamera()->getPositionY() - s.height * (anchor.y == 0.0f ? 0.5f : anchor.y), Camera::getVisitingCamera()->getPositionY() - s.height * (anchor.y == 0.0f ? 0.5f : anchor.y),
@ -153,7 +153,7 @@ void FastTMXLayer::draw(Renderer *renderer, const Mat4& transform, uint32_t flag
_dirty = false; _dirty = false;
} }
const auto& projectionMat = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); const auto& projectionMat = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
Mat4 finalMat = projectionMat * _modelViewTransform; Mat4 finalMat = projectionMat * _modelViewTransform;
for (const auto& e : _customCommands) for (const auto& e : _customCommands)
{ {
@ -168,7 +168,7 @@ void FastTMXLayer::draw(Renderer *renderer, const Mat4& transform, uint32_t flag
void FastTMXLayer::updateTiles(const Rect& culledRect) void FastTMXLayer::updateTiles(const Rect& culledRect)
{ {
Rect visibleTiles = Rect(culledRect.origin, culledRect.size * Director::getInstance()->getContentScaleFactor()); Rect visibleTiles = Rect(culledRect.origin, culledRect.size * _director->getContentScaleFactor());
Size mapTileSize = CC_SIZE_PIXELS_TO_POINTS(_mapTileSize); Size mapTileSize = CC_SIZE_PIXELS_TO_POINTS(_mapTileSize);
Size tileSize = CC_SIZE_PIXELS_TO_POINTS(_tileSet->_tileSize); Size tileSize = CC_SIZE_PIXELS_TO_POINTS(_tileSet->_tileSize);
Mat4 nodeToTileTransform = _tileToNodeTransform.getInversed(); Mat4 nodeToTileTransform = _tileToNodeTransform.getInversed();
@ -300,7 +300,7 @@ void FastTMXLayer::setupTiles()
// Parse cocos2d properties // Parse cocos2d properties
this->parseInternalProperties(); this->parseInternalProperties();
Size screenSize = Director::getInstance()->getWinSize(); auto& screenSize = _director->getWinSize();
switch (_layerOrientation) switch (_layerOrientation)
{ {

View File

@ -1736,7 +1736,7 @@ void Label::updateEffectUniforms(BatchCommand &batch, TextureAtlas* textureAtlas
{ {
updateBuffer(textureAtlas, batch.textCommand); updateBuffer(textureAtlas, batch.textCommand);
auto & matrixProjection = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); auto & matrixProjection = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
if (_shadowEnabled) { if (_shadowEnabled) {
updateBuffer(textureAtlas, batch.shadowCommand); updateBuffer(textureAtlas, batch.shadowCommand);
@ -1859,7 +1859,7 @@ void Label::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
if (_insideBounds) if (_insideBounds)
#endif #endif
{ {
cocos2d::Mat4 matrixProjection = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); cocos2d::Mat4 matrixProjection = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
if (!_shadowEnabled && (_currentLabelType == LabelType::BMFONT || _currentLabelType == LabelType::CHARMAP)) if (!_shadowEnabled && (_currentLabelType == LabelType::BMFONT || _currentLabelType == LabelType::CHARMAP))
{ {
updateBlendState(); updateBlendState();

View File

@ -56,7 +56,7 @@ LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& cha
bool LabelAtlas::initWithString(const std::string& string, const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) bool LabelAtlas::initWithString(const std::string& string, const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{ {
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(charMapFile); Texture2D *texture = _director->getTextureCache()->addImage(charMapFile);
return initWithString(string, texture, itemWidth, itemHeight, startCharMap); return initWithString(string, texture, itemWidth, itemHeight, startCharMap);
} }

View File

@ -73,8 +73,7 @@ Layer::~Layer()
bool Layer::init() bool Layer::init()
{ {
Director * director = Director::getInstance(); setContentSize(_director->getWinSize());
setContentSize(director->getWinSize());
return true; return true;
} }
@ -332,7 +331,7 @@ LayerColor * LayerColor::create(const Color4B& color)
bool LayerColor::init() bool LayerColor::init()
{ {
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
return initWithColor(Color4B(0,0,0,0), s.width, s.height); return initWithColor(Color4B(0,0,0,0), s.width, s.height);
} }
@ -365,7 +364,7 @@ bool LayerColor::initWithColor(const Color4B& color, float w, float h)
bool LayerColor::initWithColor(const Color4B& color) bool LayerColor::initWithColor(const Color4B& color)
{ {
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
return initWithColor(color, s.width, s.height); return initWithColor(color, s.width, s.height);
} }
@ -411,7 +410,7 @@ void LayerColor::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
_customCommand.init(_globalZOrder, _blendFunc); _customCommand.init(_globalZOrder, _blendFunc);
renderer->addCommand(&_customCommand); renderer->addCommand(&_customCommand);
cocos2d::Mat4 projectionMat = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); cocos2d::Mat4 projectionMat = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
auto& pipelineDescriptor = _customCommand.getPipelineDescriptor(); auto& pipelineDescriptor = _customCommand.getPipelineDescriptor();
pipelineDescriptor.programState->setUniform(_mvpMatrixLocation, projectionMat.m, sizeof(projectionMat.m)); pipelineDescriptor.programState->setUniform(_mvpMatrixLocation, projectionMat.m, sizeof(projectionMat.m));
@ -722,7 +721,7 @@ void LayerRadialGradient::draw(Renderer *renderer, const Mat4 &transform, uint32
_customCommand.init(_globalZOrder, _blendFunc); _customCommand.init(_globalZOrder, _blendFunc);
renderer->addCommand(&_customCommand); renderer->addCommand(&_customCommand);
const auto& projectionMat = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); const auto& projectionMat = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
auto programState = _customCommand.getPipelineDescriptor().programState; auto programState = _customCommand.getPipelineDescriptor().programState;
Mat4 finalMat = projectionMat * transform; Mat4 finalMat = projectionMat * transform;
programState->setUniform(_mvpMatrixLocation, finalMat.m, sizeof(finalMat.m)); programState->setUniform(_mvpMatrixLocation, finalMat.m, sizeof(finalMat.m));

View File

@ -119,7 +119,7 @@ bool Menu::initWithArray(const Vector<MenuItem*>& arrayOfItems)
{ {
_enabled = true; _enabled = true;
// menu in the center of the screen // menu in the center of the screen
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
this->setIgnoreAnchorPointForPosition(true); this->setIgnoreAnchorPointForPosition(true);
setAnchorPoint(Vec2(0.5f, 0.5f)); setAnchorPoint(Vec2(0.5f, 0.5f));

View File

@ -82,7 +82,7 @@ bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Co
{ {
CCASSERT(!path.empty(), "Invalid filename"); CCASSERT(!path.empty(), "Invalid filename");
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(path); Texture2D *texture = _director->getTextureCache()->addImage(path);
return initWithFade(fade, minSeg, stroke, color, texture); return initWithFade(fade, minSeg, stroke, color, texture);
} }
@ -101,7 +101,7 @@ bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Co
_stroke = stroke; _stroke = stroke;
_fadeDelta = 1.0f / fade; _fadeDelta = 1.0f / fade;
double fps = 1 / Director::getInstance()->getAnimationInterval(); double fps = 1 / _director->getAnimationInterval();
_maxPoints = (int)(fade * fps) + 2; _maxPoints = (int)(fade * fps) + 2;
_pointState = (float *)malloc(sizeof(float) * _maxPoints); _pointState = (float *)malloc(sizeof(float) * _maxPoints);
@ -409,7 +409,7 @@ void MotionStreak::draw(Renderer *renderer, const Mat4 &transform, uint32_t flag
auto programState = _customCommand.getPipelineDescriptor().programState; auto programState = _customCommand.getPipelineDescriptor().programState;
const auto& projectionMat = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); const auto& projectionMat = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
Mat4 finalMat = projectionMat * transform; Mat4 finalMat = projectionMat * transform;
programState->setUniform(_mvpMatrixLocaiton, finalMat.m, sizeof(Mat4)); programState->setUniform(_mvpMatrixLocaiton, finalMat.m, sizeof(Mat4));

View File

@ -110,16 +110,13 @@ void NodeGrid::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t p
// IMPORTANT: // IMPORTANT:
// To ease the migration to v3.0, we still support the Mat4 stack, // To ease the migration to v3.0, we still support the Mat4 stack,
// but it is deprecated and your code should not rely on it // but it is deprecated and your code should not rely on it
Director* director = Director::getInstance(); _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
CCASSERT(nullptr != director, "Director is null when setting matrix stack"); _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
Director::Projection beforeProjectionType = Director::Projection::DEFAULT; Director::Projection beforeProjectionType = Director::Projection::DEFAULT;
if(_nodeGrid && _nodeGrid->isActive()) if(_nodeGrid && _nodeGrid->isActive())
{ {
beforeProjectionType = Director::getInstance()->getProjection(); beforeProjectionType = _director->getProjection();
_nodeGrid->set2DProjection(); _nodeGrid->set2DProjection();
} }
@ -166,12 +163,12 @@ void NodeGrid::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t p
if(_nodeGrid && _nodeGrid->isActive()) if(_nodeGrid && _nodeGrid->isActive())
{ {
// restore projection // restore projection
director->setProjection(beforeProjectionType); _director->setProjection(beforeProjectionType);
} }
onGridEndDraw(); onGridEndDraw();
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); _director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
} }
void NodeGrid::setGrid(GridBase *grid) void NodeGrid::setGrid(GridBase *grid)

View File

@ -6,6 +6,7 @@
* Copyright (c) 2011 Marco Tillemans * Copyright (c) 2011 Marco Tillemans
* Copyright (c) 2013-2016 Chukong Technologies Inc. * Copyright (c) 2013-2016 Chukong Technologies Inc.
* Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. * Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
* Copyright (c) 2020-2021 C4games.com.
* *
* http://www.cocos2d-x.org * http://www.cocos2d-x.org
* *
@ -124,6 +125,8 @@ bool ParticleBatchNode::initWithTexture(Texture2D *tex, int capacity)
_textureAtlas = new (std::nothrow) TextureAtlas(); _textureAtlas = new (std::nothrow) TextureAtlas();
_textureAtlas->initWithTexture(tex, capacity); _textureAtlas->initWithTexture(tex, capacity);
updateProgramStateTexture();
_children.reserve(capacity); _children.reserve(capacity);
_blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
@ -136,7 +139,7 @@ bool ParticleBatchNode::initWithTexture(Texture2D *tex, int capacity)
*/ */
bool ParticleBatchNode::initWithFile(const std::string& fileImage, int capacity) bool ParticleBatchNode::initWithFile(const std::string& fileImage, int capacity)
{ {
Texture2D *tex = Director::getInstance()->getTextureCache()->addImage(fileImage); Texture2D *tex = _director->getTextureCache()->addImage(fileImage);
return initWithTexture(tex, capacity); return initWithTexture(tex, capacity);
} }
@ -165,13 +168,12 @@ void ParticleBatchNode::visit(Renderer *renderer, const Mat4 &parentTransform, u
// IMPORTANT:d // IMPORTANT:d
// To ease the migration to v3.0, we still support the Mat4 stack, // To ease the migration to v3.0, we still support the Mat4 stack,
// but it is deprecated and your code should not rely on it // but it is deprecated and your code should not rely on it
Director* director = Director::getInstance(); _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
draw(renderer, _modelViewTransform, flags); draw(renderer, _modelViewTransform, flags);
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); _director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
} }
} }
@ -439,11 +441,10 @@ void ParticleBatchNode::draw(Renderer* renderer, const Mat4 & transform, uint32_
_customCommand.init(_globalZOrder, _blendFunc); _customCommand.init(_globalZOrder, _blendFunc);
// Texture is set in TextureAtlas. // Texture is set in TextureAtlas.
const cocos2d::Mat4& projectionMat = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); const cocos2d::Mat4& projectionMat = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
Mat4 finalMat = projectionMat * transform; Mat4 finalMat = projectionMat * transform;
auto programState = _customCommand.getPipelineDescriptor().programState; auto programState = _customCommand.getPipelineDescriptor().programState;
programState->setUniform(_mvpMatrixLocaiton, finalMat.m, sizeof(finalMat.m)); programState->setUniform(_mvpMatrixLocaiton, finalMat.m, sizeof(finalMat.m));
if (_textureAtlas->isDirty()) if (_textureAtlas->isDirty())
{ {
const auto& quads = _textureAtlas->getQuads(); const auto& quads = _textureAtlas->getQuads();
@ -532,16 +533,20 @@ void ParticleBatchNode::updateBlendFunc()
void ParticleBatchNode::setTexture(Texture2D* texture) void ParticleBatchNode::setTexture(Texture2D* texture)
{ {
_textureAtlas->setTexture(texture); _textureAtlas->setTexture(texture);
if (texture) { updateProgramStateTexture();
}
void ParticleBatchNode::updateProgramStateTexture()
{
auto texture = _textureAtlas->getTexture();
if (!texture)
return;
auto programState = _customCommand.getPipelineDescriptor().programState; auto programState = _customCommand.getPipelineDescriptor().programState;
programState->setTexture(_textureAtlas->getTexture()->getBackendTexture()); programState->setTexture(texture->getBackendTexture());
// If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it // If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it
if (!texture->hasPremultipliedAlpha() && (_blendFunc.src == CC_BLEND_SRC && _blendFunc.dst == CC_BLEND_DST)) if (!texture->hasPremultipliedAlpha() && (_blendFunc.src == CC_BLEND_SRC && _blendFunc.dst == CC_BLEND_DST))
{
_blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED; _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED;
} }
}
}
Texture2D* ParticleBatchNode::getTexture() const Texture2D* ParticleBatchNode::getTexture() const
{ {

View File

@ -170,6 +170,9 @@ private:
int addChildHelper(ParticleSystem* child, int z, int aTag, const std::string &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, const std::string &name, bool setTag); void addChildByTagOrName(ParticleSystem* child, int z, int tag, const std::string &name, bool setTag);
void updateBlendFunc(); void updateBlendFunc();
void updateProgramStateTexture();
/** the texture atlas used for drawing the quads */ /** the texture atlas used for drawing the quads */
TextureAtlas* _textureAtlas = nullptr; TextureAtlas* _textureAtlas = nullptr;

View File

@ -113,7 +113,7 @@ bool ParticleFire::initWithTotalParticles(int numberOfParticles)
_angleVar = 10; _angleVar = 10;
// emitter position // emitter position
Size winSize = Director::getInstance()->getWinSize(); Size winSize = _director->getWinSize();
this->setPosition(winSize.width/2.0f, 60.0f); this->setPosition(winSize.width/2.0f, 60.0f);
this->_posVar.set(40.0f, 20.0f); this->_posVar.set(40.0f, 20.0f);
@ -214,7 +214,7 @@ bool ParticleFireworks::initWithTotalParticles(int numberOfParticles)
this->modeA.speedVar = 50.0f; this->modeA.speedVar = 50.0f;
// emitter position // emitter position
Size winSize = Director::getInstance()->getWinSize(); Size winSize = _director->getWinSize();
this->setPosition(winSize.width/2, winSize.height/2); this->setPosition(winSize.width/2, winSize.height/2);
// angle // angle
@ -323,7 +323,7 @@ bool ParticleSun::initWithTotalParticles(int numberOfParticles)
_angleVar = 360; _angleVar = 360;
// emitter position // emitter position
Size winSize = Director::getInstance()->getWinSize(); Size winSize = _director->getWinSize();
this->setPosition(winSize.width/2, winSize.height/2); this->setPosition(winSize.width/2, winSize.height/2);
setPosVar(Vec2::ZERO); setPosVar(Vec2::ZERO);
@ -430,7 +430,7 @@ bool ParticleGalaxy::initWithTotalParticles(int numberOfParticles)
_angleVar = 360; _angleVar = 360;
// emitter position // emitter position
Size winSize = Director::getInstance()->getWinSize(); Size winSize = _director->getWinSize();
this->setPosition(winSize.width/2, winSize.height/2); this->setPosition(winSize.width/2, winSize.height/2);
setPosVar(Vec2::ZERO); setPosVar(Vec2::ZERO);
@ -539,7 +539,7 @@ bool ParticleFlower::initWithTotalParticles(int numberOfParticles)
_angleVar = 360; _angleVar = 360;
// emitter position // emitter position
Size winSize = Director::getInstance()->getWinSize(); Size winSize = _director->getWinSize();
this->setPosition(winSize.width/2, winSize.height/2); this->setPosition(winSize.width/2, winSize.height/2);
setPosVar(Vec2::ZERO); setPosVar(Vec2::ZERO);
@ -647,7 +647,7 @@ bool ParticleMeteor::initWithTotalParticles(int numberOfParticles)
_angleVar = 360; _angleVar = 360;
// emitter position // emitter position
Size winSize = Director::getInstance()->getWinSize(); Size winSize = _director->getWinSize();
this->setPosition(winSize.width/2, winSize.height/2); this->setPosition(winSize.width/2, winSize.height/2);
setPosVar(Vec2::ZERO); setPosVar(Vec2::ZERO);
@ -756,7 +756,7 @@ bool ParticleSpiral::initWithTotalParticles(int numberOfParticles)
_angleVar = 0; _angleVar = 0;
// emitter position // emitter position
Size winSize = Director::getInstance()->getWinSize(); Size winSize = _director->getWinSize();
this->setPosition(winSize.width/2, winSize.height/2); this->setPosition(winSize.width/2, winSize.height/2);
setPosVar(Vec2::ZERO); setPosVar(Vec2::ZERO);
@ -864,7 +864,7 @@ bool ParticleExplosion::initWithTotalParticles(int numberOfParticles)
_angleVar = 360; _angleVar = 360;
// emitter position // emitter position
Size winSize = Director::getInstance()->getWinSize(); Size winSize = _director->getWinSize();
this->setPosition(winSize.width/2, winSize.height/2); this->setPosition(winSize.width/2, winSize.height/2);
setPosVar(Vec2::ZERO); setPosVar(Vec2::ZERO);
@ -969,7 +969,7 @@ bool ParticleSmoke::initWithTotalParticles(int numberOfParticles)
_angleVar = 5; _angleVar = 5;
// emitter position // emitter position
Size winSize = Director::getInstance()->getWinSize(); Size winSize = _director->getWinSize();
this->setPosition(winSize.width/2, 0); this->setPosition(winSize.width/2, 0);
setPosVar(Vec2(20, 0)); setPosVar(Vec2(20, 0));
@ -1074,7 +1074,7 @@ bool ParticleSnow::initWithTotalParticles(int numberOfParticles)
setTangentialAccelVar(1); setTangentialAccelVar(1);
// emitter position // emitter position
Size winSize = Director::getInstance()->getWinSize(); Size winSize = _director->getWinSize();
this->setPosition(winSize.width/2, winSize.height + 10); this->setPosition(winSize.width/2, winSize.height + 10);
setPosVar(Vec2(winSize.width/2, 0.0f)); setPosVar(Vec2(winSize.width/2, 0.0f));
@ -1186,7 +1186,7 @@ bool ParticleRain::initWithTotalParticles(int numberOfParticles)
// emitter position // emitter position
Size winSize = Director::getInstance()->getWinSize(); Size winSize = _director->getWinSize();
this->setPosition(winSize.width/2, winSize.height); this->setPosition(winSize.width/2, winSize.height);
setPosVar(Vec2(winSize.width/2, 0.0f)); setPosVar(Vec2(winSize.width/2, 0.0f));

View File

@ -500,7 +500,7 @@ bool ParticleSystem::initWithDictionary(ValueMap& dictionary, const std::string&
// set not pop-up message box when load image failed // set not pop-up message box when load image failed
bool notify = FileUtils::getInstance()->isPopupNotify(); bool notify = FileUtils::getInstance()->isPopupNotify();
FileUtils::getInstance()->setPopupNotify(false); FileUtils::getInstance()->setPopupNotify(false);
tex = Director::getInstance()->getTextureCache()->addImage(textureName); tex = _director->getTextureCache()->addImage(textureName);
// reset the value of UIImage notify // reset the value of UIImage notify
FileUtils::getInstance()->setPopupNotify(notify); FileUtils::getInstance()->setPopupNotify(notify);
} }
@ -533,7 +533,7 @@ bool ParticleSystem::initWithDictionary(ValueMap& dictionary, const std::string&
CCASSERT(isOK, "CCParticleSystem: error init image with Data"); CCASSERT(isOK, "CCParticleSystem: error init image with Data");
CC_BREAK_IF(!isOK); CC_BREAK_IF(!isOK);
setTexture(Director::getInstance()->getTextureCache()->addImage(image, _plistFile + textureName)); setTexture(_director->getTextureCache()->addImage(image, _plistFile + textureName));
image->release(); image->release();
} }

View File

@ -453,7 +453,7 @@ void ParticleSystemQuad::draw(Renderer *renderer, const Mat4 &transform, uint32_
{ {
auto programState = _quadCommand.getPipelineDescriptor().programState; auto programState = _quadCommand.getPipelineDescriptor().programState;
cocos2d::Mat4 projectionMat = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); cocos2d::Mat4 projectionMat = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
programState->setUniform(_mvpMatrixLocaiton, projectionMat.m, sizeof(projectionMat.m)); programState->setUniform(_mvpMatrixLocaiton, projectionMat.m, sizeof(projectionMat.m));
_quadCommand.init(_globalZOrder, _texture, _blendFunc, _quads, _particleCount, transform, flags); _quadCommand.init(_globalZOrder, _texture, _blendFunc, _quads, _particleCount, transform, flags);

View File

@ -569,7 +569,7 @@ void ProgressTimer::draw(Renderer *renderer, const Mat4 &transform, uint32_t fla
if( _vertexData.empty() || ! _sprite) if( _vertexData.empty() || ! _sprite)
return; return;
const cocos2d::Mat4& projectionMat = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); const cocos2d::Mat4& projectionMat = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
Mat4 finalMat = projectionMat * transform; Mat4 finalMat = projectionMat * transform;
_programState->setUniform(_locMVP1, finalMat.m, sizeof(finalMat.m)); _programState->setUniform(_locMVP1, finalMat.m, sizeof(finalMat.m));
_programState->setTexture(_locTex1, 0, _sprite->getTexture()->getBackendTexture()); _programState->setTexture(_locTex1, 0, _sprite->getTexture()->getBackendTexture());

View File

@ -272,10 +272,8 @@ void ProtectedNode::visit(Renderer* renderer, const Mat4 &parentTransform, uint3
// IMPORTANT: // IMPORTANT:
// To ease the migration to v3.0, we still support the Mat4 stack, // To ease the migration to v3.0, we still support the Mat4 stack,
// but it is deprecated and your code should not rely on it // but it is deprecated and your code should not rely on it
Director* director = Director::getInstance(); _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
CCASSERT(nullptr != director, "Director is null when setting matrix stack"); _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
int i = 0; // used by _children int i = 0; // used by _children
int j = 0; // used by _protectedChildren int j = 0; // used by _protectedChildren
@ -325,7 +323,7 @@ void ProtectedNode::visit(Renderer* renderer, const Mat4 &parentTransform, uint3
// Please refer to https://github.com/cocos2d/cocos2d-x/pull/6920 // Please refer to https://github.com/cocos2d/cocos2d-x/pull/6920
// setOrderOfArrival(0); // setOrderOfArrival(0);
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); _director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
} }
void ProtectedNode::onEnter() void ProtectedNode::onEnter()

View File

@ -484,7 +484,7 @@ void RenderTexture::draw(Renderer *renderer, const Mat4 &transform, uint32_t fla
begin(); begin();
//clear screen //clear screen
Director::getInstance()->getRenderer()->clear(_clearFlags, _clearColor, _clearDepth, _clearStencil, _globalZOrder); _director->getRenderer()->clear(_clearFlags, _clearColor, _clearDepth, _clearStencil, _globalZOrder);
//! make sure all children are drawn //! make sure all children are drawn
sortAllChildren(); sortAllChildren();
@ -502,27 +502,25 @@ void RenderTexture::draw(Renderer *renderer, const Mat4 &transform, uint32_t fla
void RenderTexture::onBegin() void RenderTexture::onBegin()
{ {
Director *director = Director::getInstance(); _oldProjMatrix = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
_director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, _projectionMatrix);
_oldProjMatrix = director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); _oldTransMatrix = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, _projectionMatrix); _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _transformMatrix);
_oldTransMatrix = director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _transformMatrix);
if(!_keepMatrix) if(!_keepMatrix)
{ {
director->setProjection(director->getProjection()); _director->setProjection(_director->getProjection());
const Size& texSize = _texture2D->getContentSizeInPixels(); const Size& texSize = _texture2D->getContentSizeInPixels();
// Calculate the adjustment ratios based on the old and new projections // Calculate the adjustment ratios based on the old and new projections
Size size = director->getWinSizeInPixels(); Size size = _director->getWinSizeInPixels();
float widthRatio = size.width / texSize.width; float widthRatio = size.width / texSize.width;
float heightRatio = size.height / texSize.height; float heightRatio = size.height / texSize.height;
Mat4 orthoMatrix; Mat4 orthoMatrix;
Mat4::createOrthographicOffCenter((float)-1.0 / widthRatio, (float)1.0 / widthRatio, (float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1, 1, &orthoMatrix); Mat4::createOrthographicOffCenter((float)-1.0 / widthRatio, (float)1.0 / widthRatio, (float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1, 1, &orthoMatrix);
director->multiplyMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, orthoMatrix); _director->multiplyMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, orthoMatrix);
} }
Rect viewport; Rect viewport;
@ -533,7 +531,7 @@ void RenderTexture::onBegin()
viewport.origin.x = (_fullRect.origin.x - _rtTextureRect.origin.x) * viewPortRectWidthRatio; viewport.origin.x = (_fullRect.origin.x - _rtTextureRect.origin.x) * viewPortRectWidthRatio;
viewport.origin.y = (_fullRect.origin.y - _rtTextureRect.origin.y) * viewPortRectHeightRatio; viewport.origin.y = (_fullRect.origin.y - _rtTextureRect.origin.y) * viewPortRectHeightRatio;
Renderer *renderer = director->getRenderer(); Renderer *renderer = _director->getRenderer();
_oldViewport = renderer->getViewport(); _oldViewport = renderer->getViewport();
renderer->setViewPort(viewport.origin.x, viewport.origin.y, viewport.size.width, viewport.size.height); renderer->setViewPort(viewport.origin.x, viewport.origin.y, viewport.size.width, viewport.size.height);
@ -544,11 +542,10 @@ void RenderTexture::onBegin()
void RenderTexture::onEnd() void RenderTexture::onEnd()
{ {
Director *director = Director::getInstance(); _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, _oldProjMatrix);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, _oldProjMatrix); _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _oldTransMatrix);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _oldTransMatrix);
Renderer *renderer = Director::getInstance()->getRenderer(); Renderer *renderer = _director->getRenderer();
renderer->setViewPort(_oldViewport.x, _oldViewport.y, _oldViewport.w, _oldViewport.h); renderer->setViewPort(_oldViewport.x, _oldViewport.y, _oldViewport.w, _oldViewport.h);
renderer->setRenderTarget(_oldRenderTarget); renderer->setRenderTarget(_oldRenderTarget);
@ -615,7 +612,7 @@ void RenderTexture::setClearFlags(ClearFlag clearFlags)
void RenderTexture::clearColorAttachment() void RenderTexture::clearColorAttachment()
{ {
auto renderer = Director::getInstance()->getRenderer(); auto renderer = _director->getRenderer();
_beforeClearAttachmentCommand.func = [=]() -> void { _beforeClearAttachmentCommand.func = [=]() -> void {
_oldRenderTarget = renderer->getRenderTarget(); _oldRenderTarget = renderer->getRenderTarget();
renderer->setRenderTarget(_renderTarget); renderer->setRenderTarget(_renderTarget);

View File

@ -51,7 +51,7 @@ NS_CC_BEGIN
Scene::Scene() Scene::Scene()
: _defaultCamera(Camera::create()) : _defaultCamera(Camera::create())
, _event(Director::getInstance()->getEventDispatcher()->addCustomEventListener(Director::EVENT_PROJECTION_CHANGED, std::bind(&Scene::onProjectionChanged, this, std::placeholders::_1))) , _event(_director->getEventDispatcher()->addCustomEventListener(Director::EVENT_PROJECTION_CHANGED, std::bind(&Scene::onProjectionChanged, this, std::placeholders::_1)))
{ {
_ignoreAnchorPointForPosition = true; _ignoreAnchorPointForPosition = true;
setAnchorPoint(Vec2(0.5f, 0.5f)); setAnchorPoint(Vec2(0.5f, 0.5f));
@ -74,7 +74,7 @@ Scene::~Scene()
#if CC_USE_NAVMESH #if CC_USE_NAVMESH
CC_SAFE_RELEASE(_navMesh); CC_SAFE_RELEASE(_navMesh);
#endif #endif
Director::getInstance()->getEventDispatcher()->removeEventListener(_event); _director->getEventDispatcher()->removeEventListener(_event);
CC_SAFE_RELEASE(_event); CC_SAFE_RELEASE(_event);
#if CC_USE_PHYSICS #if CC_USE_PHYSICS
@ -104,7 +104,7 @@ void Scene::setNavMesh(NavMesh* navMesh)
bool Scene::init() bool Scene::init()
{ {
auto size = Director::getInstance()->getWinSize(); auto size = _director->getWinSize();
return initWithSize(size); return initWithSize(size);
} }
@ -174,7 +174,6 @@ const std::vector<Camera*>& Scene::getCameras()
void Scene::render(Renderer* renderer, const Mat4& eyeTransform, const Mat4* eyeProjection) void Scene::render(Renderer* renderer, const Mat4& eyeTransform, const Mat4* eyeProjection)
{ {
auto director = Director::getInstance();
Camera* defaultCamera = nullptr; Camera* defaultCamera = nullptr;
const auto& transform = getNodeToParentTransform(); const auto& transform = getNodeToParentTransform();
@ -200,8 +199,8 @@ void Scene::render(Renderer* renderer, const Mat4& eyeTransform, const Mat4* eye
camera->setAdditionalProjection(*eyeProjection * camera->getProjectionMatrix().getInversed()); camera->setAdditionalProjection(*eyeProjection * camera->getProjectionMatrix().getInversed());
camera->setAdditionalTransform(eyeTransform.getInversed()); camera->setAdditionalTransform(eyeTransform.getInversed());
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, Camera::_visitingCamera->getViewProjectionMatrix()); _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, Camera::_visitingCamera->getViewProjectionMatrix());
camera->apply(); camera->apply();
//clear background with max depth //clear background with max depth
@ -217,7 +216,7 @@ void Scene::render(Renderer* renderer, const Mat4& eyeTransform, const Mat4* eye
renderer->render(); renderer->render();
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); _director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
// we shouldn't restore the transform matrix since it could be used // we shouldn't restore the transform matrix since it could be used
// from "update" or other parts of the game to calculate culling or something else. // from "update" or other parts of the game to calculate culling or something else.
@ -233,8 +232,8 @@ void Scene::render(Renderer* renderer, const Mat4& eyeTransform, const Mat4* eye
physics3dDebugCamera->setAdditionalProjection(*eyeProjection * physics3dDebugCamera->getProjectionMatrix().getInversed()); physics3dDebugCamera->setAdditionalProjection(*eyeProjection * physics3dDebugCamera->getProjectionMatrix().getInversed());
physics3dDebugCamera->setAdditionalTransform(eyeTransform.getInversed()); physics3dDebugCamera->setAdditionalTransform(eyeTransform.getInversed());
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, physics3dDebugCamera->getViewProjectionMatrix()); _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, physics3dDebugCamera->getViewProjectionMatrix());
physics3dDebugCamera->apply(); physics3dDebugCamera->apply();
physics3dDebugCamera->clearBackground(); physics3dDebugCamera->clearBackground();
@ -242,7 +241,7 @@ void Scene::render(Renderer* renderer, const Mat4& eyeTransform, const Mat4* eye
_physics3DWorld->debugDraw(renderer); _physics3DWorld->debugDraw(renderer);
renderer->render(); renderer->render();
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); _director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
} }
#endif #endif
@ -308,10 +307,7 @@ bool Scene::initWithPhysics()
bool ret = false; bool ret = false;
do do
{ {
Director * director; this->setContentSize(_director->getWinSize());
CC_BREAK_IF( ! (director = Director::getInstance()) );
this->setContentSize(director->getWinSize());
#if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION #if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION
Physics3DWorldDes info; Physics3DWorldDes info;

View File

@ -336,7 +336,7 @@ static unsigned char cc_2x2_white_image[] = {
// MARK: texture // MARK: texture
void Sprite::setTexture(const std::string &filename) void Sprite::setTexture(const std::string &filename)
{ {
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); Texture2D *texture = _director->getTextureCache()->addImage(filename);
setTexture(texture); setTexture(texture);
_unflippedOffsetPositionFromCenter = Vec2::ZERO; _unflippedOffsetPositionFromCenter = Vec2::ZERO;
Rect rect = Rect::ZERO; Rect rect = Rect::ZERO;
@ -1716,7 +1716,7 @@ void Sprite::setPolygonInfo(const PolygonInfo& info)
void Sprite::setMVPMatrixUniform() void Sprite::setMVPMatrixUniform()
{ {
const auto& projectionMat = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); const auto& projectionMat = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
auto programState = _trianglesCommand.getPipelineDescriptor().programState; auto programState = _trianglesCommand.getPipelineDescriptor().programState;
if (programState && _mvpMatrixLocation) if (programState && _mvpMatrixLocation)
programState->setUniform(_mvpMatrixLocation, projectionMat.m, sizeof(projectionMat.m)); programState->setUniform(_mvpMatrixLocation, projectionMat.m, sizeof(projectionMat.m));

View File

@ -174,7 +174,7 @@ bool SpriteBatchNode::init()
*/ */
bool SpriteBatchNode::initWithFile(const std::string& fileImage, ssize_t capacity/* = DEFAULT_CAPACITY*/) bool SpriteBatchNode::initWithFile(const std::string& fileImage, ssize_t capacity/* = DEFAULT_CAPACITY*/)
{ {
Texture2D *texture2D = Director::getInstance()->getTextureCache()->addImage(fileImage); Texture2D *texture2D = _director->getTextureCache()->addImage(fileImage);
return initWithTexture(texture2D, capacity); return initWithTexture(texture2D, capacity);
} }
@ -435,7 +435,7 @@ void SpriteBatchNode::draw(Renderer *renderer, const Mat4 &transform, uint32_t f
child->updateTransform(); child->updateTransform();
} }
const auto& matrixProjection = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); const auto& matrixProjection = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
auto programState = _quadCommand.getPipelineDescriptor().programState; auto programState = _quadCommand.getPipelineDescriptor().programState;
programState->setUniform(_mvpMatrixLocaiton, matrixProjection.m, sizeof(matrixProjection.m)); programState->setUniform(_mvpMatrixLocaiton, matrixProjection.m, sizeof(matrixProjection.m));
_quadCommand.init(_globalZOrder, _textureAtlas->getTexture(), _blendFunc, _textureAtlas->getQuads(), _textureAtlas->getTotalQuads(), transform, flags); _quadCommand.init(_globalZOrder, _textureAtlas->getTexture(), _blendFunc, _textureAtlas->getQuads(), _textureAtlas->getTotalQuads(), transform, flags);

View File

@ -196,7 +196,7 @@ bool TextFieldTTF::attachWithIME()
if (ret) if (ret)
{ {
// open keyboard // open keyboard
auto pGlView = Director::getInstance()->getOpenGLView(); auto pGlView = _director->getOpenGLView();
if (pGlView) if (pGlView)
{ {
pGlView->setIMEKeyboardState(true); pGlView->setIMEKeyboardState(true);
@ -211,7 +211,7 @@ bool TextFieldTTF::detachWithIME()
if (ret) if (ret)
{ {
// close keyboard // close keyboard
auto glView = Director::getInstance()->getOpenGLView(); auto glView = _director->getOpenGLView();
if (glView) if (glView)
{ {
glView->setIMEKeyboardState(false); glView->setIMEKeyboardState(false);

View File

@ -88,7 +88,7 @@ bool TransitionScene::initWithDuration(float t, Scene *scene)
#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS #endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
_inScene = scene; _inScene = scene;
_inScene->retain(); _inScene->retain();
_outScene = Director::getInstance()->getRunningScene(); _outScene = _director->getRunningScene();
if (_outScene == nullptr) if (_outScene == nullptr)
{ {
_outScene = Scene::create(); _outScene = Scene::create();
@ -152,10 +152,9 @@ void TransitionScene::setNewScene(float /*dt*/)
this->unschedule(CC_SCHEDULE_SELECTOR(TransitionScene::setNewScene)); this->unschedule(CC_SCHEDULE_SELECTOR(TransitionScene::setNewScene));
// Before replacing, save the "send cleanup to scene" // Before replacing, save the "send cleanup to scene"
Director *director = Director::getInstance(); _isSendCleanupToScene = _director->isSendCleanupToScene();
_isSendCleanupToScene = director->isSendCleanupToScene();
director->replaceScene(_inScene); _director->replaceScene(_inScene);
#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine(); auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
if (sEngine) if (sEngine)
@ -329,7 +328,7 @@ TransitionJumpZoom* TransitionJumpZoom::create(float t, Scene* scene)
void TransitionJumpZoom::onEnter() void TransitionJumpZoom::onEnter()
{ {
TransitionScene::onEnter(); TransitionScene::onEnter();
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
_inScene->setScale(0.5f); _inScene->setScale(0.5f);
_inScene->setPosition(s.width, 0); _inScene->setPosition(s.width, 0);
@ -412,7 +411,7 @@ ActionInterval* TransitionMoveInL::easeActionWithAction(ActionInterval* action)
void TransitionMoveInL::initScenes() void TransitionMoveInL::initScenes()
{ {
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
_inScene->setPosition(-s.width,0); _inScene->setPosition(-s.width,0);
} }
@ -440,7 +439,7 @@ TransitionMoveInR* TransitionMoveInR::create(float t, Scene* scene)
void TransitionMoveInR::initScenes() void TransitionMoveInR::initScenes()
{ {
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
_inScene->setPosition(s.width,0); _inScene->setPosition(s.width,0);
} }
@ -468,7 +467,7 @@ TransitionMoveInT* TransitionMoveInT::create(float t, Scene* scene)
void TransitionMoveInT::initScenes() void TransitionMoveInT::initScenes()
{ {
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
_inScene->setPosition(0,s.height); _inScene->setPosition(0,s.height);
} }
@ -496,7 +495,7 @@ TransitionMoveInB* TransitionMoveInB::create(float t, Scene* scene)
void TransitionMoveInB::initScenes() void TransitionMoveInB::initScenes()
{ {
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
_inScene->setPosition(0,-s.height); _inScene->setPosition(0,-s.height);
} }
@ -544,13 +543,13 @@ void TransitionSlideInL::sceneOrder()
void TransitionSlideInL:: initScenes() void TransitionSlideInL:: initScenes()
{ {
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
_inScene->setPosition(-(s.width-ADJUST_FACTOR),0.0f); _inScene->setPosition(-(s.width-ADJUST_FACTOR),0.0f);
} }
ActionInterval* TransitionSlideInL::action() ActionInterval* TransitionSlideInL::action()
{ {
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
return MoveBy::create(_duration, Vec2(s.width-ADJUST_FACTOR,0.0f)); return MoveBy::create(_duration, Vec2(s.width-ADJUST_FACTOR,0.0f));
} }
@ -600,14 +599,14 @@ void TransitionSlideInR::sceneOrder()
void TransitionSlideInR::initScenes() void TransitionSlideInR::initScenes()
{ {
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
_inScene->setPosition(s.width-ADJUST_FACTOR,0); _inScene->setPosition(s.width-ADJUST_FACTOR,0);
} }
ActionInterval* TransitionSlideInR:: action() ActionInterval* TransitionSlideInR:: action()
{ {
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
return MoveBy::create(_duration, Vec2(-(s.width-ADJUST_FACTOR),0.0f)); return MoveBy::create(_duration, Vec2(-(s.width-ADJUST_FACTOR),0.0f));
} }
@ -641,14 +640,14 @@ void TransitionSlideInT::sceneOrder()
void TransitionSlideInT::initScenes() void TransitionSlideInT::initScenes()
{ {
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
_inScene->setPosition(0,s.height-ADJUST_FACTOR); _inScene->setPosition(0,s.height-ADJUST_FACTOR);
} }
ActionInterval* TransitionSlideInT::action() ActionInterval* TransitionSlideInT::action()
{ {
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
return MoveBy::create(_duration, Vec2(0.0f,-(s.height-ADJUST_FACTOR))); return MoveBy::create(_duration, Vec2(0.0f,-(s.height-ADJUST_FACTOR)));
} }
@ -681,14 +680,14 @@ void TransitionSlideInB::sceneOrder()
void TransitionSlideInB:: initScenes() void TransitionSlideInB:: initScenes()
{ {
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
_inScene->setPosition(0,-(s.height-ADJUST_FACTOR)); _inScene->setPosition(0,-(s.height-ADJUST_FACTOR));
} }
ActionInterval* TransitionSlideInB:: action() ActionInterval* TransitionSlideInB:: action()
{ {
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
return MoveBy::create(_duration, Vec2(0.0f,s.height-ADJUST_FACTOR)); return MoveBy::create(_duration, Vec2(0.0f,s.height-ADJUST_FACTOR));
} }
@ -1289,7 +1288,7 @@ void TransitionCrossFade::onEnter()
// create a transparent color layer // create a transparent color layer
// in which we are going to add our rendertextures // in which we are going to add our rendertextures
Color4B color(0,0,0,0); Color4B color(0,0,0,0);
Size size = Director::getInstance()->getWinSize(); Size size = _director->getWinSize();
LayerColor* layer = LayerColor::create(color); LayerColor* layer = LayerColor::create(color);
// create the first render texture for inScene // create the first render texture for inScene
@ -1397,7 +1396,7 @@ void TransitionTurnOffTiles::onEnter()
_outSceneProxy->setTarget(_outScene); _outSceneProxy->setTarget(_outScene);
_outSceneProxy->onEnter(); _outSceneProxy->onEnter();
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
float aspect = s.width / s.height; float aspect = s.width / s.height;
int x = (int)(12 * aspect); int x = (int)(12 * aspect);
int y = 12; int y = 12;
@ -1593,7 +1592,7 @@ void TransitionFadeTR::onEnter()
_outSceneProxy->setTarget(_outScene); _outSceneProxy->setTarget(_outScene);
_outSceneProxy->onEnter(); _outSceneProxy->onEnter();
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
float aspect = s.width / s.height; float aspect = s.width / s.height;
int x = (int)(12 * aspect); int x = (int)(12 * aspect);
int y = 12; int y = 12;

View File

@ -99,7 +99,7 @@ void TransitionPageTurn::onEnter()
_inSceneProxy->onEnter(); _inSceneProxy->onEnter();
_outSceneProxy->onEnter(); _outSceneProxy->onEnter();
Size s = Director::getInstance()->getWinSize(); Size s = _director->getWinSize();
int x,y; int x,y;
if (s.width > s.height) if (s.width > s.height)
{ {

View File

@ -69,7 +69,7 @@ void TransitionProgress::onEnter()
// create a transparent color layer // create a transparent color layer
// in which we are going to add our rendertextures // in which we are going to add our rendertextures
Size size = Director::getInstance()->getWinSize(); auto& size = _director->getWinSize();
// create the second render texture for outScene // create the second render texture for outScene
RenderTexture *texture = RenderTexture::create((int)size.width, (int)size.height,backend::PixelFormat::RGBA8, backend::PixelFormat::D24S8); RenderTexture *texture = RenderTexture::create((int)size.width, (int)size.height,backend::PixelFormat::RGBA8, backend::PixelFormat::D24S8);
@ -134,7 +134,7 @@ ProgressTimer* TransitionProgress::progressTimerNodeWithRenderTexture(RenderText
ProgressTimer* TransitionProgressRadialCCW::progressTimerNodeWithRenderTexture(RenderTexture* texture) ProgressTimer* TransitionProgressRadialCCW::progressTimerNodeWithRenderTexture(RenderTexture* texture)
{ {
Size size = Director::getInstance()->getWinSize(); auto& size = _director->getWinSize();
ProgressTimer* node = ProgressTimer::create(texture->getSprite()); ProgressTimer* node = ProgressTimer::create(texture->getSprite());
@ -178,7 +178,7 @@ TransitionProgressRadialCW* TransitionProgressRadialCW::create(float t, Scene* s
ProgressTimer* TransitionProgressRadialCW::progressTimerNodeWithRenderTexture(RenderTexture* texture) ProgressTimer* TransitionProgressRadialCW::progressTimerNodeWithRenderTexture(RenderTexture* texture)
{ {
Size size = Director::getInstance()->getWinSize(); auto& size = _director->getWinSize();
ProgressTimer* node = ProgressTimer::create(texture->getSprite()); ProgressTimer* node = ProgressTimer::create(texture->getSprite());
@ -210,7 +210,7 @@ TransitionProgressHorizontal* TransitionProgressHorizontal::create(float t, Scen
ProgressTimer* TransitionProgressHorizontal::progressTimerNodeWithRenderTexture(RenderTexture* texture) ProgressTimer* TransitionProgressHorizontal::progressTimerNodeWithRenderTexture(RenderTexture* texture)
{ {
Size size = Director::getInstance()->getWinSize(); auto& size = _director->getWinSize();
ProgressTimer* node = ProgressTimer::create(texture->getSprite()); ProgressTimer* node = ProgressTimer::create(texture->getSprite());
@ -243,7 +243,7 @@ TransitionProgressVertical* TransitionProgressVertical::create(float t, Scene* s
ProgressTimer* TransitionProgressVertical::progressTimerNodeWithRenderTexture(RenderTexture* texture) ProgressTimer* TransitionProgressVertical::progressTimerNodeWithRenderTexture(RenderTexture* texture)
{ {
Size size = Director::getInstance()->getWinSize(); auto& size = _director->getWinSize();
ProgressTimer* node = ProgressTimer::create(texture->getSprite()); ProgressTimer* node = ProgressTimer::create(texture->getSprite());
@ -289,7 +289,7 @@ void TransitionProgressInOut::setupTransition()
ProgressTimer* TransitionProgressInOut::progressTimerNodeWithRenderTexture(RenderTexture* texture) ProgressTimer* TransitionProgressInOut::progressTimerNodeWithRenderTexture(RenderTexture* texture)
{ {
Size size = Director::getInstance()->getWinSize(); auto& size = _director->getWinSize();
ProgressTimer* node = ProgressTimer::create(texture->getSprite()); ProgressTimer* node = ProgressTimer::create(texture->getSprite());
@ -323,7 +323,7 @@ TransitionProgressOutIn* TransitionProgressOutIn::create(float t, Scene* scene)
ProgressTimer* TransitionProgressOutIn::progressTimerNodeWithRenderTexture(RenderTexture* texture) ProgressTimer* TransitionProgressOutIn::progressTimerNodeWithRenderTexture(RenderTexture* texture)
{ {
Size size = Director::getInstance()->getWinSize(); auto& size = _director->getWinSize();
ProgressTimer* node = ProgressTimer::create(texture->getSprite()); ProgressTimer* node = ProgressTimer::create(texture->getSprite());

View File

@ -123,9 +123,8 @@ void BillBoard::visit(Renderer *renderer, const Mat4& parentTransform, uint32_t
flags |= FLAGS_TRANSFORM_DIRTY; flags |= FLAGS_TRANSFORM_DIRTY;
} }
Director* director = Director::getInstance(); _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
int i = 0; int i = 0;
@ -154,7 +153,7 @@ void BillBoard::visit(Renderer *renderer, const Mat4& parentTransform, uint32_t
this->draw(renderer, _modelViewTransform, flags); this->draw(renderer, _modelViewTransform, flags);
} }
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); _director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
} }
bool BillBoard::calculateBillboardTransform() bool BillBoard::calculateBillboardTransform()

View File

@ -88,7 +88,7 @@ bool MotionStreak3D::initWithFade(float fade, float minSeg, float stroke, const
{ {
CCASSERT(!path.empty(), "Invalid filename"); CCASSERT(!path.empty(), "Invalid filename");
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(path); Texture2D *texture = _director->getTextureCache()->addImage(path);
return initWithFade(fade, minSeg, stroke, color, texture); return initWithFade(fade, minSeg, stroke, color, texture);
} }
@ -415,7 +415,7 @@ void MotionStreak3D::draw(Renderer *renderer, const Mat4 &transform, uint32_t fl
_afterCommand.init(_globalZOrder); _afterCommand.init(_globalZOrder);
_customCommand.init(_globalZOrder, transform, flags); _customCommand.init(_globalZOrder, transform, flags);
auto pmatrix = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); auto pmatrix = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
auto mvpMatrix = pmatrix * transform; auto mvpMatrix = pmatrix * transform;
_programState->setUniform(_locMVP, mvpMatrix.m, sizeof(mvpMatrix.m)); _programState->setUniform(_locMVP, mvpMatrix.m, sizeof(mvpMatrix.m));
@ -435,7 +435,7 @@ void MotionStreak3D::draw(Renderer *renderer, const Mat4 &transform, uint32_t fl
void MotionStreak3D::onBeforeDraw() void MotionStreak3D::onBeforeDraw()
{ {
auto *renderer = Director::getInstance()->getRenderer(); auto *renderer = _director->getRenderer();
_rendererDepthTest = renderer->getDepthTest(); _rendererDepthTest = renderer->getDepthTest();
_rendererCullface = renderer->getCullMode(); _rendererCullface = renderer->getCullMode();
@ -445,7 +445,7 @@ void MotionStreak3D::onBeforeDraw()
void MotionStreak3D::onAfterDraw() void MotionStreak3D::onAfterDraw()
{ {
auto *renderer = Director::getInstance()->getRenderer(); auto *renderer = _director->getRenderer();
renderer->setDepthTest(_rendererDepthTest); renderer->setDepthTest(_rendererDepthTest);
renderer->setCullMode(_rendererCullface); renderer->setCullMode(_rendererCullface);
} }

View File

@ -180,7 +180,7 @@ void Skybox::reload()
void Skybox::onBeforeDraw() void Skybox::onBeforeDraw()
{ {
auto *renderer = Director::getInstance()->getRenderer(); auto *renderer = _director->getRenderer();
_rendererDepthTestEnabled = renderer->getDepthTest(); _rendererDepthTestEnabled = renderer->getDepthTest();
_rendererDepthCmpFunc = renderer->getDepthCompareFunction(); _rendererDepthCmpFunc = renderer->getDepthCompareFunction();
@ -193,7 +193,7 @@ void Skybox::onBeforeDraw()
void Skybox::onAfterDraw() void Skybox::onAfterDraw()
{ {
auto *renderer = Director::getInstance()->getRenderer(); auto *renderer = _director->getRenderer();
renderer->setDepthTest(_rendererDepthTestEnabled); renderer->setDepthTest(_rendererDepthTestEnabled);
renderer->setDepthCompareFunction(_rendererDepthCmpFunc); renderer->setDepthCompareFunction(_rendererDepthCmpFunc);
renderer->setCullMode(_rendererCullMode); renderer->setCullMode(_rendererCullMode);

View File

@ -401,7 +401,7 @@ Sprite3D* Sprite3D::createSprite3DNode(NodeData* nodedata,ModelData* modeldata,c
textureData = materialData->getTextureData(NTextureData::Usage::Normal); textureData = materialData->getTextureData(NTextureData::Usage::Normal);
if (textureData) if (textureData)
{ {
auto tex = Director::getInstance()->getTextureCache()->addImage(textureData->filename); auto tex = _director->getTextureCache()->addImage(textureData->filename);
if(tex) if(tex)
{ {
Texture2D::TexParams texParams; Texture2D::TexParams texParams;
@ -566,7 +566,7 @@ void Sprite3D::createNode(NodeData* nodedata, Node* root, const MaterialDatas& m
textureData = materialData->getTextureData(NTextureData::Usage::Normal); textureData = materialData->getTextureData(NTextureData::Usage::Normal);
if (textureData) if (textureData)
{ {
auto tex = Director::getInstance()->getTextureCache()->addImage(textureData->filename); auto tex = _director->getTextureCache()->addImage(textureData->filename);
if (tex) if (tex)
{ {
Texture2D::TexParams texParams; Texture2D::TexParams texParams;
@ -659,7 +659,7 @@ void Sprite3D::addMesh(Mesh* mesh)
void Sprite3D::setTexture(const std::string& texFile) void Sprite3D::setTexture(const std::string& texFile)
{ {
auto tex = Director::getInstance()->getTextureCache()->addImage(texFile); auto tex = _director->getTextureCache()->addImage(texFile);
setTexture(tex); setTexture(tex);
} }
@ -720,9 +720,8 @@ void Sprite3D::visit(cocos2d::Renderer *renderer, const cocos2d::Mat4 &parentTra
flags |= FLAGS_RENDER_AS_3D; flags |= FLAGS_RENDER_AS_3D;
// //
Director* director = Director::getInstance(); _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
bool visibleByCamera = isVisitableByVisitingCamera(); bool visibleByCamera = isVisitableByVisitingCamera();
@ -753,7 +752,7 @@ void Sprite3D::visit(cocos2d::Renderer *renderer, const cocos2d::Mat4 &parentTra
this->draw(renderer, _modelViewTransform, flags); this->draw(renderer, _modelViewTransform, flags);
} }
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); _director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
} }
void Sprite3D::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) void Sprite3D::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)

View File

@ -131,7 +131,7 @@ void Terrain::draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &transform,
_quadRoot->preCalculateAABB(_terrainModelMatrix); _quadRoot->preCalculateAABB(_terrainModelMatrix);
} }
auto &projectionMatrix = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); auto &projectionMatrix = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
auto finalMatrix = projectionMatrix * transform; auto finalMatrix = projectionMatrix * transform;
_programState->setUniform(_mvpMatrixLocation, &finalMatrix.m, sizeof(finalMatrix.m)); _programState->setUniform(_mvpMatrixLocation, &finalMatrix.m, sizeof(finalMatrix.m));
@ -267,7 +267,7 @@ Terrain::Terrain()
reload(); reload();
} }
); );
Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(_backToForegroundListener, 1); _director->getEventDispatcher()->addEventListenerWithFixedPriority(_backToForegroundListener, 1);
#endif #endif
#ifdef CC_USE_METAL #ifdef CC_USE_METAL
auto image = new (std::nothrow)Image(); auto image = new (std::nothrow)Image();
@ -486,7 +486,7 @@ Terrain::~Terrain()
} }
#if CC_ENABLE_CACHE_TEXTURE_DATA #if CC_ENABLE_CACHE_TEXTURE_DATA
Director::getInstance()->getEventDispatcher()->removeEventListener(_backToForegroundListener); _director->getEventDispatcher()->removeEventListener(_backToForegroundListener);
#endif #endif
} }

View File

@ -65,8 +65,8 @@ if(NOT DEFINED ENGINEX_CORE_LIB)
set(ENGINEX_CORE_LIB cocos2d CACHE INTERNAL "The engine-x core lib name" ) set(ENGINEX_CORE_LIB cocos2d CACHE INTERNAL "The engine-x core lib name" )
endif() endif()
if (NOT DEFINED CC_FORCE_USE_GLES) if (NOT DEFINED CC_COMPAT_GL)
set(CC_FORCE_USE_GLES FALSE CACHE INTERNAL "Force use GLES" ) set(CC_COMPAT_GL FALSE CACHE INTERNAL "Enabling CC_COMPAT_GL" )
endif() endif()
project(cocos2d_libs) project(cocos2d_libs)
@ -151,7 +151,7 @@ set_target_properties(${ENGINEX_CORE_LIB}
PROPERTIES PROPERTIES
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
VERSION "${ENGINEX_VERSION}" VERSION "${ENGINEX_VERSION}"
FOLDER "Internal" FOLDER "Internal"
) )

View File

@ -32,6 +32,7 @@ THE SOFTWARE.
#include <unordered_map> #include <unordered_map>
#include "mio/mio.hpp" #include "mio/mio.hpp"
#include "yasio/cxx17/string_view.hpp"
/** /**
* @addtogroup base * @addtogroup base
@ -246,7 +247,7 @@ public:
** key: 16bytes key ** key: 16bytes key
** iv: 16bytes iv ** iv: 16bytes iv
*/ */
virtual void setEncryptEnabled(bool enabled, const std::string& key, const std::string& iv); virtual void setEncryptEnabled(bool enabled, cxx17::string_view key, cxx17::string_view iv);
/* /*
* Mark encrypt function as virtual, default use AES cfb128 encrypt/decrypt * Mark encrypt function as virtual, default use AES cfb128 encrypt/decrypt

View File

@ -251,17 +251,17 @@ THE SOFTWARE.
#endif #endif
/** Use physics integration API. */ /** Use physics integration API. */
// It works with:
// Chipmunk2D or Box2D
#ifndef CC_USE_PHYSICS #ifndef CC_USE_PHYSICS
#define CC_USE_PHYSICS 1 #define CC_USE_PHYSICS 1
#endif #endif
#if (CC_USE_PHYSICS) #if (CC_USE_PHYSICS)
/** Use chipmunk physics 2d engine. */ /** Use Chipmunk2D physics 2d engine on physics integration API. */
#ifndef CC_ENABLE_CHIPMUNK_INTEGRATION #ifndef CC_ENABLE_CHIPMUNK_INTEGRATION
#define CC_ENABLE_CHIPMUNK_INTEGRATION 0 #define CC_ENABLE_CHIPMUNK_INTEGRATION 0
#endif #endif
/** or use Box2D physics 2d engine on physics integration API. */
/** or use box2d physics 2d engine. */
#ifndef CC_ENABLE_BOX2D_INTEGRATION #ifndef CC_ENABLE_BOX2D_INTEGRATION
#define CC_ENABLE_BOX2D_INTEGRATION 1 #define CC_ENABLE_BOX2D_INTEGRATION 1
#endif #endif

View File

@ -657,6 +657,7 @@ using TextureUsage = backend::TextureUsage;
using PixelFormat = backend::PixelFormat; using PixelFormat = backend::PixelFormat;
using TargetBufferFlags = backend::TargetBufferFlags; using TargetBufferFlags = backend::TargetBufferFlags;
using DepthStencilFlags = backend::DepthStencilFlags;
using RenderTargetFlag = backend::RenderTargetFlag; using RenderTargetFlag = backend::RenderTargetFlag;
using ClearFlag = backend::ClearFlag; using ClearFlag = backend::ClearFlag;

View File

@ -87,7 +87,12 @@ void captureScreen(std::function<void(RefPtr<Image>)> imageCallback)
auto renderer = director->getRenderer(); auto renderer = director->getRenderer();
auto eventDispatcher = director->getEventDispatcher(); auto eventDispatcher = director->getEventDispatcher();
// !!!Metal: needs setFrameBufferOnly before draw
#if defined(CC_USE_METAL)
s_captureScreenListener = eventDispatcher->addCustomEventListener(Director::EVENT_BEFORE_DRAW, [=](EventCustom* /*event*/) {
#else
s_captureScreenListener = eventDispatcher->addCustomEventListener(Director::EVENT_AFTER_DRAW, [=](EventCustom* /*event*/) { s_captureScreenListener = eventDispatcher->addCustomEventListener(Director::EVENT_AFTER_DRAW, [=](EventCustom* /*event*/) {
#endif
eventDispatcher->removeEventListener(s_captureScreenListener); eventDispatcher->removeEventListener(s_captureScreenListener);
s_captureScreenListener = nullptr; s_captureScreenListener = nullptr;
// !!!GL: AFTER_DRAW and BEFORE_END_FRAME // !!!GL: AFTER_DRAW and BEFORE_END_FRAME

View File

@ -38,6 +38,7 @@
#include "platform/CCFileStream.h" #include "platform/CCFileStream.h"
#include "md5/md5.h" #include "md5/md5.h"
#include "yasio/xxsocket.hpp" #include "yasio/xxsocket.hpp"
#include <inttypes.h>
// **NOTE** // **NOTE**
// In the file: // In the file:
@ -366,11 +367,16 @@ namespace cocos2d { namespace network {
void run() void run()
{ {
lock_guard<mutex> lock(_threadMutex); lock_guard<mutex> lock(_threadMutex);
if (!_thread.joinable())
{ if (_tasksFinished)
std::thread newThread(&DownloaderCURL::Impl::_threadProc, this); { // all tasks finished, make sure thread not joinable
_thread.swap(newThread); if (_thread.joinable())
_thread.join();
_tasksFinished = false;
} }
if (!_thread.joinable())
_thread = std::thread(&DownloaderCURL::Impl::_threadProc, this);
} }
void stop() void stop()
@ -391,12 +397,6 @@ namespace cocos2d { namespace network {
_thread.join(); _thread.join();
} }
bool stoped()
{
lock_guard<mutex> lock(_threadMutex);
return !_thread.joinable();
}
void getProcessTasks(vector<TaskWrapper>& outList) void getProcessTasks(vector<TaskWrapper>& outList)
{ {
lock_guard<mutex> lock(_processMutex); lock_guard<mutex> lock(_processMutex);
@ -480,7 +480,7 @@ namespace cocos2d { namespace network {
if (coTask->_acceptRanges && coTask->_totalBytesReceived > 0) if (coTask->_acceptRanges && coTask->_totalBytesReceived > 0)
{ {
char buf[128]; char buf[128];
sprintf(buf, "%lld-", coTask->_totalBytesReceived); sprintf(buf, "%" PRId64 "-", coTask->_totalBytesReceived);
curl_easy_setopt(handle, CURLOPT_RANGE, buf); curl_easy_setopt(handle, CURLOPT_RANGE, buf);
curl_easy_setopt(handle, CURLOPT_RESUME_FROM_LARGE,(curl_off_t)coTask->_totalBytesReceived); curl_easy_setopt(handle, CURLOPT_RESUME_FROM_LARGE,(curl_off_t)coTask->_totalBytesReceived);
} }
@ -807,11 +807,14 @@ namespace cocos2d { namespace network {
} }
} while (!coTaskMap.empty()); } while (!coTaskMap.empty());
_tasksFinished = true;
curl_multi_cleanup(curlmHandle); curl_multi_cleanup(curlmHandle);
DLLOG("----DownloaderCURL::Impl::_threadProc end"); DLLOG("----DownloaderCURL::Impl::_threadProc end");
} }
thread _thread; thread _thread;
std::atomic_bool _tasksFinished{};
deque<TaskWrapper> _requestQueue; deque<TaskWrapper> _requestQueue;
set<TaskWrapper> _processSet; set<TaskWrapper> _processSet;
// deque<TaskWrapper> _finishedQueue; // deque<TaskWrapper> _finishedQueue;

View File

@ -32,7 +32,7 @@ THE SOFTWARE.
#include "base/CCConsole.h" #include "base/CCConsole.h"
// #define CC_DOWNLOADER_DEBUG // #define CC_DOWNLOADER_DEBUG
#ifdef CC_DOWNLOADER_DEBUG #if defined(CC_DOWNLOADER_DEBUG) || defined(_DEBUG)
#define DLLOG(format, ...) cocos2d::log(format, ##__VA_ARGS__) #define DLLOG(format, ...) cocos2d::log(format, ##__VA_ARGS__)
#else #else
#define DLLOG(...) do {} while (0) #define DLLOG(...) do {} while (0)

View File

@ -36,9 +36,15 @@ THE SOFTWARE.
#include "platform/win32/CCGL-win32.h" #include "platform/win32/CCGL-win32.h"
#elif CC_TARGET_PLATFORM == CC_PLATFORM_LINUX #elif CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
#include "platform/linux/CCGL-linux.h" #include "platform/linux/CCGL-linux.h"
#elif CC_TARGET_PLATFORM == CC_PLATFORM_IOS && !defined(CC_USE_METAL) #elif CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#if CC_COMPAT_GL
#include "platform/ios/CCGL-ios.h" #include "platform/ios/CCGL-ios.h"
#endif #endif
#elif CC_TARGET_PLATFORM == CC_PLATFORM_MAC
#if CC_COMPAT_GL
#include "platform/mac/CCGL-mac.h"
#endif
#endif
/// @endcond /// @endcond
#endif /* __PLATFORM_CCPLATFORMDEFINE_H__*/ #endif /* __PLATFORM_CCPLATFORMDEFINE_H__*/

View File

@ -104,11 +104,13 @@ THE SOFTWARE.
#endif // CC_PLATFORM_WIN32 #endif // CC_PLATFORM_WIN32
/* /*
* Windows: https://github.com/google/angle windows: https://github.com/google/angle
* iOS: Use Apple GLES mac: GL
iOS: GLES
other: GL
*/ */
#ifndef CC_FORCE_USE_GLES #ifndef CC_COMPAT_GL
#define CC_FORCE_USE_GLES 0 #define CC_COMPAT_GL 0
#endif #endif
#if ((CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)) #if ((CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS))
@ -118,21 +120,27 @@ THE SOFTWARE.
#endif #endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
#if !CC_COMPAT_GL
#define CC_USE_METAL #define CC_USE_METAL
#else
#define CC_USE_GL
#endif
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) #elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#if !CC_FORCE_USE_GLES #if !CC_COMPAT_GL
#define CC_USE_METAL #define CC_USE_METAL
#else #else
#define CC_USE_GLES #define CC_USE_GLES
#endif #endif
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#define CC_USE_GLES #define CC_USE_GLES
#else #elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#if !CC_FORCE_USE_GLES #if !CC_COMPAT_GL
#define CC_USE_GL #define CC_USE_GL
#else #else
#define CC_USE_GLES #define CC_USE_GLES
#endif #endif
#else
#define CC_USE_GL
#endif #endif
/// @endcond /// @endcond

View File

@ -1,5 +1,3 @@
cmake_minimum_required(VERSION 3.6)
# need to whole-archive this lib # need to whole-archive this lib
set(target_name cpp_android_spec) set(target_name cpp_android_spec)

View File

@ -218,9 +218,9 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
this.mHandler.sendMessage(msg); this.mHandler.sendMessage(msg);
} }
@Override @Deprecated
public void runOnGLThread(final Runnable pRunnable) { public void runOnGLThread(final Runnable runnable) {
this.mGLSurfaceView.queueEvent(pRunnable); Cocos2dxHelper.runOnGLThread(runnable);
} }
@Override @Override

View File

@ -130,7 +130,7 @@ public class Cocos2dxEditBoxHelper {
public void afterTextChanged(final Editable s) { public void afterTextChanged(final Editable s) {
if (!editBox.getChangedTextProgrammatically()) { if (!editBox.getChangedTextProgrammatically()) {
if ((Boolean) editBox.getTag()) { if ((Boolean) editBox.getTag()) {
mCocos2dxActivity.runOnGLThread(new Runnable() { Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override @Override
public void run() { public void run() {
Cocos2dxEditBoxHelper.__editBoxEditingChanged(index, s.toString()); Cocos2dxEditBoxHelper.__editBoxEditingChanged(index, s.toString());
@ -152,7 +152,7 @@ public class Cocos2dxEditBoxHelper {
editBox.setTag(true); editBox.setTag(true);
editBox.setChangedTextProgrammatically(false); editBox.setChangedTextProgrammatically(false);
if (hasFocus) { if (hasFocus) {
mCocos2dxActivity.runOnGLThread(new Runnable() { Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override @Override
public void run() { public void run() {
editBox.endAction = Cocos2dxEditBox.kEndActionUnknown; editBox.endAction = Cocos2dxEditBox.kEndActionUnknown;
@ -168,7 +168,7 @@ public class Cocos2dxEditBoxHelper {
// Note that we must to copy a string to prevent string content is modified // Note that we must to copy a string to prevent string content is modified
// on UI thread while 's.toString' is invoked at the same time. // on UI thread while 's.toString' is invoked at the same time.
final String text = new String(editBox.getText().toString()); final String text = new String(editBox.getText().toString());
mCocos2dxActivity.runOnGLThread(new Runnable() { Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override @Override
public void run() { public void run() {
int action = editBox.endAction; int action = editBox.endAction;

View File

@ -111,7 +111,7 @@ public class Cocos2dxHelper {
// =========================================================== // ===========================================================
public static void runOnGLThread(final Runnable r) { public static void runOnGLThread(final Runnable r) {
((Cocos2dxActivity)sActivity).runOnGLThread(r); nativeRunOnGLThread(r);
} }
private static boolean sInited = false; private static boolean sInited = false;
@ -264,6 +264,8 @@ public class Cocos2dxHelper {
// Methods // Methods
// =========================================================== // ===========================================================
private static native void nativeRunOnGLThread(final Object runnable);
private static native void nativeSetEditTextDialogResult(final byte[] pBytes); private static native void nativeSetEditTextDialogResult(final byte[] pBytes);
private static native void nativeSetContext(final Object pContext, final Object pAssetManager); private static native void nativeSetContext(final Object pContext, final Object pAssetManager);
@ -394,7 +396,7 @@ public class Cocos2dxHelper {
try { try {
final byte[] bytesUTF8 = pResult.getBytes("UTF8"); final byte[] bytesUTF8 = pResult.getBytes("UTF8");
Cocos2dxHelper.sCocos2dxHelperListener.runOnGLThread(new Runnable() { Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override @Override
public void run() { public void run() {
Cocos2dxHelper.nativeSetEditTextDialogResult(bytesUTF8); Cocos2dxHelper.nativeSetEditTextDialogResult(bytesUTF8);
@ -608,8 +610,6 @@ public class Cocos2dxHelper {
public static interface Cocos2dxHelperListener { public static interface Cocos2dxHelperListener {
public void showDialog(final String pTitle, final String pMessage); public void showDialog(final String pTitle, final String pMessage);
public void runOnGLThread(final Runnable pRunnable);
} }
//Enhance API modification begin //Enhance API modification begin

View File

@ -33,6 +33,8 @@ import android.webkit.WebView;
import android.webkit.WebViewClient; import android.webkit.WebViewClient;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import org.cocos2dx.lib.Cocos2dxHelper;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.URI; import java.net.URI;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
@ -109,7 +111,7 @@ public class Cocos2dxWebView extends WebView {
try { try {
URI uri = URI.create(urlString); URI uri = URI.create(urlString);
if (uri != null && uri.getScheme().equals(mJSScheme)) { if (uri != null && uri.getScheme().equals(mJSScheme)) {
activity.runOnGLThread(new Runnable() { Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override @Override
public void run() { public void run() {
Cocos2dxWebViewHelper._onJsCallback(mViewTag, urlString); Cocos2dxWebViewHelper._onJsCallback(mViewTag, urlString);
@ -125,7 +127,7 @@ public class Cocos2dxWebView extends WebView {
CountDownLatch latch = new CountDownLatch(1); CountDownLatch latch = new CountDownLatch(1);
// run worker on cocos thread // run worker on cocos thread
activity.runOnGLThread(new ShouldStartLoadingWorker(latch, result, mViewTag, urlString)); Cocos2dxHelper.runOnGLThread(new ShouldStartLoadingWorker(latch, result, mViewTag, urlString));
// wait for result from cocos thread // wait for result from cocos thread
try { try {
@ -140,8 +142,7 @@ public class Cocos2dxWebView extends WebView {
@Override @Override
public void onPageFinished(WebView view, final String url) { public void onPageFinished(WebView view, final String url) {
super.onPageFinished(view, url); super.onPageFinished(view, url);
Cocos2dxActivity activity = (Cocos2dxActivity)getContext(); Cocos2dxHelper.runOnGLThread(new Runnable() {
activity.runOnGLThread(new Runnable() {
@Override @Override
public void run() { public void run() {
Cocos2dxWebViewHelper._didFinishLoading(mViewTag, url); Cocos2dxWebViewHelper._didFinishLoading(mViewTag, url);
@ -153,7 +154,7 @@ public class Cocos2dxWebView extends WebView {
public void onReceivedError(WebView view, int errorCode, String description, final String failingUrl) { public void onReceivedError(WebView view, int errorCode, String description, final String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl); super.onReceivedError(view, errorCode, description, failingUrl);
Cocos2dxActivity activity = (Cocos2dxActivity)getContext(); Cocos2dxActivity activity = (Cocos2dxActivity)getContext();
activity.runOnGLThread(new Runnable() { Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override @Override
public void run() { public void run() {
Cocos2dxWebViewHelper._didFailLoading(mViewTag, failingUrl); Cocos2dxWebViewHelper._didFailLoading(mViewTag, failingUrl);

View File

@ -82,6 +82,23 @@ extern "C" {
} }
} }
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeRunOnGLThread(JNIEnv* env, jclass, jobject runnable) {
using jobject_type = std::remove_pointer_t<jobject>;
struct jobject_delete {
void operator()(jobject_type* __ptr) const _NOEXCEPT {
JniHelper::getEnv()->DeleteGlobalRef(__ptr);
}
};
cocos2d::Director::getInstance()->getScheduler()->performFunctionInCocosThread([wrap = std::make_shared<std::unique_ptr<jobject_type, jobject_delete>>(env->NewGlobalRef(runnable))]{
auto curEnv = JniHelper::getEnv();
JniMethodInfo mi;
if(JniHelper::getMethodInfo(mi, "java/lang/Runnable", "run", "()V")){
curEnv->CallVoidMethod(wrap.get()->get(), mi.methodID);
}
});
}
} }
const char * getApkPath() { const char * getApkPath() {

View File

@ -0,0 +1,113 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __PLATFORM_MAC_CCGL_H__
#define __PLATFORM_MAC_CCGL_H__
#include "platform/CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_MAC
#import <OpenGL/gl.h>
#import <OpenGL/glu.h>
#import <OpenGL/glext.h>
#define CC_GL_DEPTH24_STENCIL8 -1
#define glDeleteVertexArrays glDeleteVertexArraysAPPLE
#define glGenVertexArrays glGenVertexArraysAPPLE
#define glBindVertexArray glBindVertexArrayAPPLE
#define glClearDepthf glClearDepth
#define glDepthRangef glDepthRange
#define glReleaseShaderCompiler(xxx)
// GLES macros, only for compiling compatible
#if !defined(GL_ETC1_RGB8_OES)
#define GL_ETC1_RGB8_OES 0x8D64
#endif
#if !defined(GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG)
#define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00
#define GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01
#define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02
#define GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03
#define GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG 0x9137
#define GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG 0x9138
#define GL_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT 0x8A54
#define GL_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT 0x8A55
#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT 0x8A56
#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT 0x8A57
#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV2_IMG 0x93F0
#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV2_IMG 0x93F1
#endif
#if !defined(GL_COMPRESSED_RGB8_ETC2)
#define GL_COMPRESSED_RGB8_ETC2 0x9274
#define GL_COMPRESSED_SRGB8_ETC2 0x9275
#define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278
#define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279
#endif
#if !defined(GL_ATC_RGB_AMD)
#define GL_ATC_RGB_AMD 0x8C92
#define GL_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93
#define GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE
#endif
#if !defined(GL_COMPRESSED_RGBA_ASTC_4x4_KHR)
#define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93B0
#define GL_COMPRESSED_RGBA_ASTC_5x4_KHR 0x93B1
#define GL_COMPRESSED_RGBA_ASTC_5x5_KHR 0x93B2
#define GL_COMPRESSED_RGBA_ASTC_6x5_KHR 0x93B3
#define GL_COMPRESSED_RGBA_ASTC_6x6_KHR 0x93B4
#define GL_COMPRESSED_RGBA_ASTC_8x5_KHR 0x93B5
#define GL_COMPRESSED_RGBA_ASTC_8x6_KHR 0x93B6
#define GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93B7
#define GL_COMPRESSED_RGBA_ASTC_10x5_KHR 0x93B8
#define GL_COMPRESSED_RGBA_ASTC_10x6_KHR 0x93B9
#define GL_COMPRESSED_RGBA_ASTC_10x8_KHR 0x93BA
#define GL_COMPRESSED_RGBA_ASTC_10x10_KHR 0x93BB
#define GL_COMPRESSED_RGBA_ASTC_12x10_KHR 0x93BC
#define GL_COMPRESSED_RGBA_ASTC_12x12_KHR 0x93BD
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR 0x93D1
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR 0x93D2
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR 0x93D3
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR 0x93D4
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR 0x93D5
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR 0x93D6
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR 0x93D7
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR 0x93D8
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR 0x93D9
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR 0x93DA
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR 0x93DB
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR 0x93DC
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR 0x93DD
#endif
#endif // __PLATFORM_MAC_CCGL_H__
#endif //s CC_TARGET_PLATFORM == CC_PLATFORM_MAC

View File

@ -379,8 +379,10 @@ bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float fram
glfwWindowHint(GLFW_SAMPLES, _glContextAttrs.multisamplingCount); glfwWindowHint(GLFW_SAMPLES, _glContextAttrs.multisamplingCount);
#if defined(CC_USE_METAL)
// Don't create gl context. // Don't create gl context.
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
#endif
int neededWidth = rect.size.width * _frameZoomFactor; int neededWidth = rect.size.width * _frameZoomFactor;
int neededHeight = rect.size.height * _frameZoomFactor; int neededHeight = rect.size.height * _frameZoomFactor;
@ -408,6 +410,7 @@ bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float fram
size.width = static_cast<CGFloat>(fbWidth); size.width = static_cast<CGFloat>(fbWidth);
size.height = static_cast<CGFloat>(fbHeight); size.height = static_cast<CGFloat>(fbHeight);
#if defined(CC_USE_METAL)
// Initialize device. // Initialize device.
id<MTLDevice> device = MTLCreateSystemDefaultDevice(); id<MTLDevice> device = MTLCreateSystemDefaultDevice();
if (!device) if (!device)
@ -425,6 +428,7 @@ bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float fram
[layer setDrawableSize:size]; [layer setDrawableSize:size];
[contentView setLayer:layer]; [contentView setLayer:layer];
backend::DeviceMTL::setCAMetalLayer(layer); backend::DeviceMTL::setCAMetalLayer(layer);
#endif
/* /*
* Note that the created window and context may differ from what you requested, * Note that the created window and context may differ from what you requested,
@ -447,6 +451,10 @@ bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float fram
rect.size.height = realH / _frameZoomFactor; rect.size.height = realH / _frameZoomFactor;
} }
#if defined(CC_USE_GL)
glfwMakeContextCurrent(_mainWindow);
#endif
glfwSetMouseButtonCallback(_mainWindow, GLFWEventHandler::onGLFWMouseCallBack); glfwSetMouseButtonCallback(_mainWindow, GLFWEventHandler::onGLFWMouseCallBack);
glfwSetCursorPosCallback(_mainWindow, GLFWEventHandler::onGLFWMouseMoveCallBack); glfwSetCursorPosCallback(_mainWindow, GLFWEventHandler::onGLFWMouseMoveCallBack);
glfwSetScrollCallback(_mainWindow, GLFWEventHandler::onGLFWMouseScrollCallback); glfwSetScrollCallback(_mainWindow, GLFWEventHandler::onGLFWMouseScrollCallback);
@ -507,8 +515,10 @@ void GLViewImpl::end()
void GLViewImpl::swapBuffers() void GLViewImpl::swapBuffers()
{ {
// if(_mainWindow) #if defined(CC_USE_GL)
// glfwSwapBuffers(_mainWindow); if(_mainWindow)
glfwSwapBuffers(_mainWindow);
#endif
} }
bool GLViewImpl::windowShouldClose() bool GLViewImpl::windowShouldClose()
@ -984,10 +994,12 @@ void GLViewImpl::onGLFWWindowSizeCallback(GLFWwindow* /*window*/, int width, int
Director::getInstance()->setViewport(); Director::getInstance()->setViewport();
Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(GLViewImpl::EVENT_WINDOW_RESIZED, nullptr); Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(GLViewImpl::EVENT_WINDOW_RESIZED, nullptr);
#if defined(CC_USE_METAL)
//update metal attachment texture size. //update metal attachment texture size.
int fbWidth, fbHeight; int fbWidth, fbHeight;
glfwGetFramebufferSize(_mainWindow, &fbWidth, &fbHeight); glfwGetFramebufferSize(_mainWindow, &fbWidth, &fbHeight);
backend::UtilsMTL::resizeDefaultAttachmentTexture(fbWidth, fbHeight); backend::UtilsMTL::resizeDefaultAttachmentTexture(fbWidth, fbHeight);
#endif
} }
} }

View File

@ -44,7 +44,7 @@ CustomCommand::~CustomCommand()
CustomCommand::CustomCommand(const CustomCommand& rhs) CustomCommand::CustomCommand(const CustomCommand& rhs)
{ {
this->assign(std::move(rhs)); this->assign(rhs);
} }
CustomCommand::CustomCommand(CustomCommand&& rhs) CustomCommand::CustomCommand(CustomCommand&& rhs)

View File

@ -27,7 +27,7 @@
#include "renderer/backend/DepthStencilState.h" #include "renderer/backend/DepthStencilState.h"
#include "renderer/backend/Texture.h" #include "renderer/backend/Texture.h"
#include "renderer/backend/VertexLayout.h" #include "renderer/backend/VertexLayout.h"
#include "renderer/backend/RenderPassParams.h" #include "renderer/backend/RenderPassDescriptor.h"
#include "renderer/backend/ProgramState.h" #include "renderer/backend/ProgramState.h"
#include <string> #include <string>

View File

@ -198,9 +198,9 @@ void Renderer::init()
auto device = backend::Device::getInstance(); auto device = backend::Device::getInstance();
_commandBuffer = device->newCommandBuffer(); _commandBuffer = device->newCommandBuffer();
// @MTL: the depth stencil flags must same render target and _depthStencilDescriptor // @MTL: the depth stencil flags must same render target and _dsDesc
_depthStencilDescriptor.depthStencilFlags = TargetBufferFlags::DEPTH_AND_STENCIL; _dsDesc.flags = DepthStencilFlags::ALL;
_defaultRT = device->newDefaultRenderTarget(TargetBufferFlags::COLOR | _depthStencilDescriptor.depthStencilFlags); _defaultRT = device->newDefaultRenderTarget(TargetBufferFlags::COLOR | TargetBufferFlags::DEPTH_AND_STENCIL);
_currentRT = _defaultRT; _currentRT = _defaultRT;
_renderPipeline = device->newRenderPipeline(); _renderPipeline = device->newRenderPipeline();
@ -380,9 +380,9 @@ void Renderer::render()
_isRendering = false; _isRendering = false;
} }
void Renderer::beginFrame() bool Renderer::beginFrame()
{ {
_commandBuffer->beginFrame(); return _commandBuffer->beginFrame();
} }
void Renderer::endFrame() void Renderer::endFrame()
@ -419,11 +419,11 @@ void Renderer::setDepthTest(bool value)
{ {
if (value) { if (value) {
_currentRT->addFlag(TargetBufferFlags::DEPTH); _currentRT->addFlag(TargetBufferFlags::DEPTH);
_depthStencilDescriptor.addFlag(TargetBufferFlags::DEPTH); _dsDesc.addFlag(DepthStencilFlags::DEPTH_TEST);
} }
else { else {
_currentRT->removeFlag(TargetBufferFlags::DEPTH); _currentRT->removeFlag(TargetBufferFlags::DEPTH);
_depthStencilDescriptor.removeFlag(TargetBufferFlags::DEPTH); _dsDesc.removeFlag(DepthStencilFlags::DEPTH_TEST);
} }
} }
@ -431,51 +431,54 @@ void Renderer::setStencilTest(bool value)
{ {
if (value) { if (value) {
_currentRT->addFlag(TargetBufferFlags::STENCIL); _currentRT->addFlag(TargetBufferFlags::STENCIL);
_depthStencilDescriptor.addFlag(TargetBufferFlags::STENCIL); _dsDesc.addFlag(DepthStencilFlags::STENCIL_TEST);
} }
else { else {
_currentRT->removeFlag(TargetBufferFlags::STENCIL); _currentRT->removeFlag(TargetBufferFlags::STENCIL);
_depthStencilDescriptor.removeFlag(TargetBufferFlags::STENCIL); _dsDesc.removeFlag(DepthStencilFlags::STENCIL_TEST);
} }
} }
void Renderer::setDepthWrite(bool value) void Renderer::setDepthWrite(bool value)
{ {
_depthStencilDescriptor.depthWriteEnabled = value; if(value)
_dsDesc.addFlag(DepthStencilFlags::DEPTH_WRITE);
else
_dsDesc.removeFlag(DepthStencilFlags::DEPTH_WRITE);
} }
void Renderer::setDepthCompareFunction(backend::CompareFunction func) void Renderer::setDepthCompareFunction(backend::CompareFunction func)
{ {
_depthStencilDescriptor.depthCompareFunction = func; _dsDesc.depthCompareFunction = func;
} }
backend::CompareFunction Renderer::getDepthCompareFunction() const backend::CompareFunction Renderer::getDepthCompareFunction() const
{ {
return _depthStencilDescriptor.depthCompareFunction; return _dsDesc.depthCompareFunction;
} }
bool Renderer::Renderer::getDepthTest() const bool Renderer::Renderer::getDepthTest() const
{ {
return bitmask::any(_depthStencilDescriptor.depthStencilFlags, TargetBufferFlags::DEPTH); return bitmask::any(_dsDesc.flags, DepthStencilFlags::DEPTH_TEST);
} }
bool Renderer::getStencilTest() const bool Renderer::getStencilTest() const
{ {
return bitmask::any(_depthStencilDescriptor.depthStencilFlags, TargetBufferFlags::STENCIL); return bitmask::any(_dsDesc.flags, DepthStencilFlags::STENCIL_TEST);
} }
bool Renderer::getDepthWrite() const bool Renderer::getDepthWrite() const
{ {
return _depthStencilDescriptor.depthWriteEnabled; return bitmask::any(_dsDesc.flags, DepthStencilFlags::DEPTH_WRITE);
} }
void Renderer::setStencilCompareFunction(backend::CompareFunction func, unsigned int ref, unsigned int readMask) void Renderer::setStencilCompareFunction(backend::CompareFunction func, unsigned int ref, unsigned int readMask)
{ {
_depthStencilDescriptor.frontFaceStencil.stencilCompareFunction = func; _dsDesc.frontFaceStencil.stencilCompareFunction = func;
_depthStencilDescriptor.backFaceStencil.stencilCompareFunction = func; _dsDesc.backFaceStencil.stencilCompareFunction = func;
_depthStencilDescriptor.frontFaceStencil.readMask = readMask; _dsDesc.frontFaceStencil.readMask = readMask;
_depthStencilDescriptor.backFaceStencil.readMask = readMask; _dsDesc.backFaceStencil.readMask = readMask;
_stencilRef = ref; _stencilRef = ref;
} }
@ -484,50 +487,50 @@ void Renderer::setStencilOperation(backend::StencilOperation stencilFailureOp,
backend::StencilOperation depthFailureOp, backend::StencilOperation depthFailureOp,
backend::StencilOperation stencilDepthPassOp) backend::StencilOperation stencilDepthPassOp)
{ {
_depthStencilDescriptor.frontFaceStencil.stencilFailureOperation = stencilFailureOp; _dsDesc.frontFaceStencil.stencilFailureOperation = stencilFailureOp;
_depthStencilDescriptor.backFaceStencil.stencilFailureOperation = stencilFailureOp; _dsDesc.backFaceStencil.stencilFailureOperation = stencilFailureOp;
_depthStencilDescriptor.frontFaceStencil.depthFailureOperation = depthFailureOp; _dsDesc.frontFaceStencil.depthFailureOperation = depthFailureOp;
_depthStencilDescriptor.backFaceStencil.depthFailureOperation = depthFailureOp; _dsDesc.backFaceStencil.depthFailureOperation = depthFailureOp;
_depthStencilDescriptor.frontFaceStencil.depthStencilPassOperation = stencilDepthPassOp; _dsDesc.frontFaceStencil.depthStencilPassOperation = stencilDepthPassOp;
_depthStencilDescriptor.backFaceStencil.depthStencilPassOperation = stencilDepthPassOp; _dsDesc.backFaceStencil.depthStencilPassOperation = stencilDepthPassOp;
} }
void Renderer::setStencilWriteMask(unsigned int mask) void Renderer::setStencilWriteMask(unsigned int mask)
{ {
_depthStencilDescriptor.frontFaceStencil.writeMask = mask; _dsDesc.frontFaceStencil.writeMask = mask;
_depthStencilDescriptor.backFaceStencil.writeMask = mask; _dsDesc.backFaceStencil.writeMask = mask;
} }
backend::StencilOperation Renderer::getStencilFailureOperation() const backend::StencilOperation Renderer::getStencilFailureOperation() const
{ {
return _depthStencilDescriptor.frontFaceStencil.stencilFailureOperation; return _dsDesc.frontFaceStencil.stencilFailureOperation;
} }
backend::StencilOperation Renderer::getStencilPassDepthFailureOperation() const backend::StencilOperation Renderer::getStencilPassDepthFailureOperation() const
{ {
return _depthStencilDescriptor.frontFaceStencil.depthFailureOperation; return _dsDesc.frontFaceStencil.depthFailureOperation;
} }
backend::StencilOperation Renderer::getStencilDepthPassOperation() const backend::StencilOperation Renderer::getStencilDepthPassOperation() const
{ {
return _depthStencilDescriptor.frontFaceStencil.depthStencilPassOperation; return _dsDesc.frontFaceStencil.depthStencilPassOperation;
} }
backend::CompareFunction Renderer::getStencilCompareFunction() const backend::CompareFunction Renderer::getStencilCompareFunction() const
{ {
return _depthStencilDescriptor.depthCompareFunction; return _dsDesc.depthCompareFunction;
} }
unsigned int Renderer::getStencilReadMask() const unsigned int Renderer::getStencilReadMask() const
{ {
return _depthStencilDescriptor.frontFaceStencil.readMask; return _dsDesc.frontFaceStencil.readMask;
} }
unsigned int Renderer::getStencilWriteMask() const unsigned int Renderer::getStencilWriteMask() const
{ {
return _depthStencilDescriptor.frontFaceStencil.writeMask; return _dsDesc.frontFaceStencil.writeMask;
} }
unsigned int Renderer::getStencilReferenceValue() const unsigned int Renderer::getStencilReferenceValue() const
@ -535,6 +538,16 @@ unsigned int Renderer::getStencilReferenceValue() const
return _stencilRef; return _stencilRef;
} }
void Renderer::setDepthStencilDesc(const backend::DepthStencilDescriptor& dsDesc)
{
_dsDesc = dsDesc;
}
const backend::DepthStencilDescriptor& Renderer::getDepthStencilDesc() const
{
return _dsDesc;
}
void Renderer::setViewPort(int x, int y, unsigned int w, unsigned int h) void Renderer::setViewPort(int x, int y, unsigned int w, unsigned int h)
{ {
_viewport.x = x; _viewport.x = x;
@ -644,13 +657,13 @@ void Renderer::drawBatchedTriangles()
/************** 2: Draw *************/ /************** 2: Draw *************/
beginRenderPass(); beginRenderPass();
for (int i = 0; i < batchesTotal; ++i)
{
auto& drawInfo = _triBatchesToDraw[i];
_commandBuffer->updatePipelineState(_currentRT, drawInfo.cmd->getPipelineDescriptor());
_commandBuffer->setVertexBuffer(_vertexBuffer); _commandBuffer->setVertexBuffer(_vertexBuffer);
_commandBuffer->setIndexBuffer(_indexBuffer); _commandBuffer->setIndexBuffer(_indexBuffer);
for (int i = 0; i < batchesTotal; ++i)
{
auto& drawInfo = _triBatchesToDraw[i];
_commandBuffer->updatePipelineState(_currentRT, drawInfo.cmd->getPipelineDescriptor());
auto& pipelineDescriptor = drawInfo.cmd->getPipelineDescriptor(); auto& pipelineDescriptor = drawInfo.cmd->getPipelineDescriptor();
_commandBuffer->setProgramState(pipelineDescriptor.programState); _commandBuffer->setProgramState(pipelineDescriptor.programState);
_commandBuffer->drawElements(backend::PrimitiveType::TRIANGLE, _commandBuffer->drawElements(backend::PrimitiveType::TRIANGLE,
@ -661,8 +674,8 @@ void Renderer::drawBatchedTriangles()
_drawnBatches++; _drawnBatches++;
_drawnVertices += _triBatchesToDraw[i].indicesToDraw; _drawnVertices += _triBatchesToDraw[i].indicesToDraw;
} }
_commandBuffer->endRenderPass(); _commandBuffer->endRenderPass();
@ -682,8 +695,9 @@ void Renderer::drawCustomCommand(RenderCommand *command)
if (cmd->getBeforeCallback()) cmd->getBeforeCallback()(); if (cmd->getBeforeCallback()) cmd->getBeforeCallback()();
beginRenderPass(); beginRenderPass();
_commandBuffer->updatePipelineState(_currentRT, cmd->getPipelineDescriptor());
_commandBuffer->setVertexBuffer(cmd->getVertexBuffer()); _commandBuffer->setVertexBuffer(cmd->getVertexBuffer());
_commandBuffer->updatePipelineState(_currentRT, cmd->getPipelineDescriptor());
_commandBuffer->setProgramState(cmd->getPipelineDescriptor().programState); _commandBuffer->setProgramState(cmd->getPipelineDescriptor().programState);
auto drawType = cmd->getDrawType(); auto drawType = cmd->getDrawType();
@ -782,13 +796,15 @@ void Renderer::readPixels(backend::RenderTarget* rt, std::function<void(const ba
void Renderer::beginRenderPass() void Renderer::beginRenderPass()
{ {
_commandBuffer->beginRenderPass(_currentRT, _renderPassParams); _commandBuffer->beginRenderPass(_currentRT, _renderPassDesc);
_commandBuffer->updateDepthStencilState(_dsDesc);
_commandBuffer->setStencilReferenceValue(_stencilRef);
_commandBuffer->setViewport(_viewport.x, _viewport.y, _viewport.w, _viewport.h); _commandBuffer->setViewport(_viewport.x, _viewport.y, _viewport.w, _viewport.h);
_commandBuffer->setCullMode(_cullMode); _commandBuffer->setCullMode(_cullMode);
_commandBuffer->setWinding(_winding); _commandBuffer->setWinding(_winding);
_commandBuffer->setScissorRect(_scissorState.isEnabled, _scissorState.rect.x, _scissorState.rect.y, _scissorState.rect.width, _scissorState.rect.height); _commandBuffer->setScissorRect(_scissorState.isEnabled, _scissorState.rect.x, _scissorState.rect.y, _scissorState.rect.width, _scissorState.rect.height);
_commandBuffer->setStencilReferenceValue(_stencilRef);
_commandBuffer->updateDepthStencilState(_depthStencilDescriptor);
} }
void Renderer::clear(ClearFlag flags, const Color4F& color, float depth, unsigned int stencil, float globalOrder) void Renderer::clear(ClearFlag flags, const Color4F& color, float depth, unsigned int stencil, float globalOrder)
@ -798,7 +814,7 @@ void Renderer::clear(ClearFlag flags, const Color4F& color, float depth, unsigne
CallbackCommand* command = nextClearCommand(); CallbackCommand* command = nextClearCommand();
command->init(globalOrder); command->init(globalOrder);
command->func = [=]() -> void { command->func = [=]() -> void {
backend::RenderPassParams descriptor; backend::RenderPassDescriptor descriptor;
descriptor.flags.clear = flags; descriptor.flags.clear = flags;
if (bitmask::any(flags, ClearFlag::COLOR)) { if (bitmask::any(flags, ClearFlag::COLOR)) {
@ -839,12 +855,12 @@ const Color4F& Renderer::getClearColor() const
float Renderer::getClearDepth() const float Renderer::getClearDepth() const
{ {
return _renderPassParams.clearDepthValue; return _renderPassDesc.clearDepthValue;
} }
unsigned int Renderer::getClearStencil() const unsigned int Renderer::getClearStencil() const
{ {
return _renderPassParams.clearStencilValue; return _renderPassDesc.clearStencilValue;
} }
ClearFlag Renderer::getClearFlag() const ClearFlag Renderer::getClearFlag() const

View File

@ -338,6 +338,16 @@ public:
*/ */
unsigned int getStencilReferenceValue() const; unsigned int getStencilReferenceValue() const;
/**
* Sets depth stencil descriptor
*/
void setDepthStencilDesc(const backend::DepthStencilDescriptor& dsDesc);
/**
* Gets depth stencil descriptor
*/
const backend::DepthStencilDescriptor& getDepthStencilDesc() const;
/** /**
* Fixed-function state * Fixed-function state
* @param mode Controls if primitives are culled when front facing, back facing, or not culled at all. * @param mode Controls if primitives are culled when front facing, back facing, or not culled at all.
@ -442,7 +452,7 @@ protected:
void drawCustomCommand(RenderCommand* command); void drawCustomCommand(RenderCommand* command);
void drawMeshCommand(RenderCommand* command); void drawMeshCommand(RenderCommand* command);
void beginFrame(); /// Indicate the begining of a frame bool beginFrame(); /// Indicate the begining of a frame
void endFrame(); /// Finish a frame. void endFrame(); /// Finish a frame.
///Draw the previews queued triangles and flush previous context ///Draw the previews queued triangles and flush previous context
@ -491,10 +501,10 @@ protected:
TriangleCommandBufferManager _triangleCommandBufferManager; TriangleCommandBufferManager _triangleCommandBufferManager;
backend::CommandBuffer* _commandBuffer = nullptr; backend::CommandBuffer* _commandBuffer = nullptr;
backend::RenderPassParams _renderPassParams; backend::RenderPassDescriptor _renderPassDesc;
backend::DepthStencilState* _depthStencilState = nullptr; backend::DepthStencilState* _depthStencilState = nullptr;
backend::DepthStencilDescriptor _depthStencilDescriptor; backend::DepthStencilDescriptor _dsDesc;
// Internal structure that has the information for the batches // Internal structure that has the information for the batches
struct TriBatchToDraw struct TriBatchToDraw

View File

@ -27,7 +27,7 @@ set(COCOS_RENDERER_HEADER
renderer/backend/Program.h renderer/backend/Program.h
renderer/backend/ProgramCache.h renderer/backend/ProgramCache.h
renderer/backend/Macros.h renderer/backend/Macros.h
renderer/backend/RenderPassParams.h renderer/backend/RenderPassDescriptor.h
renderer/backend/RenderPipeline.h renderer/backend/RenderPipeline.h
renderer/backend/ShaderModule.h renderer/backend/ShaderModule.h
renderer/backend/Texture.h renderer/backend/Texture.h
@ -73,10 +73,10 @@ set(COCOS_RENDERER_SRC
renderer/backend/ProgramState.cpp renderer/backend/ProgramState.cpp
renderer/backend/ProgramStateRegistry.cpp renderer/backend/ProgramStateRegistry.cpp
renderer/backend/ShaderCache.cpp renderer/backend/ShaderCache.cpp
renderer/backend/RenderPassParams.cpp renderer/backend/RenderPassDescriptor.cpp
) )
if(ANDROID OR WINDOWS OR LINUX OR (IOS AND CC_FORCE_USE_GLES)) if(ANDROID OR WINDOWS OR LINUX OR CC_COMPAT_GL)
list(APPEND COCOS_RENDERER_HEADER list(APPEND COCOS_RENDERER_HEADER
renderer/backend/opengl/BufferGL.h renderer/backend/opengl/BufferGL.h

View File

@ -24,7 +24,7 @@
#pragma once #pragma once
#include "renderer/backend/RenderPassParams.h" #include "renderer/backend/RenderPassDescriptor.h"
#include "renderer/backend/RenderPipeline.h" #include "renderer/backend/RenderPipeline.h"
#include "renderer/backend/Device.h" #include "renderer/backend/Device.h"
#include "renderer/backend/Types.h" #include "renderer/backend/Types.h"

View File

@ -31,7 +31,7 @@
#include "Macros.h" #include "Macros.h"
#include "Types.h" #include "Types.h"
#include "RenderPassParams.h" #include "RenderPassDescriptor.h"
#include "PixelBufferDescriptor.h" #include "PixelBufferDescriptor.h"
#include "CCStdC.h" #include "CCStdC.h"
#include "ProgramState.h" #include "ProgramState.h"
@ -81,13 +81,13 @@ public:
/** /**
* @brief Indicate the begining of a frame * @brief Indicate the begining of a frame
*/ */
virtual void beginFrame() = 0; virtual bool beginFrame() = 0;
/** /**
* Begin a render pass, initial color, depth and stencil attachment. * Begin a render pass, initial color, depth and stencil attachment.
* @param descriptor Specifies a group of render targets that hold the results of a render pass. * @param descriptor Specifies a group of render targets that hold the results of a render pass.
*/ */
virtual void beginRenderPass(const RenderTarget* renderTarget, const RenderPassParams& descriptor) = 0; virtual void beginRenderPass(const RenderTarget* renderTarget, const RenderPassDescriptor& descriptor) = 0;
/** /**

View File

@ -23,6 +23,7 @@
****************************************************************************/ ****************************************************************************/
#include "DepthStencilState.h" #include "DepthStencilState.h"
#include "RenderTarget.h"
CC_BACKEND_BEGIN CC_BACKEND_BEGIN
@ -40,13 +41,9 @@ bool StencilDescriptor::operator==(const StencilDescriptor &rhs) const
DepthStencilState::~DepthStencilState() DepthStencilState::~DepthStencilState()
{} {}
bool DepthStencilState::isEnabled() const { void DepthStencilState::update(const DepthStencilDescriptor& dsDesc) {
return bitmask::any(_depthStencilInfo.depthStencilFlags, TargetBufferFlags::DEPTH_AND_STENCIL); _depthStencilInfo = dsDesc;
} _isBackFrontStencilEqual = dsDesc.backFaceStencil == dsDesc.frontFaceStencil;
void DepthStencilState::update(const DepthStencilDescriptor& descriptor) {
_depthStencilInfo = descriptor;
_isBackFrontStencilEqual = descriptor.backFaceStencil == descriptor.frontFaceStencil;
} }
CC_BACKEND_END CC_BACKEND_END

View File

@ -31,6 +31,7 @@
CC_BACKEND_BEGIN CC_BACKEND_BEGIN
class RenderTarget;
/** /**
* @addtogroup _backend * @addtogroup _backend
* @{ * @{
@ -59,11 +60,10 @@ struct DepthStencilDescriptor
CompareFunction depthCompareFunction = CompareFunction::LESS; CompareFunction depthCompareFunction = CompareFunction::LESS;
StencilDescriptor backFaceStencil; StencilDescriptor backFaceStencil;
StencilDescriptor frontFaceStencil; StencilDescriptor frontFaceStencil;
bool depthWriteEnabled = false; void addFlag(DepthStencilFlags flag) { this->flags |= flag; }
TargetBufferFlags depthStencilFlags = {}; void removeFlag(DepthStencilFlags flag) { this->flags &= ~flag; }
// must match current render target
void addFlag(TargetBufferFlags flag) { depthStencilFlags |= flag; } DepthStencilFlags flags = DepthStencilFlags::ALL;
void removeFlag(TargetBufferFlags flag) { depthStencilFlags &= ~flag; }
}; };
/** /**
@ -72,9 +72,9 @@ struct DepthStencilDescriptor
class DepthStencilState : public cocos2d::Ref class DepthStencilState : public cocos2d::Ref
{ {
public: public:
virtual void update(const DepthStencilDescriptor& descriptor); virtual void update(const DepthStencilDescriptor& desc);
const DepthStencilDescriptor& getDepthStencilInfo()const { return _depthStencilInfo; } const DepthStencilDescriptor& getDepthStencilInfo()const { return _depthStencilInfo; }
bool isEnabled() const; bool isEnabled() const { return bitmask::any(_depthStencilInfo.flags, DepthStencilFlags::DEPTH_STENCIL_TEST); }
protected: protected:
/** /**
* @param descriptor Specifies depth and stencil descriptor. * @param descriptor Specifies depth and stencil descriptor.

View File

@ -26,7 +26,7 @@
#include "Macros.h" #include "Macros.h"
#include "Types.h" #include "Types.h"
#include "RenderPassParams.h" #include "RenderPassDescriptor.h"
#include "Texture.h" #include "Texture.h"
#include "DepthStencilState.h" #include "DepthStencilState.h"
#include "ProgramCache.h" #include "ProgramCache.h"

View File

@ -141,13 +141,14 @@ public:
*/ */
virtual const std::unordered_map<std::string, UniformInfo>& getAllActiveUniformInfo(ShaderStage stage) const = 0; virtual const std::unordered_map<std::string, UniformInfo>& getAllActiveUniformInfo(ShaderStage stage) const = 0;
protected:
/** /**
* Set engin built-in program type. * Set engin built-in program type.
* @param type Specifies the program type. * @param type Specifies the program type.
*/ */
void setProgramType(uint32_t type); void setProgramType(uint32_t type);
protected:
/** /**
* @param vs Specifes the vertex shader source. * @param vs Specifes the vertex shader source.
* @param fs Specifes the fragment shader source. * @param fs Specifes the fragment shader source.

View File

@ -22,11 +22,11 @@
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "RenderPassParams.h" #include "RenderPassDescriptor.h"
CC_BACKEND_BEGIN CC_BACKEND_BEGIN
bool RenderPassParams::operator==(const RenderPassParams& descriptor) const bool RenderPassDescriptor::operator==(const RenderPassDescriptor& descriptor) const
{ {
return (clearDepthValue == descriptor.clearDepthValue && return (clearDepthValue == descriptor.clearDepthValue &&
clearStencilValue == descriptor.clearStencilValue && clearStencilValue == descriptor.clearStencilValue &&

View File

@ -62,10 +62,10 @@ struct RenderPassFlags {
/** /**
* Store values about color, depth and stencil attachment. * Store values about color, depth and stencil attachment.
*/ */
struct RenderPassParams struct RenderPassDescriptor
{ {
RenderPassParams& operator=(const RenderPassParams& descriptor) = default; RenderPassDescriptor& operator=(const RenderPassDescriptor& descriptor) = default;
bool operator==(const RenderPassParams& descriptor) const; bool operator==(const RenderPassDescriptor& descriptor) const;
float clearDepthValue = 0.f; float clearDepthValue = 0.f;
float clearStencilValue = 0.f; float clearStencilValue = 0.f;
@ -74,8 +74,6 @@ struct RenderPassParams
// Now, only clear flag used // Now, only clear flag used
RenderPassFlags flags{}; RenderPassFlags flags{};
}; };
typedef RenderPassParams RenderPassParams;
//end of _backend group //end of _backend group
/// @} /// @}
CC_BACKEND_END CC_BACKEND_END

View File

@ -28,7 +28,7 @@
#include "Types.h" #include "Types.h"
#include "base/CCRef.h" #include "base/CCRef.h"
#include "renderer/CCPipelineDescriptor.h" #include "renderer/CCPipelineDescriptor.h"
#include "renderer/backend/RenderPassParams.h" #include "renderer/backend/RenderPassDescriptor.h"
CC_BACKEND_BEGIN CC_BACKEND_BEGIN
/** /**

View File

@ -266,7 +266,6 @@ enum class ColorWriteMask : uint32_t
CC_ENABLE_BITMASK_OPS(ColorWriteMask) CC_ENABLE_BITMASK_OPS(ColorWriteMask)
CC_ENABLE_BITSHIFT_OPS(ColorWriteMask) CC_ENABLE_BITSHIFT_OPS(ColorWriteMask)
/** /**
* Bitmask for selecting render buffers * Bitmask for selecting render buffers
*/ */
@ -293,6 +292,17 @@ inline TargetBufferFlags getMRTColorFlag(size_t index) noexcept {
typedef TargetBufferFlags ClearFlag; typedef TargetBufferFlags ClearFlag;
typedef TargetBufferFlags RenderTargetFlag; typedef TargetBufferFlags RenderTargetFlag;
enum class DepthStencilFlags : unsigned int {
NONE = 0,
DEPTH_TEST = 1,
DEPTH_WRITE = 1 << 1,
STENCIL_TEST = 1 << 2,
DEPTH_STENCIL_TEST = DEPTH_TEST | STENCIL_TEST,
ALL = DEPTH_TEST | STENCIL_TEST | DEPTH_WRITE,
};
CC_ENABLE_BITMASK_OPS(DepthStencilFlags)
CC_ENABLE_BITSHIFT_OPS(DepthStencilFlags)
struct SamplerDescriptor struct SamplerDescriptor
{ {
SamplerFilter magFilter = SamplerFilter::LINEAR; SamplerFilter magFilter = SamplerFilter::LINEAR;

View File

@ -72,14 +72,14 @@ public:
* Then create MTLCommandBuffer and enqueue it to MTLCommandQueue. * Then create MTLCommandBuffer and enqueue it to MTLCommandQueue.
* Then start schedule available MTLBuffer * Then start schedule available MTLBuffer
*/ */
virtual void beginFrame() override; virtual bool beginFrame() override;
/** /**
* Create a MTLRenderCommandEncoder object for graphics rendering to an attachment in a RenderPassParams. * Create a MTLRenderCommandEncoder object for graphics rendering to an attachment in a RenderPassDescriptor.
* MTLRenderCommandEncoder is cached if current RenderPassParams is identical to previous one. * MTLRenderCommandEncoder is cached if current RenderPassDescriptor is identical to previous one.
* @param descriptor Specifies a group of render targets that hold the results of a render pass. * @param descriptor Specifies a group of render targets that hold the results of a render pass.
*/ */
virtual void beginRenderPass(const RenderTarget* renderTarget, const RenderPassParams& descriptor) override; virtual void beginRenderPass(const RenderTarget* renderTarget, const RenderPassDescriptor& descriptor) override;
/** /**
* Update depthStencil status, improvment: for metal backend cache it * Update depthStencil status, improvment: for metal backend cache it
@ -208,7 +208,7 @@ private:
void afterDraw(); void afterDraw();
void flush(); void flush();
void flushCaptureCommands(); void flushCaptureCommands();
id<MTLRenderCommandEncoder> getRenderCommandEncoder(const RenderTarget* renderTarget, const RenderPassParams& renderPassParams); void updateRenderCommandEncoder(const RenderTarget* renderTarget, const RenderPassDescriptor& renderPassParams);
id<MTLCommandBuffer> _mtlCommandBuffer = nil; id<MTLCommandBuffer> _mtlCommandBuffer = nil;
id<MTLCommandQueue> _mtlCommandQueue = nil; id<MTLCommandQueue> _mtlCommandQueue = nil;
@ -225,7 +225,7 @@ private:
dispatch_semaphore_t _frameBoundarySemaphore; dispatch_semaphore_t _frameBoundarySemaphore;
const RenderTarget* _currentRenderTarget = nil; // weak ref const RenderTarget* _currentRenderTarget = nil; // weak ref
RenderPassParams _currentRenderPassParams; RenderPassDescriptor _currentRenderPassDesc;
TargetBufferFlags _currentRenderTargetFlags = TargetBufferFlags::NONE; TargetBufferFlags _currentRenderTargetFlags = TargetBufferFlags::NONE;
NSAutoreleasePool* _autoReleasePool = nil; NSAutoreleasePool* _autoReleasePool = nil;

View File

@ -125,12 +125,12 @@ namespace
} }
} }
static MTLRenderPassDescriptor* toMTLRenderPassDescriptor(const RenderTarget* rt, const RenderPassParams& params) static MTLRenderPassDescriptor* toMTLRenderPassDescriptor(const RenderTarget* rt, const RenderPassDescriptor& desc)
{ {
MTLRenderPassDescriptor* mtlDescritpor = [MTLRenderPassDescriptor renderPassDescriptor]; MTLRenderPassDescriptor* mtlDescritpor = [MTLRenderPassDescriptor renderPassDescriptor];
auto rtMTL = static_cast<const RenderTargetMTL*>(rt); auto rtMTL = static_cast<const RenderTargetMTL*>(rt);
rtMTL->applyRenderPassAttachments(params, mtlDescritpor); rtMTL->applyRenderPassAttachments(desc, mtlDescritpor);
return mtlDescritpor; return mtlDescritpor;
} }
@ -185,7 +185,7 @@ void CommandBufferMTL::setRenderPipeline(RenderPipeline* renderPipeline)
_renderPipelineMTL = static_cast<RenderPipelineMTL*>(renderPipeline); _renderPipelineMTL = static_cast<RenderPipelineMTL*>(renderPipeline);
} }
void CommandBufferMTL::beginFrame() bool CommandBufferMTL::beginFrame()
{ {
_autoReleasePool = [[NSAutoreleasePool alloc] init]; _autoReleasePool = [[NSAutoreleasePool alloc] init];
dispatch_semaphore_wait(_frameBoundarySemaphore, DISPATCH_TIME_FOREVER); dispatch_semaphore_wait(_frameBoundarySemaphore, DISPATCH_TIME_FOREVER);
@ -196,12 +196,13 @@ void CommandBufferMTL::beginFrame()
[_mtlCommandBuffer retain]; [_mtlCommandBuffer retain];
BufferManager::beginFrame(); BufferManager::beginFrame();
return true;
} }
id<MTLRenderCommandEncoder> CommandBufferMTL::getRenderCommandEncoder(const RenderTarget* renderTarget, const RenderPassParams& renderPassParams) void CommandBufferMTL::updateRenderCommandEncoder(const RenderTarget* renderTarget, const RenderPassDescriptor& renderPassDesc)
{ {
if(_mtlRenderEncoder != nil && if(_mtlRenderEncoder != nil &&
_currentRenderPassParams == renderPassParams && _currentRenderPassDesc == renderPassDesc &&
_currentRenderTarget == renderTarget && _currentRenderTarget == renderTarget &&
_currentRenderTargetFlags == renderTarget->getTargetFlags()) _currentRenderTargetFlags == renderTarget->getTargetFlags())
{ {
@ -209,7 +210,7 @@ id<MTLRenderCommandEncoder> CommandBufferMTL::getRenderCommandEncoder(const Rend
} }
_currentRenderTarget = renderTarget; _currentRenderTarget = renderTarget;
_currentRenderPassParams = renderPassParams; _currentRenderPassDesc = renderPassDesc;
_currentRenderTargetFlags = renderTarget->getTargetFlags(); _currentRenderTargetFlags = renderTarget->getTargetFlags();
if(_mtlRenderEncoder != nil) if(_mtlRenderEncoder != nil)
@ -219,22 +220,19 @@ id<MTLRenderCommandEncoder> CommandBufferMTL::getRenderCommandEncoder(const Rend
_mtlRenderEncoder = nil; _mtlRenderEncoder = nil;
} }
auto mtlDescriptor = toMTLRenderPassDescriptor(renderTarget, renderPassParams); auto mtlDescriptor = toMTLRenderPassDescriptor(renderTarget, renderPassDesc);
_renderTargetWidth = (unsigned int)mtlDescriptor.colorAttachments[0].texture.width; _renderTargetWidth = (unsigned int)mtlDescriptor.colorAttachments[0].texture.width;
_renderTargetHeight = (unsigned int)mtlDescriptor.colorAttachments[0].texture.height; _renderTargetHeight = (unsigned int)mtlDescriptor.colorAttachments[0].texture.height;
id<MTLRenderCommandEncoder> mtlRenderEncoder = [_mtlCommandBuffer renderCommandEncoderWithDescriptor:mtlDescriptor]; _mtlRenderEncoder = [_mtlCommandBuffer renderCommandEncoderWithDescriptor:mtlDescriptor];
[mtlRenderEncoder retain]; [_mtlRenderEncoder retain];
return mtlRenderEncoder;
} }
void CommandBufferMTL::beginRenderPass(const RenderTarget* renderTarget, const RenderPassParams& descriptor) void CommandBufferMTL::beginRenderPass(const RenderTarget* renderTarget, const RenderPassDescriptor& renderPassDesc)
{ {
_mtlRenderEncoder = getRenderCommandEncoder(renderTarget, descriptor); updateRenderCommandEncoder(renderTarget, renderPassDesc);
// [_mtlRenderEncoder setFrontFacingWinding:MTLWindingCounterClockwise]; // [_mtlRenderEncoder setFrontFacingWinding:MTLWindingCounterClockwise];
} }
void CommandBufferMTL::updateDepthStencilState(const DepthStencilDescriptor& descriptor) void CommandBufferMTL::updateDepthStencilState(const DepthStencilDescriptor& descriptor)
{ {
_depthStencilStateMTL->update(descriptor); _depthStencilStateMTL->update(descriptor);
@ -315,7 +313,6 @@ void CommandBufferMTL::drawElements(PrimitiveType primitiveType, IndexFormat ind
void CommandBufferMTL::endRenderPass() void CommandBufferMTL::endRenderPass()
{ {
afterDraw(); afterDraw();
} }
void CommandBufferMTL::readPixels(RenderTarget* rt, std::function<void(const PixelBufferDescriptor&)> callback) void CommandBufferMTL::readPixels(RenderTarget* rt, std::function<void(const PixelBufferDescriptor&)> callback)
@ -335,8 +332,9 @@ void CommandBufferMTL::endFrame()
[_mtlRenderEncoder release]; [_mtlRenderEncoder release];
_mtlRenderEncoder = nil; _mtlRenderEncoder = nil;
[_mtlCommandBuffer presentDrawable:DeviceMTL::getCurrentDrawable()]; auto currentDrawable = DeviceMTL::getCurrentDrawable();
_drawableTexture = DeviceMTL::getCurrentDrawable().texture; [_mtlCommandBuffer presentDrawable:currentDrawable];
_drawableTexture = currentDrawable.texture;
[_mtlCommandBuffer addCompletedHandler:^(id<MTLCommandBuffer> commandBuffer) { [_mtlCommandBuffer addCompletedHandler:^(id<MTLCommandBuffer> commandBuffer) {
// GPU work is complete // GPU work is complete
// Signal the semaphore to start the CPU work // Signal the semaphore to start the CPU work

View File

@ -50,9 +50,7 @@ public:
DepthStencilStateMTL(id<MTLDevice> mtlDevice); DepthStencilStateMTL(id<MTLDevice> mtlDevice);
~DepthStencilStateMTL(); ~DepthStencilStateMTL();
uint32_t hashValue() const; void update(const DepthStencilDescriptor& dsDesc) override;
void update(const DepthStencilDescriptor& descriptor) override;
/// @name Setters & Getters /// @name Setters & Getters
/** /**

View File

@ -23,6 +23,7 @@
****************************************************************************/ ****************************************************************************/
#include "DepthStencilStateMTL.h" #include "DepthStencilStateMTL.h"
#include "../RenderTarget.h"
#include "xxhash.h" #include "xxhash.h"
CC_BACKEND_BEGIN CC_BACKEND_BEGIN
@ -106,32 +107,25 @@ namespace
DepthStencilStateMTL::DepthStencilStateMTL(id<MTLDevice> mtlDevice) : _mtlDevice(mtlDevice) DepthStencilStateMTL::DepthStencilStateMTL(id<MTLDevice> mtlDevice) : _mtlDevice(mtlDevice)
{ {
} }
uint32_t DepthStencilStateMTL::hashValue() const void DepthStencilStateMTL::update(const DepthStencilDescriptor& dsDesc)
{ {
DepthStencilDescriptor hashMe; DepthStencilState::update(dsDesc);
memset(&hashMe, 0, sizeof(hashMe));
hashMe.depthCompareFunction = _depthStencilInfo.depthCompareFunction;
hashMe.backFaceStencil = _depthStencilInfo.backFaceStencil;
hashMe.frontFaceStencil = _depthStencilInfo.frontFaceStencil;
hashMe.depthWriteEnabled = _depthStencilInfo.depthWriteEnabled;
hashMe.depthStencilFlags = _depthStencilInfo.depthStencilFlags;
return XXH32((const void*)&hashMe, sizeof(hashMe), 0);
}
void DepthStencilStateMTL::update(const DepthStencilDescriptor& descriptor)
{
DepthStencilState::update(descriptor);
if(!isEnabled()) { if(!isEnabled()) {
_mtlDepthStencilState = nil; _mtlDepthStencilState = nil;
return; return;
} }
auto key = hashValue(); DepthStencilDescriptor hashMe;
memset(&hashMe, 0, sizeof(hashMe));
hashMe.depthCompareFunction = dsDesc.depthCompareFunction;
hashMe.backFaceStencil = dsDesc.backFaceStencil;
hashMe.frontFaceStencil = dsDesc.frontFaceStencil;
hashMe.flags = dsDesc.flags;
auto key = XXH32((const void*)&hashMe, sizeof(hashMe), 0);
auto it = _mtlStateCache.find(key); auto it = _mtlStateCache.find(key);
if(it != _mtlStateCache.end()) { if(it != _mtlStateCache.end()) {
_mtlDepthStencilState = it->second; _mtlDepthStencilState = it->second;
@ -140,17 +134,17 @@ void DepthStencilStateMTL::update(const DepthStencilDescriptor& descriptor)
MTLDepthStencilDescriptor* mtlDescriptor = [[MTLDepthStencilDescriptor alloc] init]; MTLDepthStencilDescriptor* mtlDescriptor = [[MTLDepthStencilDescriptor alloc] init];
if (bitmask::any(descriptor.depthStencilFlags, TargetBufferFlags::DEPTH)) if (bitmask::any(dsDesc.flags, DepthStencilFlags::DEPTH_TEST))
mtlDescriptor.depthCompareFunction = toMTLCompareFunction(descriptor.depthCompareFunction); mtlDescriptor.depthCompareFunction = toMTLCompareFunction(_depthStencilInfo.depthCompareFunction);
else else
mtlDescriptor.depthCompareFunction = MTLCompareFunctionAlways; mtlDescriptor.depthCompareFunction = MTLCompareFunctionAlways;
mtlDescriptor.depthWriteEnabled = descriptor.depthWriteEnabled; mtlDescriptor.depthWriteEnabled = bitmask::any(dsDesc.flags, DepthStencilFlags::DEPTH_WRITE);
if (bitmask::any(descriptor.depthStencilFlags, TargetBufferFlags::STENCIL)) if (bitmask::any(dsDesc.flags, DepthStencilFlags::STENCIL_TEST))
{ {
setMTLStencilDescriptor(mtlDescriptor.frontFaceStencil, descriptor.frontFaceStencil); setMTLStencilDescriptor(mtlDescriptor.frontFaceStencil, _depthStencilInfo.frontFaceStencil);
setMTLStencilDescriptor(mtlDescriptor.backFaceStencil, descriptor.backFaceStencil); setMTLStencilDescriptor(mtlDescriptor.backFaceStencil, _depthStencilInfo.backFaceStencil);
} }
_mtlDepthStencilState = [_mtlDevice newDepthStencilStateWithDescriptor:mtlDescriptor]; _mtlDepthStencilState = [_mtlDevice newDepthStencilStateWithDescriptor:mtlDescriptor];

View File

@ -297,16 +297,22 @@ void RenderPipelineMTL::chooseAttachmentFormat(const RenderTarget* renderTarget,
PixelFormat& depthFormat, PixelFormat& depthFormat,
PixelFormat& stencilFormat) PixelFormat& stencilFormat)
{ {
// choose color attachment format // Choose color attachment format
auto rtMTL = static_cast<const RenderTargetMTL*>(renderTarget); auto rtMTL = static_cast<const RenderTargetMTL*>(renderTarget);
auto rtflags = rtMTL->getTargetFlags(); auto rtflags = rtMTL->getTargetFlags();
for(auto i = 0; i < MAX_COLOR_ATTCHMENT; ++i) { for(auto i = 0; i < MAX_COLOR_ATTCHMENT; ++i) {
colorAttachmentsFormat[i] = bitmask::any(rtflags, getMRTColorFlag(i)) ? rtMTL->getColorAttachmentPixelFormat(i) : PixelFormat::NONE; colorAttachmentsFormat[i] = bitmask::any(rtflags, getMRTColorFlag(i)) ? rtMTL->getColorAttachmentPixelFormat(i) : PixelFormat::NONE;
} }
// choose depth and stencil attachment format, match RenderTargetMTL::applyRenderPassAttachments if (bitmask::any(rtflags, RenderTargetFlag::DEPTH_AND_STENCIL))
depthFormat = bitmask::any(rtflags, RenderTargetFlag::DEPTH) ? rtMTL->getDepthAttachmentPixelFormat() : PixelFormat::NONE; {
stencilFormat = bitmask::any(rtflags, RenderTargetFlag::STENCIL) ? rtMTL->getStencilAttachmentPixelFormat() : PixelFormat::NONE; depthFormat = rtMTL->getDepthAttachmentPixelFormat();
stencilFormat =rtMTL->getStencilAttachmentPixelFormat();
}
else
{
depthFormat = stencilFormat = PixelFormat::NONE;
}
} }
void RenderPipelineMTL::setBlendStateAndFormat(const BlendDescriptor& blendDescriptor) void RenderPipelineMTL::setBlendStateAndFormat(const BlendDescriptor& blendDescriptor)

View File

@ -28,7 +28,7 @@ public:
void setDepthAttachment(TextureBackend* attachment, int level = 0) override; void setDepthAttachment(TextureBackend* attachment, int level = 0) override;
void setStencilAttachment(TextureBackend* attachment, int level = 0) override; void setStencilAttachment(TextureBackend* attachment, int level = 0) override;
void applyRenderPassAttachments(const RenderPassParams& parmas, MTLRenderPassDescriptor* descriptor) const; void applyRenderPassAttachments(const RenderPassDescriptor&, MTLRenderPassDescriptor*) const;
Attachment getColorAttachment(int index) const; Attachment getColorAttachment(int index) const;
Attachment getDepthAttachment() const; Attachment getDepthAttachment() const;

View File

@ -3,7 +3,7 @@
CC_BACKEND_BEGIN CC_BACKEND_BEGIN
static MTLLoadAction getLoadAction(const RenderPassParams& params, static MTLLoadAction getLoadAction(const RenderPassDescriptor& params,
TargetBufferFlags buffer) { TargetBufferFlags buffer) {
const auto clearFlags = (TargetBufferFlags) params.flags.clear; const auto clearFlags = (TargetBufferFlags) params.flags.clear;
const auto discardStartFlags = params.flags.discardStart; const auto discardStartFlags = params.flags.discardStart;
@ -15,7 +15,7 @@ static MTLLoadAction getLoadAction(const RenderPassParams& params,
return MTLLoadActionLoad; return MTLLoadActionLoad;
} }
static MTLStoreAction getStoreAction(const RenderPassParams& params, static MTLStoreAction getStoreAction(const RenderPassDescriptor& params,
TargetBufferFlags buffer) { TargetBufferFlags buffer) {
const auto discardEndFlags = params.flags.discardEnd; const auto discardEndFlags = params.flags.discardEnd;
if (bitmask::any(discardEndFlags, buffer)) { if (bitmask::any(discardEndFlags, buffer)) {
@ -59,9 +59,10 @@ void RenderTargetMTL::setStencilAttachment(TextureBackend* attachment, int level
} }
void RenderTargetMTL::applyRenderPassAttachments(const RenderPassParams& params, MTLRenderPassDescriptor* descriptor) const void RenderTargetMTL::applyRenderPassAttachments(const RenderPassDescriptor& params, MTLRenderPassDescriptor* descriptor) const
{ {
const auto discardFlags = params.flags.discardEnd; // const auto discardFlags = params.flags.discardEnd;
auto clearFlags = params.flags.clear;
for (size_t i = 0; i < MAX_COLOR_ATTCHMENT; i++) { for (size_t i = 0; i < MAX_COLOR_ATTCHMENT; i++) {
auto attachment = getColorAttachment(i); auto attachment = getColorAttachment(i);
@ -69,11 +70,14 @@ void RenderTargetMTL::applyRenderPassAttachments(const RenderPassParams& params,
continue; continue;
} }
const auto MRTColorFlag = getMRTColorFlag(i);
descriptor.colorAttachments[i].texture = attachment.texture; descriptor.colorAttachments[i].texture = attachment.texture;
descriptor.colorAttachments[i].level = attachment.level; descriptor.colorAttachments[i].level = attachment.level;
// descriptor.colorAttachments[i].slice = attachment.layer; // descriptor.colorAttachments[i].slice = attachment.layer;
descriptor.colorAttachments[i].loadAction = getLoadAction(params, getMRTColorFlag(i)); descriptor.colorAttachments[i].loadAction = getLoadAction(params, MRTColorFlag);
descriptor.colorAttachments[i].storeAction = getStoreAction(params, getMRTColorFlag(i)); descriptor.colorAttachments[i].storeAction = getStoreAction(params,MRTColorFlag);
if(bitmask::any(clearFlags, MRTColorFlag))
descriptor.colorAttachments[i].clearColor = MTLClearColorMake( descriptor.colorAttachments[i].clearColor = MTLClearColorMake(
params.clearColorValue[0], params.clearColorValue[1], params.clearColorValue[2], params.clearColorValue[3]); params.clearColorValue[0], params.clearColorValue[1], params.clearColorValue[2], params.clearColorValue[3]);
#if 0 #if 0
@ -97,7 +101,7 @@ void RenderTargetMTL::applyRenderPassAttachments(const RenderPassParams& params,
} }
// Sets descriptor depth and stencil params, should match RenderTargetMTL::chooseAttachmentFormat // Sets descriptor depth and stencil params, should match RenderTargetMTL::chooseAttachmentFormat
if(bitmask::any(this->_flags, RenderTargetFlag::DEPTH)) { if(bitmask::any(this->_flags, RenderTargetFlag::DEPTH_AND_STENCIL)) {
auto depthAttachment = getDepthAttachment(); auto depthAttachment = getDepthAttachment();
if(depthAttachment){ if(depthAttachment){
descriptor.depthAttachment.texture = depthAttachment.texture; descriptor.depthAttachment.texture = depthAttachment.texture;
@ -105,11 +109,10 @@ void RenderTargetMTL::applyRenderPassAttachments(const RenderPassParams& params,
// descriptor.depthAttachment.slice = depthAttachment.layer; // descriptor.depthAttachment.slice = depthAttachment.layer;
descriptor.depthAttachment.loadAction = getLoadAction(params, TargetBufferFlags::DEPTH); descriptor.depthAttachment.loadAction = getLoadAction(params, TargetBufferFlags::DEPTH);
descriptor.depthAttachment.storeAction = getStoreAction(params, TargetBufferFlags::DEPTH); descriptor.depthAttachment.storeAction = getStoreAction(params, TargetBufferFlags::DEPTH);
if(bitmask::any(clearFlags, TargetBufferFlags::DEPTH))
descriptor.depthAttachment.clearDepth = params.clearDepthValue; descriptor.depthAttachment.clearDepth = params.clearDepthValue;
} }
}
if(bitmask::any(this->_flags, RenderTargetFlag::STENCIL)) {
auto stencilAttachment = getStencilAttachment(); auto stencilAttachment = getStencilAttachment();
if(stencilAttachment) { if(stencilAttachment) {
descriptor.stencilAttachment.texture = stencilAttachment.texture; descriptor.stencilAttachment.texture = stencilAttachment.texture;
@ -117,6 +120,7 @@ void RenderTargetMTL::applyRenderPassAttachments(const RenderPassParams& params,
// descriptor.stencilAttachment.slice = depthAttachment.layer; // descriptor.stencilAttachment.slice = depthAttachment.layer;
descriptor.stencilAttachment.loadAction = getLoadAction(params, TargetBufferFlags::STENCIL); descriptor.stencilAttachment.loadAction = getLoadAction(params, TargetBufferFlags::STENCIL);
descriptor.stencilAttachment.storeAction = getStoreAction(params, TargetBufferFlags::STENCIL); descriptor.stencilAttachment.storeAction = getStoreAction(params, TargetBufferFlags::STENCIL);
if(bitmask::any(clearFlags, TargetBufferFlags::STENCIL))
descriptor.stencilAttachment.clearStencil = params.clearStencilValue; descriptor.stencilAttachment.clearStencil = params.clearStencilValue;
} }
} }
@ -177,7 +181,7 @@ PixelFormat RenderTargetMTL::getColorAttachmentPixelFormat(int index) const
PixelFormat RenderTargetMTL::getDepthAttachmentPixelFormat() const PixelFormat RenderTargetMTL::getDepthAttachmentPixelFormat() const
{ // FIXME: engine-x only support D24S8 { // FIXME: engine-x only support D24S8
if(bitmask::any(_flags, TargetBufferFlags::DEPTH)) { if(bitmask::any(_flags, TargetBufferFlags::DEPTH_AND_STENCIL)) {
if(isDefaultRenderTarget() || !_depth) if(isDefaultRenderTarget() || !_depth)
return PixelFormat::D24S8; return PixelFormat::D24S8;
return _depth.texture->getTextureFormat(); return _depth.texture->getTextureFormat();
@ -187,7 +191,7 @@ PixelFormat RenderTargetMTL::getDepthAttachmentPixelFormat() const
PixelFormat RenderTargetMTL::getStencilAttachmentPixelFormat() const PixelFormat RenderTargetMTL::getStencilAttachmentPixelFormat() const
{ // FIXME: engine-x only support D24S8 { // FIXME: engine-x only support D24S8
if(bitmask::any(_flags, TargetBufferFlags::STENCIL)) { if(bitmask::any(_flags, TargetBufferFlags::DEPTH_AND_STENCIL)) {
if(isDefaultRenderTarget() || !_stencil) if(isDefaultRenderTarget() || !_stencil)
return PixelFormat::D24S8; return PixelFormat::D24S8;
return _stencil.texture->getTextureFormat(); return _stencil.texture->getTextureFormat();

View File

@ -66,11 +66,12 @@ CommandBufferGL::~CommandBufferGL()
cleanResources(); cleanResources();
} }
void CommandBufferGL::beginFrame() bool CommandBufferGL::beginFrame()
{ {
return true;
} }
void CommandBufferGL::beginRenderPass(const RenderTarget* rt, const RenderPassParams& descirptor) void CommandBufferGL::beginRenderPass(const RenderTarget* rt, const RenderPassDescriptor& descirptor)
{ {
auto rtGL = static_cast<const RenderTargetGL*>(rt); auto rtGL = static_cast<const RenderTargetGL*>(rt);
@ -227,6 +228,8 @@ void CommandBufferGL::drawElements(PrimitiveType primitiveType, IndexFormat inde
void CommandBufferGL::endRenderPass() void CommandBufferGL::endRenderPass()
{ {
CC_SAFE_RELEASE_NULL(_indexBuffer);
CC_SAFE_RELEASE_NULL(_vertexBuffer);
} }
void CommandBufferGL::endFrame() void CommandBufferGL::endFrame()
@ -436,9 +439,7 @@ void CommandBufferGL::setUniform(bool isArray, GLuint location, unsigned int siz
void CommandBufferGL::cleanResources() void CommandBufferGL::cleanResources()
{ {
CC_SAFE_RELEASE_NULL(_indexBuffer);
CC_SAFE_RELEASE_NULL(_programState); CC_SAFE_RELEASE_NULL(_programState);
CC_SAFE_RELEASE_NULL(_vertexBuffer);
} }
void CommandBufferGL::setLineWidth(float lineWidth) void CommandBufferGL::setLineWidth(float lineWidth)

View File

@ -70,13 +70,13 @@ public:
/** /**
* @brief Indicate the begining of a frame * @brief Indicate the begining of a frame
*/ */
virtual void beginFrame() override; virtual bool beginFrame() override;
/** /**
* Begin a render pass, initial color, depth and stencil attachment. * Begin a render pass, initial color, depth and stencil attachment.
* @param descriptor Specifies a group of render targets that hold the results of a render pass. * @param descriptor Specifies a group of render targets that hold the results of a render pass.
*/ */
virtual void beginRenderPass(const RenderTarget* rt, const RenderPassParams& descriptor) override; virtual void beginRenderPass(const RenderTarget* rt, const RenderPassDescriptor& descriptor) override;
/** /**
* Update depthStencil status, improvment: for metal backend cache it * Update depthStencil status, improvment: for metal backend cache it

View File

@ -38,8 +38,9 @@ void DepthStencilStateGL::reset()
void DepthStencilStateGL::apply(unsigned int stencilReferenceValueFront, unsigned int stencilReferenceValueBack) const void DepthStencilStateGL::apply(unsigned int stencilReferenceValueFront, unsigned int stencilReferenceValueBack) const
{ {
const auto dsFlags = _depthStencilInfo.flags;
// depth test // depth test
if (bitmask::any(_depthStencilInfo.depthStencilFlags, TargetBufferFlags::DEPTH)) if (bitmask::any(dsFlags, DepthStencilFlags::DEPTH_TEST))
{ {
glEnable(GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
} }
@ -48,7 +49,7 @@ void DepthStencilStateGL::apply(unsigned int stencilReferenceValueFront, unsigne
glDisable(GL_DEPTH_TEST); glDisable(GL_DEPTH_TEST);
} }
if (_depthStencilInfo.depthWriteEnabled) if (bitmask::any(dsFlags, DepthStencilFlags::DEPTH_WRITE))
glDepthMask(GL_TRUE); glDepthMask(GL_TRUE);
else else
glDepthMask(GL_FALSE); glDepthMask(GL_FALSE);
@ -56,7 +57,7 @@ void DepthStencilStateGL::apply(unsigned int stencilReferenceValueFront, unsigne
glDepthFunc(UtilsGL::toGLComareFunction(_depthStencilInfo.depthCompareFunction)); glDepthFunc(UtilsGL::toGLComareFunction(_depthStencilInfo.depthCompareFunction));
// stencil test // stencil test
if (bitmask::any(_depthStencilInfo.depthStencilFlags, TargetBufferFlags::STENCIL)) { if (bitmask::any(dsFlags, DepthStencilFlags::STENCIL_TEST)) {
glEnable(GL_STENCIL_TEST); glEnable(GL_STENCIL_TEST);
if (_isBackFrontStencilEqual) if (_isBackFrontStencilEqual)

View File

@ -864,6 +864,15 @@ void EditBox::keyboardDidHide(IMEKeyboardNotificationInfo& /*info*/)
} }
void EditBox::setGlobalZOrder(float globalZOrder)
{
Widget::setGlobalZOrder(globalZOrder);
if (_editBoxImpl)
{
_editBoxImpl->setGlobalZOrder(globalZOrder);
}
}
#if CC_ENABLE_SCRIPT_BINDING #if CC_ENABLE_SCRIPT_BINDING
void EditBox::registerScriptEditBoxHandler(int handler) void EditBox::registerScriptEditBoxHandler(int handler)
{ {

View File

@ -648,6 +648,8 @@ namespace ui {
*/ */
virtual void keyboardDidHide(IMEKeyboardNotificationInfo& info) override; virtual void keyboardDidHide(IMEKeyboardNotificationInfo& info) override;
void setGlobalZOrder(float globalZOrder) override;
void openKeyboard() const; void openKeyboard() const;
protected: protected:

View File

@ -96,12 +96,14 @@ void EditBoxImplCommon::initInactiveLabels(const Size& size)
_label->setAnchorPoint(Vec2(0.0f,1.0f)); _label->setAnchorPoint(Vec2(0.0f,1.0f));
_label->setOverflow(Label::Overflow::CLAMP); _label->setOverflow(Label::Overflow::CLAMP);
_label->setVisible(false); _label->setVisible(false);
_label->setGlobalZOrder(_editBox->getGlobalZOrder());
_editBox->addChild(_label, kLabelZOrder); _editBox->addChild(_label, kLabelZOrder);
_labelPlaceHolder = Label::create(); _labelPlaceHolder = Label::create();
_labelPlaceHolder->setAnchorPoint(Vec2(0.0f, 1.0f)); _labelPlaceHolder->setAnchorPoint(Vec2(0.0f, 1.0f));
_labelPlaceHolder->setTextColor(Color4B::GRAY); _labelPlaceHolder->setTextColor(Color4B::GRAY);
_labelPlaceHolder->enableWrap(false); _labelPlaceHolder->enableWrap(false);
_labelPlaceHolder->setGlobalZOrder(_editBox->getGlobalZOrder());
_editBox->addChild(_labelPlaceHolder, kLabelZOrder); _editBox->addChild(_labelPlaceHolder, kLabelZOrder);
setFont(pDefaultFontName, size.height*2/3); setFont(pDefaultFontName, size.height*2/3);
@ -291,6 +293,19 @@ void EditBoxImplCommon::setContentSize(const Size& size)
placeInactiveLabels(_contentSize); placeInactiveLabels(_contentSize);
} }
void EditBoxImplCommon::setGlobalZOrder(float globalZOrder)
{
if (_label)
{
_label->setGlobalZOrder(globalZOrder);
}
if (_labelPlaceHolder)
{
_labelPlaceHolder->setGlobalZOrder(globalZOrder);
}
}
void EditBoxImplCommon::draw(Renderer* /*renderer*/, const Mat4& /*transform*/, uint32_t flags) void EditBoxImplCommon::draw(Renderer* /*renderer*/, const Mat4& /*transform*/, uint32_t flags)
{ {
if(flags) if(flags)

View File

@ -91,6 +91,7 @@ public:
virtual void setAnchorPoint(const Vec2& anchorPoint) override {} virtual void setAnchorPoint(const Vec2& anchorPoint) override {}
virtual void setPosition(const Vec2& pos) override {} virtual void setPosition(const Vec2& pos) override {}
virtual void setGlobalZOrder(float globalZOrder) override;
/** /**
* @js NA * @js NA

View File

@ -87,6 +87,8 @@ namespace cocos2d {
virtual void setContentSize(const Size& size) = 0; virtual void setContentSize(const Size& size) = 0;
virtual void setAnchorPoint(const Vec2& anchorPoint) = 0; virtual void setAnchorPoint(const Vec2& anchorPoint) = 0;
virtual void setGlobalZOrder(float globalZOrder) = 0;
/** /**
* check the editbox's position, update it when needed * check the editbox's position, update it when needed
*/ */

View File

@ -241,10 +241,8 @@ void Layout::stencilClippingVisit(Renderer *renderer, const Mat4& parentTransfor
// IMPORTANT: // IMPORTANT:
// To ease the migration to v3.0, we still support the Mat4 stack, // To ease the migration to v3.0, we still support the Mat4 stack,
// but it is deprecated and your code should not rely on it // but it is deprecated and your code should not rely on it
Director* director = Director::getInstance(); _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
CCASSERT(nullptr != director, "Director is null when setting matrix stack"); _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
//Add group command //Add group command
_groupCommand.init(_globalZOrder); _groupCommand.init(_globalZOrder);
@ -313,17 +311,17 @@ void Layout::stencilClippingVisit(Renderer *renderer, const Mat4& parentTransfor
renderer->popGroup(); renderer->popGroup();
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); _director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
} }
void Layout::onBeforeVisitScissor() void Layout::onBeforeVisitScissor()
{ {
auto glview = Director::getInstance()->getOpenGLView(); auto glview = _director->getOpenGLView();
// apply scissor test // apply scissor test
_scissorOldState = glview->isScissorEnabled(); _scissorOldState = glview->isScissorEnabled();
if (false == _scissorOldState) if (false == _scissorOldState)
{ {
auto renderer = Director::getInstance()->getRenderer(); auto renderer = _director->getRenderer();
renderer->setScissorTest(true); renderer->setScissorTest(true);
} }
@ -346,7 +344,7 @@ void Layout::onAfterVisitScissor()
// revert scissor box // revert scissor box
if (false == _clippingOldRect.equals(_clippingRect)) if (false == _clippingOldRect.equals(_clippingRect))
{ {
auto glview = Director::getInstance()->getOpenGLView(); auto glview = _director->getOpenGLView();
glview->setScissorInPoints(_clippingOldRect.origin.x, glview->setScissorInPoints(_clippingOldRect.origin.x,
_clippingOldRect.origin.y, _clippingOldRect.origin.y,
_clippingOldRect.size.width, _clippingOldRect.size.width,
@ -356,7 +354,7 @@ void Layout::onAfterVisitScissor()
else else
{ {
// revert scissor test // revert scissor test
auto renderer = Director::getInstance()->getRenderer(); auto renderer = _director->getRenderer();
renderer->setScissorTest(false); renderer->setScissorTest(false);
} }
} }
@ -368,10 +366,8 @@ void Layout::scissorClippingVisit(Renderer *renderer, const Mat4& parentTransfor
_clippingRectDirty = true; _clippingRectDirty = true;
} }
Director* director = Director::getInstance(); _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
CCASSERT(nullptr != director, "Director is null when setting matrix stack"); _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
_groupCommand.init(_globalZOrder); _groupCommand.init(_globalZOrder);
renderer->addCommand(&_groupCommand); renderer->addCommand(&_groupCommand);
@ -388,7 +384,7 @@ void Layout::scissorClippingVisit(Renderer *renderer, const Mat4& parentTransfor
renderer->addCommand(&_afterVisitCmdScissor); renderer->addCommand(&_afterVisitCmdScissor);
renderer->popGroup(); renderer->popGroup();
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); _director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
} }
void Layout::setClippingEnabled(bool able) void Layout::setClippingEnabled(bool able)
@ -632,6 +628,7 @@ void Layout::supplyTheLayoutParameterLackToChild(Widget *child)
break; break;
case Type::HORIZONTAL: case Type::HORIZONTAL:
case Type::VERTICAL: case Type::VERTICAL:
case Type::CENTER_VERTICAL:
{ {
LinearLayoutParameter* layoutParameter = dynamic_cast<LinearLayoutParameter*>(child->getLayoutParameter()); LinearLayoutParameter* layoutParameter = dynamic_cast<LinearLayoutParameter*>(child->getLayoutParameter());
if (!layoutParameter) if (!layoutParameter)
@ -922,6 +919,9 @@ LayoutManager* Layout::createLayoutManager()
case Type::VERTICAL: case Type::VERTICAL:
exe = LinearVerticalLayoutManager::create(); exe = LinearVerticalLayoutManager::create();
break; break;
case Type::CENTER_VERTICAL:
exe = LinearCenterVerticalLayoutManager::create();
break;
case Type::HORIZONTAL: case Type::HORIZONTAL:
exe = LinearHorizontalLayoutManager::create(); exe = LinearHorizontalLayoutManager::create();
break; break;
@ -1043,7 +1043,7 @@ Size Layout::getLayoutAccumulatedSize()const
{ {
layoutSize = layoutSize - Size(0, layoutSize.height/widgetCount * (widgetCount-1)); layoutSize = layoutSize - Size(0, layoutSize.height/widgetCount * (widgetCount-1));
} }
if (type == Type::VERTICAL) if (type == Type::VERTICAL || type == Type::CENTER_VERTICAL)
{ {
layoutSize = layoutSize - Size(layoutSize.width/widgetCount * (widgetCount-1), 0); layoutSize = layoutSize - Size(layoutSize.width/widgetCount * (widgetCount-1), 0);
} }
@ -1634,7 +1634,8 @@ bool Layout::isLastWidgetInContainer(Widget* widget, FocusDirection direction)c
auto& container = parent->getChildren(); auto& container = parent->getChildren();
ssize_t index = container.getIndex(widget); ssize_t index = container.getIndex(widget);
if (parent->getLayoutType() == Type::HORIZONTAL) const auto parentLayoutType = parent->getLayoutType();
if (parentLayoutType == Type::HORIZONTAL)
{ {
if (direction == FocusDirection::LEFT) if (direction == FocusDirection::LEFT)
{ {
@ -1668,7 +1669,7 @@ bool Layout::isLastWidgetInContainer(Widget* widget, FocusDirection direction)c
return isLastWidgetInContainer(parent, direction); return isLastWidgetInContainer(parent, direction);
} }
} }
else if(parent->getLayoutType() == Type::VERTICAL) else if (parentLayoutType == Type::VERTICAL || parentLayoutType == Type::CENTER_VERTICAL)
{ {
if (direction == FocusDirection::UP) if (direction == FocusDirection::UP)
{ {
@ -1721,7 +1722,7 @@ bool Layout::isWidgetAncestorSupportLoopFocus(Widget* widget, FocusDirection di
} }
if (parent->isLoopFocus()) if (parent->isLoopFocus())
{ {
auto layoutType = parent->getLayoutType(); const auto layoutType = parent->getLayoutType();
if (layoutType == Type::HORIZONTAL) if (layoutType == Type::HORIZONTAL)
{ {
if (direction == FocusDirection::LEFT || direction == FocusDirection::RIGHT) if (direction == FocusDirection::LEFT || direction == FocusDirection::RIGHT)
@ -1733,7 +1734,7 @@ bool Layout::isWidgetAncestorSupportLoopFocus(Widget* widget, FocusDirection di
return isWidgetAncestorSupportLoopFocus(parent, direction); return isWidgetAncestorSupportLoopFocus(parent, direction);
} }
} }
if (layoutType == Type::VERTICAL) if (layoutType == Type::VERTICAL || layoutType == Type::CENTER_VERTICAL)
{ {
if (direction == FocusDirection::DOWN || direction == FocusDirection::UP) if (direction == FocusDirection::DOWN || direction == FocusDirection::UP)
{ {
@ -1823,7 +1824,7 @@ Widget* Layout::findNextFocusedWidget(FocusDirection direction, Widget* current)
break; break;
} }
} }
else if (_layoutType == Type::VERTICAL) else if (_layoutType == Type::VERTICAL || _layoutType == Type::CENTER_VERTICAL)
{ {
switch (direction) switch (direction)
{ {

View File

@ -120,6 +120,7 @@ public:
{ {
ABSOLUTE, ABSOLUTE,
VERTICAL, VERTICAL,
CENTER_VERTICAL,
HORIZONTAL, HORIZONTAL,
RELATIVE RELATIVE
}; };

View File

@ -85,7 +85,6 @@ void LinearHorizontalLayoutManager::doLayout(LayoutProtocol* layout)
} }
} }
//LinearVerticalLayoutManager //LinearVerticalLayoutManager
LinearVerticalLayoutManager* LinearVerticalLayoutManager::create() LinearVerticalLayoutManager* LinearVerticalLayoutManager::create()
{ {
@ -143,6 +142,82 @@ void LinearVerticalLayoutManager::doLayout(LayoutProtocol* layout)
} }
} }
//LinearCenterVerticalLayoutManager
LinearCenterVerticalLayoutManager* LinearCenterVerticalLayoutManager::create()
{
auto* exe = new (std::nothrow) LinearCenterVerticalLayoutManager();
if (exe)
{
exe->autorelease();
return exe;
}
CC_SAFE_DELETE(exe);
return nullptr;
}
void LinearCenterVerticalLayoutManager::doLayout(LayoutProtocol* layout)
{
const auto layoutSize = layout->getLayoutContentSize();
auto&& container = layout->getLayoutElements();
auto topBoundary = layoutSize.height;
auto totalHeight = 0.f;
// need to get total sub-widget height
for (auto&& subWidget : container)
{
auto* child = dynamic_cast<LayoutParameterProtocol*>(subWidget);
if (child)
{
auto* layoutParameter = dynamic_cast<LinearLayoutParameter*>(child->getLayoutParameter());
if (layoutParameter)
{
auto&& mg = layoutParameter->getMargin();
totalHeight += subWidget->getBoundingBox().size.height + mg.top + mg.bottom;
}
}
}
topBoundary = topBoundary - (topBoundary - totalHeight) / 2.f;
for (auto&& subWidget : container)
{
auto* child = dynamic_cast<LayoutParameterProtocol*>(subWidget);
if (child)
{
auto* layoutParameter = dynamic_cast<LinearLayoutParameter*>(child->getLayoutParameter());
if (layoutParameter)
{
const auto childGravity = layoutParameter->getGravity();
const auto ap = subWidget->getAnchorPoint();
const auto cs = subWidget->getBoundingBox().size;
auto finalPosX = ap.x * cs.width;
auto finalPosY = topBoundary - ((1.0f - ap.y) * cs.height);
switch (childGravity)
{
case LinearLayoutParameter::LinearGravity::NONE:
case LinearLayoutParameter::LinearGravity::LEFT:
break;
case LinearLayoutParameter::LinearGravity::RIGHT:
finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width);
break;
case LinearLayoutParameter::LinearGravity::CENTER_HORIZONTAL:
finalPosX = layoutSize.width / 2.0f - cs.width * (0.5f - ap.x);
break;
default:
break;
}
auto&& mg = layoutParameter->getMargin();
finalPosX += mg.left;
finalPosY -= mg.top;
subWidget->setPosition(finalPosX, finalPosY);
topBoundary = subWidget->getPosition().y - subWidget->getAnchorPoint().y * subWidget->getBoundingBox().size.height - mg.bottom;
}
}
}
}
//RelativeLayoutManager //RelativeLayoutManager
RelativeLayoutManager* RelativeLayoutManager::create() RelativeLayoutManager* RelativeLayoutManager::create()

View File

@ -94,6 +94,23 @@ private:
friend class Layout; friend class Layout;
}; };
/**
*@brief Linear vertical layouting class.
* Note: This class is used only by @see `Layout` class.
* @lua NA
* @js NA
*/
class CC_GUI_DLL LinearCenterVerticalLayoutManager : public LayoutManager
{
private:
LinearCenterVerticalLayoutManager() {};
virtual ~LinearCenterVerticalLayoutManager() {};
static LinearCenterVerticalLayoutManager* create();
virtual void doLayout(LayoutProtocol* layout) override;
friend class Layout;
};
/** /**
*@brief Relative layouting class. *@brief Relative layouting class.
*Note: This class is used only by `Layout` class. *Note: This class is used only by `Layout` class.

View File

@ -117,7 +117,7 @@ void ListView::updateInnerContainerSize()
float totalHeight = (length == 0) ? 0.0f : (length - 1) * _itemsMargin + (_topPadding + _bottomPadding); float totalHeight = (length == 0) ? 0.0f : (length - 1) * _itemsMargin + (_topPadding + _bottomPadding);
for (auto& item : _items) for (auto& item : _items)
{ {
totalHeight += item->getContentSize().height; totalHeight += item->getContentSize().height * item->getScaleY();
} }
float finalWidth = _contentSize.width; float finalWidth = _contentSize.width;
float finalHeight = totalHeight; float finalHeight = totalHeight;
@ -130,7 +130,7 @@ void ListView::updateInnerContainerSize()
float totalWidth = (length == 0) ? 0.0f : (length - 1) * _itemsMargin + (_leftPadding + _rightPadding); float totalWidth = (length == 0) ? 0.0f : (length - 1) * _itemsMargin + (_leftPadding + _rightPadding);
for (auto& item : _items) for (auto& item : _items)
{ {
totalWidth += item->getContentSize().width; totalWidth += item->getContentSize().width * item->getScaleX();
} }
float finalWidth = totalWidth; float finalWidth = totalWidth;
float finalHeight = _contentSize.height; float finalHeight = _contentSize.height;

View File

@ -466,7 +466,7 @@ namespace ui {
if (ret) if (ret)
{ {
// open keyboard // open keyboard
GLView * pGlView = Director::getInstance()->getOpenGLView(); GLView * pGlView = _director->getOpenGLView();
if (pGlView) if (pGlView)
{ {
pGlView->setIMEKeyboardState(true); pGlView->setIMEKeyboardState(true);
@ -481,7 +481,7 @@ namespace ui {
if (ret) if (ret)
{ {
// close keyboard // close keyboard
GLView * glView = Director::getInstance()->getOpenGLView(); GLView * glView = _director->getOpenGLView();
if (glView) if (glView)
{ {
glView->setIMEKeyboardState(false); glView->setIMEKeyboardState(false);

View File

@ -1371,7 +1371,7 @@ void Widget::dispatchFocusEvent(cocos2d::ui::Widget *widgetLoseFocus, cocos2d::u
} }
EventFocus event(widgetLoseFocus, widgetGetFocus); EventFocus event(widgetLoseFocus, widgetGetFocus);
auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); auto dispatcher = _director->getEventDispatcher();
dispatcher->dispatchEvent(&event); dispatcher->dispatchEvent(&event);
} }

View File

@ -48,7 +48,7 @@ function(setup_cocos_extension_config target_name)
PROPERTIES PROPERTIES
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
FOLDER "Extensions" FOLDER "Extensions"
) )

View File

@ -30,6 +30,9 @@
// Physics integration // Physics integration
#include "physics-nodes/CCPhysicsDebugNode.h" #include "physics-nodes/CCPhysicsDebugNode.h"
#include "physics-nodes/CCPhysicsSprite.h" #include "physics-nodes/CCPhysicsSprite.h"
#include "physics-nodes/CCPhysicsSpriteBox2D.h"
#include "physics-nodes/CCPhysicsSpriteChipmunk2D.h"
#include "assets-manager/AssetsManager.h" #include "assets-manager/AssetsManager.h"
#include "assets-manager/AssetsManagerEx.h" #include "assets-manager/AssetsManagerEx.h"

View File

@ -208,14 +208,12 @@ void GUIReader::registerTypeAndCallBack(const std::string& classType,
Widget* GUIReader::widgetFromJsonFile(const char *fileName) Widget* GUIReader::widgetFromJsonFile(const char *fileName)
{ {
auto thiz = GUIReader::getInstance();
std::string jsonpath; std::string jsonpath;
rapidjson::Document jsonDict; rapidjson::Document jsonDict;
jsonpath = fileName; jsonpath = fileName;
// jsonpath = CCFileUtils::getInstance()->fullPathForFilename(fileName); // jsonpath = CCFileUtils::getInstance()->fullPathForFilename(fileName);
size_t pos = jsonpath.find_last_of('/'); size_t pos = jsonpath.find_last_of('/');
thiz->m_strFilePath = jsonpath.substr(0,pos+1); m_strFilePath = jsonpath.substr(0,pos+1);
std::string contentStr = FileUtils::getInstance()->getStringFromFile(jsonpath); std::string contentStr = FileUtils::getInstance()->getStringFromFile(jsonpath);
jsonDict.Parse<0>(contentStr.c_str()); jsonDict.Parse<0>(contentStr.c_str());
if (jsonDict.HasParseError()) if (jsonDict.HasParseError())
@ -227,22 +225,22 @@ Widget* GUIReader::widgetFromJsonFile(const char *fileName)
WidgetPropertiesReader * pReader = nullptr; WidgetPropertiesReader * pReader = nullptr;
if (fileVersion) if (fileVersion)
{ {
int versionInteger = thiz->getVersionInteger(fileVersion); int versionInteger = this->getVersionInteger(fileVersion);
if (versionInteger < 250) if (versionInteger < 250)
{ {
pReader = new (std::nothrow) WidgetPropertiesReader0250(); pReader = new (std::nothrow) WidgetPropertiesReader0250();
widget = pReader->createWidget(jsonDict, thiz->m_strFilePath.c_str(), fileName); widget = pReader->createWidget(jsonDict, this->m_strFilePath.c_str(), fileName);
} }
else else
{ {
pReader = new (std::nothrow) WidgetPropertiesReader0300(); pReader = new (std::nothrow) WidgetPropertiesReader0300();
widget = pReader->createWidget(jsonDict, thiz->m_strFilePath.c_str(), fileName); widget = pReader->createWidget(jsonDict, this->m_strFilePath.c_str(), fileName);
} }
} }
else else
{ {
pReader = new (std::nothrow) WidgetPropertiesReader0250(); pReader = new (std::nothrow) WidgetPropertiesReader0250();
widget = pReader->createWidget(jsonDict, thiz->m_strFilePath.c_str(), fileName); widget = pReader->createWidget(jsonDict, this->m_strFilePath.c_str(), fileName);
} }
CC_SAFE_DELETE(pReader); CC_SAFE_DELETE(pReader);
@ -366,14 +364,12 @@ WidgetReaderProtocol* WidgetPropertiesReader::createWidgetReaderProtocol(const s
Widget* GUIReader::widgetFromBinaryFile(const char *fileName) Widget* GUIReader::widgetFromBinaryFile(const char *fileName)
{ {
auto thiz = GUIReader::getInstance();
std::string jsonpath; std::string jsonpath;
rapidjson::Document jsonDict; rapidjson::Document jsonDict;
jsonpath = fileName; jsonpath = fileName;
// jsonpath = CCFileUtils::getInstance()->fullPathForFilename(fileName); // jsonpath = CCFileUtils::getInstance()->fullPathForFilename(fileName);
size_t pos = jsonpath.find_last_of('/'); size_t pos = jsonpath.find_last_of('/');
thiz->m_strFilePath = jsonpath.substr(0,pos+1); m_strFilePath = jsonpath.substr(0,pos+1);
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName); std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName);
auto fileData = FileUtils::getInstance()->getDataFromFile(fullPath); auto fileData = FileUtils::getInstance()->getDataFromFile(fullPath);
auto fileDataBytes = fileData.getBytes(); auto fileDataBytes = fileData.getBytes();
@ -406,7 +402,7 @@ Widget* GUIReader::widgetFromBinaryFile(const char *fileName)
WidgetPropertiesReader * pReader = nullptr; WidgetPropertiesReader * pReader = nullptr;
if (fileVersion) if (fileVersion)
{ {
int versionInteger = thiz->getVersionInteger(fileVersion); int versionInteger = this->getVersionInteger(fileVersion);
if (versionInteger < 250) if (versionInteger < 250)
{ {
CCASSERT(0, "You current studio doesn't support binary format, please upgrade to the latest version!"); CCASSERT(0, "You current studio doesn't support binary format, please upgrade to the latest version!");

View File

@ -1,4 +1,4 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2013-2017 Chukong Technologies Inc. Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
@ -62,9 +62,9 @@ public:
static GUIReader* getInstance(); static GUIReader* getInstance();
static void destroyInstance(); static void destroyInstance();
static cocos2d::ui::Widget* widgetFromJsonFile(const char* fileName); cocos2d::ui::Widget* widgetFromJsonFile(const char* fileName);
static cocos2d::ui::Widget* widgetFromBinaryFile(const char* fileName); cocos2d::ui::Widget* widgetFromBinaryFile(const char* fileName);
int getVersionInteger(const char* str); int getVersionInteger(const char* str);
/** /**

View File

@ -101,7 +101,7 @@ void FUISprite::setScaleByTile(bool value)
void FUISprite::setGrayed(bool value) void FUISprite::setGrayed(bool value)
{ {
#if defined(ENGINEX_VERSION) #if defined(ENGINEX_VERSION)
Sprite::setProgramState(backend::ProgramType::GRAY_SCALE); Sprite::setProgramState(value ? backend::ProgramType::GRAY_SCALE : backend::ProgramType::POSITION_TEXTURE_COLOR);
#elif COCOS2D_VERSION >= 0x00040000 #elif COCOS2D_VERSION >= 0x00040000
auto isETC1 = getTexture() && getTexture()->getAlphaTextureName(); auto isETC1 = getTexture() && getTexture()->getAlphaTextureName();
if (value) { if (value) {

View File

@ -22,9 +22,8 @@
*/ */
#include "CCPhysicsDebugNode.h" #include "CCPhysicsDebugNode.h"
#if CC_ENABLE_CHIPMUNK_INTEGRATION
#include "chipmunk/chipmunk_private.h" #include "chipmunk/chipmunk_private.h"
#endif
#include "base/ccTypes.h" #include "base/ccTypes.h"
#include "math/CCGeometry.h" #include "math/CCGeometry.h"
@ -38,7 +37,6 @@
NS_CC_EXT_BEGIN NS_CC_EXT_BEGIN
#if CC_ENABLE_CHIPMUNK_INTEGRATION
/* /*
IMPORTANT - READ ME! IMPORTANT - READ ME!
@ -160,7 +158,7 @@ static void DrawConstraint(cpConstraint *constraint, DrawNode *renderer)
// printf("Cannot draw constraint\n"); // printf("Cannot draw constraint\n");
} }
} }
#endif // #if CC_ENABLE_CHIPMUNK_INTEGRATION
// implementation of PhysicsDebugNode // implementation of PhysicsDebugNode
@ -170,7 +168,6 @@ void PhysicsDebugNode::draw(Renderer *renderer, const Mat4 &transform, uint32_t
{ {
return; return;
} }
#if CC_ENABLE_CHIPMUNK_INTEGRATION
// clear the shapes information before draw current shapes. // clear the shapes information before draw current shapes.
DrawNode::clear(); DrawNode::clear();
@ -178,7 +175,6 @@ void PhysicsDebugNode::draw(Renderer *renderer, const Mat4 &transform, uint32_t
cpSpaceEachConstraint(_spacePtr, (cpSpaceConstraintIteratorFunc)DrawConstraint, this); cpSpaceEachConstraint(_spacePtr, (cpSpaceConstraintIteratorFunc)DrawConstraint, this);
DrawNode::draw(renderer, transform, flags); DrawNode::draw(renderer, transform, flags);
#endif
} }
PhysicsDebugNode::PhysicsDebugNode() PhysicsDebugNode::PhysicsDebugNode()
@ -191,11 +187,7 @@ PhysicsDebugNode* PhysicsDebugNode::create(cpSpace *space)
if (node) if (node)
{ {
node->init(); node->init();
#if CC_ENABLE_CHIPMUNK_INTEGRATION
node->_spacePtr = space; node->_spacePtr = space;
#else
CCASSERT(false, "CC_ENABLE_CHIPMUNK_INTEGRATION was not enabled!");
#endif
node->autorelease(); node->autorelease();
} }
else else
@ -212,21 +204,12 @@ PhysicsDebugNode::~PhysicsDebugNode()
cpSpace* PhysicsDebugNode::getSpace() const cpSpace* PhysicsDebugNode::getSpace() const
{ {
#if CC_ENABLE_CHIPMUNK_INTEGRATION
return _spacePtr; return _spacePtr;
#else
CCASSERT(false, "Can't call chipmunk methods when Chipmunk is disabled");
return nullptr;
#endif
} }
void PhysicsDebugNode::setSpace(cpSpace *space) void PhysicsDebugNode::setSpace(cpSpace *space)
{ {
#if CC_ENABLE_CHIPMUNK_INTEGRATION
_spacePtr = space; _spacePtr = space;
#else
CCASSERT(false, "Can't call chipmunk methods when Chipmunk is disabled");
#endif
} }
NS_CC_EXT_END NS_CC_EXT_END

View File

@ -27,9 +27,6 @@
#if (CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION) #if (CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION)
#if (CC_ENABLE_CHIPMUNK_INTEGRATION && CC_ENABLE_BOX2D_INTEGRATION)
#error "Either Chipmunk or Box2d should be enabled, but not both at the same time"
#endif
#if CC_ENABLE_CHIPMUNK_INTEGRATION #if CC_ENABLE_CHIPMUNK_INTEGRATION
#include "chipmunk/chipmunk.h" #include "chipmunk/chipmunk.h"

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