Merge branch 'develop' into develop_nutty_modify_framework_addlayoutparameterclone

This commit is contained in:
CaiWenzhi 2014-02-07 11:26:46 +08:00
commit c1cfa1cce2
1294 changed files with 13670 additions and 32490 deletions

6
.gitmodules vendored
View File

@ -4,12 +4,12 @@
[submodule "cocos/scripting/auto-generated"]
path = cocos/scripting/auto-generated
url = git://github.com/cocos2d-x/bindings-auto-generated.git
[submodule "samples/Javascript/Shared"]
path = samples/Javascript/Shared
url = git://github.com/cocos2d/cocos2d-js-tests.git
[submodule "tools/cocos2d-console"]
path = tools/cocos2d-console
url = git://github.com/cocos2d/cocos2d-console.git
[submodule "plugin"]
path = plugin
url = https://github.com/cocos2d-x/plugin-x.git
[submodule "tests/test-javascript/tests"]
path = tests/test-javascript/tests
url = git://github.com/cocos2d/cocos2d-js-tests.git

View File

@ -95,6 +95,7 @@ Developers:
Added Mingw-crt Support without breaking VS SDK
CMake support for windows.
Added support for x64 target of windows.
Added Dutch Language support.
mchinen
fix emulator issue for OpenGL ES 2.0 on Android
@ -510,6 +511,8 @@ Developers:
Lee, Jae-Hong (pyrasis)
Maintainer of tizen port.
localStorageGetItem crashes when column text is NULL.
fix image bug on Android
lumendes
Updating spine-runtime to EsotericSoftware/spine-runtimes@5f90386.
@ -725,6 +728,12 @@ Developers:
liang8305
Use multiple processes according the number of cores to build android project
pandamicro
Exposed SAXParser to JS, it is used for parsing XML in JS.
hanjukim
Fixed a bug that color and opacity settings were not applied when invoking Label::alignText.
Retired Core Developers:
WenSheng Yang

View File

@ -1,5 +1,14 @@
cocos2d-x-3.0beta2 ?.? ?
cocos2d-x-3.0rc0 Feb.?? 2014
[All]
[NEW] Adds Dutch Language support.
[FIX] EGLView improvements: renamed to GLView, no longer a singleton, easier to customize
[FIX] Removes samples except testcpp|testjavascript|testlua. Moves sample games to `cocos2d/samples` repo.
cocos2d-x-3.0beta2 Jan.24 2014
[All]
[NEW] Full screen support for desktop platforms.
[NEW] Adds performance test for EventDispatcher.
[NEW] Adds performance test for Containers(Vector<>, Array, Map<K,V>, Dictionary).
[NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier.
[NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands
@ -8,15 +17,22 @@ cocos2d-x-3.0beta2 ?.? ?
[NEW] Label: Integrates LabelAtlas into new Label.
[NEW] Node: Added `setGlobalZOrder()`. Useful to change the Node's render order. Node::setZOrder() -> Node::setLocalZOrder()
[NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10%
[NEW] LuaBindings: Bindings-generator supports to bind namespace for lua.
[FIX] event->stopPropagation can't work for EventListenerTouchAllAtOnce.
[FIX] Uses unified `desktop/CCEGLView.h/cpp` for desktop platforms (windows, mac, linux).
[FIX] Bindings-generator supports Windows again and remove dependency of LLVM since we only need binary(libclang.so/dll).
[FIX] Removes unused files for MAC platform after using glfw3 to create opengl context.
[FIX] Wrong arithmetic of child's position in ParallaxNode::addChild()
[FIX] CocoStudio: TestColliderDetector in ArmatureTest can't work.
[FIX] CocoStudio: The order of transform calculation in Skin::getNodeToWorldTransform() is incorrect.
[FIX] Crash if file doesn't exist when using FileUtils::getStringFromFile.
[FIX] If setting a shorter string than before while using LabelAtlas, the effect will be wrong.
[FIX] Label: Memory leak in FontFreeType::createFontAtlas().
[FIX] Label: Crash when using unknown characters.
[FIX] Label: Missing line breaks and wrong alignment.
[FIX] Label: Corrupt looking characters and incorrect spacing between characters
[FIX] Label: Label:color and opacity settings are invalid afeter these these properties changed: 1)text content changed 2)align style changed 3)max line width limited
[FIX] Label: Crash when using unknown characters
[FIX] Console: log(format, va_args) is private to prevent possible resolution errors
[FIX] Configuration: dumpInfo() -> getInfo()
[FIX] ControlSlider doesn't support to set selected thumb sprite.
@ -28,12 +44,42 @@ cocos2d-x-3.0beta2 ?.? ?
[FIX] Renderer Performance Fix: When note using VAO, call glBufferData() instead of glBufferSubData().
[FIX] Renderer Performance Fix: Doesn't sort z=0 elements. It also uses sort() instead of stable_sort() for z!=0.
[FIX] Sprite: removed _hasChildren optimization. It uses !_children.empty() now which is super fast as well
[FIX] Tests: TestCpp works with CMake on Windows.
[FIX] Tests: Sprites Performance Test has 4 new tests
[FIX] TextureCache: getTextureForKey and removeTextureForKey work as expected
[FIX] TextureCache: dumpCachedTextureInfo() -> getCachedTextureInfo()
[FIX] Websocket doesn't support send/receive data which larger than 4096 bytes.
[FIX] Windows: There will be some compilation errors when using x64 target on Windows.
[FIX] Object: Remove _retainCount
[FIX] ParallaxNode: Coordinate of Sprite may be wrong after being added into ParallaxNode
[FIX] Crash if there is not `textureFileName`section in particle plist file
[FIX] Websocket cannot send/receive more than 4096 bytes data
[FIX] TextureCache::addImageAsync can't load first image
[FIX] ControlSlider: Can not set "selected thumb sprite"
[FIX] ControlSlider: Can not set "scale ratio"
[FIX] Crash when loading tga format image
[FIX] Keyboard pressed events are being repeatedly fired before keyboard is released
[Android]
[FIX] Background music can't be resumed when back from foreground
[FIX] ANR (Application Not Responding) appears on android 2.3 when pressing hardware button.
[lua binding]
[NEW] Can bind classes that have the same class names but different namesapces
[FIX] Use EventDispatcher to update some test cases
[FIX] sp.SkeletonAnimation:registerScriptHandler should not override cc.Node:registerScriptHandler
[javascript binding]
[NEW] Bind SAXParser
[FIX] Pure JS class that wants to inherite from cc.Class will trigger an irrelevant log
[FIX] Mac and iOS Simulator should also use SpiderMonkey which was built in RELEASE mode
[FIX] Crash when running JSB projects on iOS device in DEBUG mode
[FIX] Crash when Firefox connects to JSB application on Mac platform.
[Desktop]
[NEW] Support fullscreen
[Linux]
[FIX] "Testing empty labels" in LabelTest crashes.
[Mac]
[FIX] Removes unused files after using glfw3 to create opengl context
[Win32]
[FIX] Compiling error when using x64 target
[FIX] Tests: TestCpp works with CMake
[FIX] Bindings-generator supports Windows again and remove dependency of LLVM since it only needs binary of libclang
cocos2d-x-3.0beta Jan.7 2014
[All]
@ -780,7 +826,7 @@ cocos2d-2.0-x-2.0.2 @Aug.30 2012
Refactor #1399: adjust directory structure
Refactor #1402: improve static creator function names to avoid confusion
Refactor #1413: improve CCTouch::getLocation(), getDelta() which returns OpenGL coordinates directly
Refactor #1437: change the return type of CCApplication::sharedApplication() and CCEGLView::sharedOpenGLView() to a pointer
Refactor #1437: change the return type of CCApplication::sharedApplication() and CCGLView::sharedOpenGLView() to a pointer
Refactor #1441: put hd and iPad resources of TestCpp into separate directories
Refactor #1442: use CREATE_FUNC to replace LAYER_CREATE_FUNC and SCENE_CREATE_FUNC
[iOS]
@ -814,7 +860,7 @@ cocos2d-2.0-rc2-x-2.0.1 @Jun.28 2012
Bug #1293: fix a bug that CCDirector::getFrames() returns wrong value
Bug #1296: fix a logical error in CCTMXTiledMap::tilesetForLayer()
Bug #1300: fix a typo of CC_ENABLE_CACHE_TEXTTURE_DATA
Bug #1301: apply scissor with points in CCEGLView::sharedOpenGLView().setScissorInPoints()
Bug #1301: apply scissor with points in CCGLView::sharedOpenGLView().setScissorInPoints()
Bug #1302: change the parameter type of CCMenu::setHandlerPriority to signed int
Bug #1308: fix a logical bug in CCTouchDispatcher
Bug #1326: fix a bug that the compilation of HelloLua and testjs project was broken after synchronizing to rc2

View File

@ -45,9 +45,7 @@ option(BUILD_EDITOR_SPINE "Build editor support for spine" ON)
option(BUILD_EDITOR_COCOSTUDIO "Build editor support for cocostudio" ON)
option(BUILD_EDITOR_COCOSBUILDER "Build editor support for cocosbuilder" ON)
option(BUILD_HelloCpp "Only build HelloCpp sample" ON)
option(BUILD_TestCpp "Only build TestCpp sample" ON)
option(BUILD_HelloLua "Only build HelloLua sample" OFF)
option(BUILD_TestLua "Only build TestLua sample" OFF)
else()#temp
@ -63,10 +61,7 @@ option(BUILD_EDITOR_SPINE "Build editor support for spine" ON)
option(BUILD_EDITOR_COCOSTUDIO "Build editor support for cocostudio" ON)
option(BUILD_EDITOR_COCOSBUILDER "Build editor support for cocosbuilder" ON)
option(BUILD_HelloCpp "Only build HelloCpp sample" ON)
option(BUILD_TestCpp "Only build TestCpp sample" ON)
option(BUILD_HelloLua "Only build HelloLua sample" ON)
option(BUILD_TestLua "Only build TestLua sample" ON)
endif()#temp
@ -155,6 +150,7 @@ include_directories(
${CMAKE_CURRENT_SOURCE_DIR}/external/unzip
${CMAKE_CURRENT_SOURCE_DIR}/external/edtaa3func
${CMAKE_CURRENT_SOURCE_DIR}/external/chipmunk/include/chipmunk
${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d/platform/desktop
${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d/platform/${PLATFORM_FOLDER}
${CMAKE_CURRENT_SOURCE_DIR}/external/jpeg/include/${PLATFORM_FOLDER}
${CMAKE_CURRENT_SOURCE_DIR}/external/png/include/${PLATFORM_FOLDER}
@ -169,7 +165,7 @@ if(WIN32)
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/gles/include/OGLES
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/icon/include
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/zlib/include
external/curl/include/${PLATFORM_FOLDER}
external/curl/include/${PLATFORM_FOLDER}
)
elseif(APPLE)
include_directories(
@ -177,8 +173,9 @@ elseif(APPLE)
)
else()
include_directories(
/usr/include
/usr/local/include/GLFW
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/fmod/include/${ARCH_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/external/curl/include/${PLATFORM_FOLDER}/${ARCH_DIR}
)
endif()
@ -192,8 +189,8 @@ if(WIN32)
${CMAKE_CURRENT_SOURCE_DIR}/external/png/prebuilt/${PLATFORM_FOLDER}
${CMAKE_CURRENT_SOURCE_DIR}/external/freetype2/prebuilt/${PLATFORM_FOLDER}
${CMAKE_CURRENT_SOURCE_DIR}/external/curl/prebuilt/${PLATFORM_FOLDER}
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/icon/prebuilt
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/zlib/prebuilt
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/icon/prebuilt
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/zlib/prebuilt
)
endif()
@ -208,7 +205,6 @@ else()
${CMAKE_CURRENT_SOURCE_DIR}/external/webp/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/external/png/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/external/freetype2/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/external/curl/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/fmod/prebuilt/${ARCH_DIR}
)
@ -283,20 +279,13 @@ add_subdirectory(external/lua/tolua)
add_subdirectory(cocos/scripting)
endif(BUILD_LIBS_LUA)
# build samples
if(BUILD_HelloCpp)
add_subdirectory(samples/Cpp/HelloCpp)
endif(BUILD_HelloCpp)
# build tests
if(BUILD_TestCpp)
add_subdirectory(samples/Cpp/TestCpp)
add_subdirectory(tests/test-cpp)
endif(BUILD_TestCpp)
if(BUILD_HelloLua)
add_subdirectory(samples/Lua/HelloLua)
endif(BUILD_HelloLua)
if(BUILD_TestLua)
add_subdirectory(samples/Lua/TestLua)
add_subdirectory(tests/test-lua)
endif(BUILD_TestLua)

View File

@ -1,26 +1,33 @@
#!/usr/bin/python
# android-build.py
# Build android samples
# Build android
import sys
import os, os.path
import shutil
from optparse import OptionParser
CPP_SAMPLES = ['hellocpp', 'testcpp', 'simplegame', 'assetsmanager']
LUA_SAMPLES = ['hellolua', 'testlua']
JSB_SAMPLES = ['cocosdragon', 'crystalcraze', 'moonwarriors', 'testjavascript', 'watermelonwithme']
CPP_SAMPLES = ['testcpp']
LUA_SAMPLES = ['testlua']
JSB_SAMPLES = ['testjavascript']
ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JSB_SAMPLES
def get_num_of_cpu():
''' The build process can be accelerated by running multiple concurrent job processes using the -j-option.
'''
try:
from numpy.distutils import cpuinfo
return cpuinfo.cpu._getNCPUs()
platform = sys.platform
if platform == 'win32':
if 'NUMBER_OF_PROCESSORS' in os.environ:
return int(os.environ['NUMBER_OF_PROCESSORS'])
else:
return 1
else:
from numpy.distutils import cpuinfo
return cpuinfo.cpu._getNCPUs()
except Exception:
print "Can't know cpuinfo, use default 1 cpu"
return 1
return 1
def check_environment_variables():
''' Checking the environment NDK_ROOT, which will be used for building
@ -67,9 +74,9 @@ def select_toolchain_version():
def caculate_built_samples(args):
''' Compute the sampels to be built
'cpp' for short of all cpp samples
'lua' for short of all lua smpleas
'jsb' for short of all javascript samples
'cpp' for short of all cpp tests
'lua' for short of all lua tests
'jsb' for short of all javascript tests
'''
if 'all' in args:
@ -152,47 +159,23 @@ def copy_resources(target, app_android_root):
# jsb samples should copy javascript files and resources(shared with cocos2d-html5)
if target in JSB_SAMPLES:
resources_dir = os.path.join(app_android_root, "../../../../cocos/scripting/javascript/script")
resources_dir = os.path.join(app_android_root, "../../../cocos/scripting/javascript/script")
copy_files(resources_dir, assets_dir)
if target == "cocosdragon":
resources_dir = os.path.join(app_android_root, "../../Shared/games/CocosDragonJS/Published files Android")
if target == "crystalcraze":
resources_dir = os.path.join(app_android_root, "../../Shared/games/CrystalCraze/Published-Android")
if target == "testjavascript":
resources_dir = os.path.join(app_android_root, "../../Shared/tests/")
if target == "watermelonwithme":
resources_dir = os.path.join(app_android_root, "../../Shared/games/WatermelonWithMe")
if target != "moonwarriors":
copy_files(resources_dir, assets_dir)
else:
resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors/res")
dst_dir = os.path.join(assets_dir, "res")
os.mkdir(dst_dir)
copy_files(resources_dir, dst_dir)
resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors/src")
dst_dir = os.path.join(assets_dir, "src")
os.mkdir(dst_dir)
copy_files(resources_dir, dst_dir)
resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors")
for item in os.listdir(resources_dir):
path = os.path.join(resources_dir, item)
if item.endswith('.js') and os.path.isfile(path):
shutil.copy(path, assets_dir)
resources_dir = os.path.join(app_android_root, "../tests/")
# AssetsManager test should also copy javascript files
if target == "assetsmanager":
resources_dir = os.path.join(app_android_root, "../../../../cocos/scripting/javascript/script")
copy_files(resources_dir, assets_dir)
# lua samples should copy lua script
if target in LUA_SAMPLES:
resources_dir = os.path.join(app_android_root, "../../../../cocos/scripting/lua/script")
resources_dir = os.path.join(app_android_root, "../../../cocos/scripting/lua/script")
copy_files(resources_dir, assets_dir)
# TestLua shared resources with TestCpp
if target == "testlua":
resources_dir = os.path.join(app_android_root, "../../../Cpp/TestCpp/Resources")
resources_dir = os.path.join(app_android_root, "../../test-cpp/Resources")
copy_files(resources_dir, assets_dir)
def build_samples(target,ndk_build_param,android_platform,build_mode):
@ -206,12 +189,12 @@ def build_samples(target,ndk_build_param,android_platform,build_mode):
cocos_root = os.path.join(current_dir, "..")
if android_platform is not None:
sdk_root = check_environment_variables_sdk()
if android_platform.isdigit():
android_platform = 'android-'+android_platform
else:
print 'please use vaild android platform'
exit(1)
sdk_root = check_environment_variables_sdk()
if android_platform.isdigit():
android_platform = 'android-'+android_platform
else:
print 'please use vaild android platform'
exit(1)
if build_mode is None:
build_mode = 'debug'
@ -220,28 +203,12 @@ def build_samples(target,ndk_build_param,android_platform,build_mode):
app_android_root = ''
for target in build_targets:
if target == 'hellocpp':
app_android_root = os.path.join(cocos_root, 'samples/Cpp/HelloCpp/proj.android')
elif target == 'testcpp':
app_android_root = os.path.join(cocos_root, 'samples/Cpp/TestCpp/proj.android')
elif target == 'simplegame':
app_android_root = os.path.join(cocos_root, 'samples/Cpp/SimpleGame/proj.android')
elif target == 'assetsmanager':
app_android_root = os.path.join(cocos_root, 'samples/Cpp/AssetsManagerTest/proj.android')
elif target == 'hellolua':
app_android_root = os.path.join(cocos_root, 'samples/Lua/HelloLua/proj.android')
if target == 'testcpp':
app_android_root = os.path.join(cocos_root, 'tests/test-cpp/proj.android')
elif target == 'testlua':
app_android_root = os.path.join(cocos_root, 'samples/Lua/TestLua/proj.android')
elif target == 'cocosdragon':
app_android_root = os.path.join(cocos_root, 'samples/Javascript/CocosDragonJS/proj.android')
elif target == 'crystalcraze':
app_android_root = os.path.join(cocos_root, 'samples/Javascript/CrystalCraze/proj.android')
elif target == 'moonwarriors':
app_android_root = os.path.join(cocos_root, 'samples/Javascript/MoonWarriors/proj.android')
app_android_root = os.path.join(cocos_root, 'tests/test-lua/proj.android')
elif target == 'testjavascript':
app_android_root = os.path.join(cocos_root, 'samples/Javascript/TestJavascript/proj.android')
elif target == 'watermelonwithme':
app_android_root = os.path.join(cocos_root, 'samples/Javascript/WatermelonWithMe/proj.android')
app_android_root = os.path.join(cocos_root, 'tests/test-javascript/proj.android')
else:
print 'unknown target: %s' % target
continue
@ -253,19 +220,40 @@ def build_samples(target,ndk_build_param,android_platform,build_mode):
if __name__ == '__main__':
#parse the params
usage = """usage: %prog [options] target
usage = """
This script is mainy used for building tests built-in with cocos2d-x.
Valid targets are: [hellocpp|testcpp|simplegame|assetsmanager|hellolua|testlua|cocosdragon|crystalcraze|moonwarriors|testjavascript|watermelonwithme]
Usage: %prog [options] target
You can use [all|cpp|lua|jsb], to build all, or all the C++, or all the Lua, or all the JavaScript samples respectevely."""
Valid targets are: [testcpp|testlua|testjavascript]. You can combine them arbitrarily with a whitespace among two valid targets.
You can use [all|cpp|lua|jsb], to build all the tests, or all the c++ tests, or all the Lua tests, or all the JavaScript tests respectevely.
cpp = ['testcpp']
lua = ['testlua']
jsb = ['testjavascript']
all = cpp + lua + jsb // be careful with the all target, it may took a very long time to compile all the projects, do it under your own risk.
If you are new to cocos2d-x, I recommend you start with testcpp, testlua or testjavascript.
You can combine these targets like this:
//1. to build simplegame and assetsmanager
python android-build.py -p 10 testcpp testlua
//2. to build testlua and all the jsb tests
python android-build.py -p 19 testlua jsb
Note: You should install ant to generate apk while building the andriod tests. But it is optional. You can generate apk with eclipse.
"""
parser = OptionParser(usage=usage)
parser.add_option("-n", "--ndk", dest="ndk_build_param",
help='parameter for ndk-build')
help='Parameter for ndk-build')
parser.add_option("-p", "--platform", dest="android_platform",
help='parameter for android-update.Without the parameter,the script just build dynamic library for project. Valid android-platform are:[10|11|12|13|14|15|16|17|18|19]')
help='Parameter for android-update. Without the parameter,the script just build dynamic library for the projects. Valid android-platform are:[10|11|12|13|14|15|16|17|18|19]')
parser.add_option("-b", "--build", dest="build_mode",
help='the build mode for java project,debug[default] or release.Get more information,please refer to http://developer.android.com/tools/building/building-cmdline.html')
help='The build mode for java project,debug[default] or release. Get more information,please refer to http://developer.android.com/tools/building/building-cmdline.html')
(opts, args) = parser.parse_args()
if len(args) == 0:

View File

@ -5,15 +5,13 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libAudio", "..\cocos\audio\
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\cocos\2d\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloCpp", "..\samples\Cpp\HelloCpp\proj.win32\HelloCpp.vcxproj", "{B8BF9E81-35FD-4582-BA1C-B85FA365BABB}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libBox2D", "..\external\Box2D\proj.win32\Box2D.vcxproj", "{929480E7-23C0-4DF6-8456-096D71547116}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libchipmunk", "..\external\chipmunk\proj.win32\chipmunk.vcxproj", "{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libExtensions", "..\extensions\proj.win32\libExtensions.vcxproj", "{21B2C324-891F-48EA-AD1A-5AE13DE12E28}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestCpp", "..\samples\Cpp\TestCpp\proj.win32\TestCpp.vcxproj", "{76A39BB2-9B84-4C65-98A5-654D86B86F2A}"
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestCpp", "..\tests\test-cpp\proj.win32\TestCpp.vcxproj", "{76A39BB2-9B84-4C65-98A5-654D86B86F2A}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libCocosBuilder", "..\cocos\editor-support\cocosbuilder\proj.win32\libCocosBuilder.vcxproj", "{811C0DAB-7B96-4BD3-A154-B7572B58E4AB}"
EndProject
@ -25,29 +23,15 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libNetwork", "..\cocos\netw
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libSpine", "..\cocos\editor-support\spine\proj.win32\libSpine.vcxproj", "{B7C2A162-DEC9-4418-972E-240AB3CBFCAE}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AssetsManagerTest", "..\samples\Cpp\AssetsManagerTest\proj.win32\AssetsManagerTest.vcxproj", "{6D37505F-A890-441D-BD3F-A61E2C0469CE}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBinding", "..\cocos\scripting\javascript\bindings\proj.win32\libJSBinding.vcxproj", "{39379840-825A-45A0-B363-C09FFEF864BD}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestJavascript", "..\samples\Javascript\TestJavascript\proj.win32\TestJavascript.vcxproj", "{D0F06A44-A245-4D13-A498-0120C203B539}"
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestJavascript", "..\tests\test-javascript\proj.win32\TestJavascript.vcxproj", "{D0F06A44-A245-4D13-A498-0120C203B539}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libLocalStorage", "..\cocos\storage\local-storage\proj.win32\libLocalStorage.vcxproj", "{632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CocosDragonJS", "..\samples\Javascript\CocosDragonJS\proj.win32\CocosDragonJS.vcxproj", "{68ED0B4E-2BCA-45D2-9648-CEABEBD3B9D7}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CrystalCraze", "..\samples\Javascript\CrystalCraze\proj.win32\CrystalCraze.vcxproj", "{9A17D9A4-4B11-4E32-94F6-895FF4909EC5}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MoonWarriors", "..\samples\Javascript\MoonWarriors\proj.win32\MoonWarriors.vcxproj", "{1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WatermelonWithMe", "..\samples\Javascript\WatermelonWithMe\proj.win32\WatermelonWithMe.vcxproj", "{BE092D9E-95AE-4F86-84CE-F4519E4F3F15}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblua", "..\cocos\scripting\lua\bindings\liblua.vcxproj", "{DDC3E27F-004D-4DD4-9DD3-931A013D2159}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloLua", "..\samples\Lua\HelloLua\proj.win32\HelloLua.vcxproj", "{13E55395-94A2-4CD9-BFC2-1A051F80C17D}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLua", "..\samples\Lua\TestLua\proj.win32\TestLua.win32.vcxproj", "{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SimpleGame", "..\samples\Cpp\SimpleGame\proj.win32\SimpleGame.vcxproj", "{E0E282F4-8487-452C-BFAB-CB960EB4D22F}"
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLua", "..\tests\test-lua\proj.win32\TestLua.win32.vcxproj", "{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBindingForBuilder", "..\cocos\scripting\javascript\bindings\cocosbuilder\libJSBindingForBuilder.vcxproj", "{F9DA0FC1-651B-457B-962E-A4D61CEBF5FD}"
EndProject

View File

@ -1 +1 @@
db31f01b55bf1ae19e57e71bae6f58a037bfe5b9
caae58ff83f2655d5ea4c19e00a2be17259f8559

View File

@ -1 +0,0 @@
986d41d9721f8079f005999caa9fb0053ea11321

View File

@ -0,0 +1 @@
88d35147fd70ffbc353388aa9424bd2f0645ac95

View File

@ -1,8 +0,0 @@
@echo off
SETLOCAL
:start
mkdir win32-msvc-vs2010-x86
cd win32-msvc-vs2010-x86
cmake -G "Visual Studio 10" ../..
pause

View File

@ -111,7 +111,7 @@ cocos2d.cpp \
TGAlib.cpp \
TransformUtils.cpp \
ZipUtils.cpp \
platform/CCEGLViewProtocol.cpp \
platform/CCGLViewProtocol.cpp \
platform/CCFileUtils.cpp \
platform/CCSAXParser.cpp \
platform/CCThread.cpp \

View File

@ -75,7 +75,7 @@ bool Configuration::init()
_valueDict["cocos2d.x.compiled_with_gl_state_cache"] = Value(true);
#endif
#ifdef DEBUG
#if COCOS2D_DEBUG
_valueDict["cocos2d.x.build_type"] = Value("DEBUG");
#else
_valueDict["cocos2d.x.build_type"] = Value("RELEASE");

View File

@ -764,7 +764,7 @@ CC_DEPRECATED_ATTRIBUTE typedef TMXTiledMap CCTMXTiledMap;
CC_DEPRECATED_ATTRIBUTE typedef TileMapAtlas CCTileMapAtlas;
CC_DEPRECATED_ATTRIBUTE typedef Timer CCTimer;
CC_DEPRECATED_ATTRIBUTE typedef Scheduler CCScheduler;
CC_DEPRECATED_ATTRIBUTE typedef EGLView CCEGLView;
CC_DEPRECATED_ATTRIBUTE typedef GLView CCEGLView;
CC_DEPRECATED_ATTRIBUTE typedef Component CCComponent;
CC_DEPRECATED_ATTRIBUTE typedef AffineTransform CCAffineTransform;

View File

@ -55,7 +55,7 @@ THE SOFTWARE.
#include "kazmath/GL/matrix.h"
#include "CCProfiling.h"
#include "platform/CCImage.h"
#include "CCEGLView.h"
#include "CCGLView.h"
#include "CCConfiguration.h"
#include "CCEventDispatcher.h"
#include "CCEventCustom.h"
@ -351,7 +351,7 @@ void Director::calculateDeltaTime()
_deltaTime = MAX(0, _deltaTime);
}
#ifdef DEBUG
#if COCOS2D_DEBUG
// If we are debugging our code, prevent big delta time
if (_deltaTime > 0.2f)
{
@ -365,7 +365,7 @@ float Director::getDeltaTime() const
{
return _deltaTime;
}
void Director::setOpenGLView(EGLView *openGLView)
void Director::setOpenGLView(GLView *openGLView)
{
CCASSERT(openGLView, "opengl view should not be null");
@ -376,9 +376,10 @@ void Director::setOpenGLView(EGLView *openGLView)
conf->gatherGPUInfo();
CCLOG("%s\n",conf->getInfo().c_str());
// EAGLView is not a Object
delete _openGLView; // [openGLView_ release]
if(_openGLView)
_openGLView->release();
_openGLView = openGLView;
_openGLView->retain();
// set size
_winSizeInPoints = _openGLView->getDesignResolutionSize();
@ -941,7 +942,8 @@ void Director::createStatsLabel()
Secondly, the size of this image is 480*320, to display the FPS label with correct size,
a factor of design resolution ratio of 480x320 is also needed.
*/
float factor = EGLView::getInstance()->getDesignResolutionSize().height / 320.0f;
auto glview = Director::getInstance()->getOpenGLView();
float factor = glview->getDesignResolutionSize().height / 320.0f;
_FPSLabel = LabelAtlas::create();
_FPSLabel->retain();

View File

@ -49,7 +49,7 @@ NS_CC_BEGIN
/* Forward declarations. */
class LabelAtlas;
class Scene;
class EGLView;
class GLView;
class DirectorDelegate;
class Node;
class Scheduler;
@ -143,12 +143,12 @@ public:
/** seconds per frame */
inline float getSecondsPerFrame() { return _secondsPerFrame; }
/** Get the EGLView, where everything is rendered
/** Get the GLView, where everything is rendered
* @js NA
* @lua NA
*/
inline EGLView* getOpenGLView() { return _openGLView; }
void setOpenGLView(EGLView *openGLView);
inline GLView* getOpenGLView() { return _openGLView; }
void setOpenGLView(GLView *openGLView);
TextureCache* getTextureCache() const;
@ -202,7 +202,7 @@ public:
/** returns visible size of the OpenGL view in points.
* the value is equal to getWinSize if don't invoke
* EGLView::setDesignResolutionSize()
* GLView::setDesignResolutionSize()
*/
Size getVisibleSize() const;
@ -422,8 +422,8 @@ protected:
/* delta time since last tick to main loop */
float _deltaTime;
/* The EGLView, where everything is rendered */
EGLView *_openGLView;
/* The GLView, where everything is rendered */
GLView *_openGLView;
//texture cache belongs to this director
TextureCache *_textureCache;
@ -492,8 +492,8 @@ protected:
/* Console for the director */
Console *_console;
// EGLViewProtocol will recreate stats labels to fit visible rect
friend class EGLViewProtocol;
// GLViewProtocol will recreate stats labels to fit visible rect
friend class GLViewProtocol;
};
/**

View File

@ -815,7 +815,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event)
if (event->isStopped())
{
updateListeners(event);
return false;
return true;
}
return false;

View File

@ -60,7 +60,7 @@ private:
EventCode _eventCode;
std::vector<Touch*> _touches;
friend class EGLViewProtocol;
friend class GLViewProtocol;
};

View File

@ -85,6 +85,7 @@ void Font::setCurrentGlyphCollection(GlyphCollection glyphs, const char *customG
break;
}
_usedGlyphs = glyphs;
}
const char * Font::getCurrentGlyphCollection() const
@ -99,7 +100,7 @@ const char * Font::getCurrentGlyphCollection() const
}
}
unsigned short int * Font::getUTF16Text(const char *text, int &outNumLetters) const
unsigned short* Font::getUTF16Text(const char *text, int &outNumLetters) const
{
unsigned short* utf16String = cc_utf8_to_utf16(text);
@ -115,7 +116,7 @@ int Font::getUTF16TextLenght(unsigned short int *text) const
return cc_wcslen(text);
}
unsigned short int * Font::trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const
unsigned short * Font::trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const
{
if ( newBegin < 0 || newEnd <= 0 )
return 0;
@ -141,11 +142,6 @@ unsigned short int * Font::trimUTF16Text(unsigned short int *text, int newBegin
return trimmedString;
}
Rect Font::getRectForChar(unsigned short theChar) const
{
return Rect::ZERO;
}
NS_CC_END

View File

@ -44,15 +44,13 @@ public:
virtual int* getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const = 0;
virtual const char* getCurrentGlyphCollection() const;
virtual int getLetterPadding() const { return 0; }
virtual unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const { return 0; }
virtual int getFontMaxHeight() const { return 0; }
virtual Rect getRectForChar(unsigned short theChar) const;
virtual int getUTF16TextLenght(unsigned short int *text) const;
virtual unsigned short int * getUTF16Text(const char *text, int &outNumLetters) const;
virtual unsigned short int * trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const;
virtual unsigned short * getUTF16Text(const char *text, int &outNumLetters) const;
virtual unsigned short * trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const;
protected:

View File

@ -48,7 +48,7 @@ _currentPageData(nullptr)
_currentPage = 0;
_currentPageOrigX = 0;
_currentPageOrigY = 0;
_letterPadding = 5;
_letterPadding = 0;
_makeDistanceMap = fontTTf->isDistanceFieldEnabled();
if(_makeDistanceMap)
@ -116,6 +116,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
std::unordered_map<unsigned short, FontLetterDefinition> fontDefs;
int length = cc_wcslen(utf16String);
float offsetAdjust = _letterPadding / 2;
//find out new letter
for (int i = 0; i < length; ++i)
{
@ -129,15 +130,12 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
Rect tempRect;
FontLetterDefinition tempDef;
tempDef.anchorX = 0.0f;
tempDef.anchorY = 1.0f;
FontLetterDefinition tempDef;
if (!fontTTf->getBBOXFotChar(utf16String[i], tempRect,tempDef.xAdvance))
{
tempDef.validDefinition = false;
tempDef.letteCharUTF16 = utf16String[i];
tempDef.commonLineHeight = 0;
tempDef.width = 0;
tempDef.height = 0;
tempDef.U = 0;
@ -151,11 +149,10 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
{
tempDef.validDefinition = true;
tempDef.letteCharUTF16 = utf16String[i];
tempDef.width = tempRect.size.width + _letterPadding;
tempDef.height = _currentPageLineHeight - 1;
tempDef.offsetX = tempRect.origin.x;
tempDef.offsetY = tempRect.origin.y;
tempDef.commonLineHeight = _currentPageLineHeight;
tempDef.width = tempRect.size.width + _letterPadding;
tempDef.height = tempRect.size.height + _letterPadding;
tempDef.offsetX = tempRect.origin.x + offsetAdjust;
tempDef.offsetY = _commonLineHeight + tempRect.origin.y - offsetAdjust;
}
fontDefs[utf16String[i]] = tempDef;
}
@ -171,8 +168,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
{
if(it->second.validDefinition)
{
_currentPageOrigX += _letterPadding;
glyphWidth = it->second.width - _letterPadding;
glyphWidth = it->second.width;
if (_currentPageOrigX + glyphWidth > PAGE_WIDTH)
{
@ -196,7 +192,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
}
fontTTf->renderCharAt(it->second.letteCharUTF16,_currentPageOrigX,_currentPageOrigY,_currentPageData,PAGE_WIDTH);
it->second.U = _currentPageOrigX - 1;
it->second.U = _currentPageOrigX;
it->second.V = _currentPageOrigY;
it->second.textureID = _currentPage;
// take from pixels to points
@ -209,7 +205,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
glyphWidth = 0;
_fontLetterDefinitions[it->second.letteCharUTF16] = it->second;
_currentPageOrigX += glyphWidth;
_currentPageOrigX += glyphWidth + 1;
}
if(fontDefs.size() > 0)
_atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, pixelFormat, PAGE_WIDTH, PAGE_HEIGHT, _pageContentSize );
@ -234,8 +230,6 @@ float FontAtlas::getCommonLineHeight() const
void FontAtlas::setCommonLineHeight(float newHeight)
{
if(_makeDistanceMap)
newHeight += 2 * FontFreeType::DistanceMapSpread;
_commonLineHeight = newHeight;
}
@ -244,4 +238,4 @@ const Font * FontAtlas::getFont() const
return _font;
}
NS_CC_END
NS_CC_END

View File

@ -45,9 +45,6 @@ struct FontLetterDefinition
float offsetX;
float offsetY;
int textureID;
float commonLineHeight;
float anchorX;
float anchorY;
bool validDefinition;
int xAdvance;
};

View File

@ -218,7 +218,7 @@ bool FontAtlasCache::releaseFontAtlas(FontAtlas *atlas)
{
if ( item.second == atlas )
{
if( atlas->isSingleReference() )
if (atlas->getReferenceCount() == 1)
{
_atlasMap.erase(item.first);
}

View File

@ -121,11 +121,6 @@ int * FontCharMap::getHorizontalKerningForTextUTF16(unsigned short *text, int &o
return sizes;
}
Rect FontCharMap::getRectForChar(unsigned short theChar) const
{
return _charRect;
}
FontAtlas * FontCharMap::createFontAtlas()
{
FontAtlas *tempAtlas = new FontAtlas(*this);
@ -141,8 +136,6 @@ FontAtlas * FontCharMap::createFontAtlas()
FontLetterDefinition tempDefinition;
tempDefinition.textureID = 0;
tempDefinition.anchorX = 0.5f;
tempDefinition.anchorY = 0.5f;
tempDefinition.offsetX = 0.0f;
tempDefinition.offsetY = 0.0f;
tempDefinition.validDefinition = true;

View File

@ -38,7 +38,6 @@ public:
static FontCharMap * create(const std::string& plistFile);
virtual int* getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const override;
virtual Rect getRectForChar(unsigned short theChar) const override;
virtual FontAtlas *createFontAtlas() override;
protected:
@ -47,7 +46,6 @@ protected:
,_mapStartChar(startCharMap)
,_itemWidth(itemWidth)
,_itemHeight(itemHeight)
,_charRect(0,0,itemWidth,itemHeight)
{}
/**
* @js NA
@ -61,7 +59,6 @@ private:
int _itemWidth;
int _itemHeight;
Rect _charRect;
};
NS_CC_END

View File

@ -104,28 +104,6 @@ int FontFNT::getHorizontalKerningForChars(unsigned short firstChar, unsigned sh
return ret;
}
Rect FontFNT::getRectForCharInternal(unsigned short theChar) const
{
Rect retRect;
ccBMFontDef fontDef;
tFontDefHashElement *element = nullptr;
unsigned int key = theChar;
HASH_FIND_INT(_configuration->_fontDefDictionary, &key, element);
if (element)
{
retRect = element->fontDef.rect;
}
return retRect;
}
Rect FontFNT::getRectForChar(unsigned short theChar) const
{
return getRectForCharInternal(theChar);
}
FontAtlas * FontFNT::createFontAtlas()
{
FontAtlas *tempAtlas = new FontAtlas(*this);

View File

@ -40,7 +40,6 @@ public:
static FontFNT * create(const std::string& fntFilePath);
virtual int* getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const override;
virtual Rect getRectForChar(unsigned short theChar) const override;
virtual FontAtlas *createFontAtlas() override;
protected:
@ -56,7 +55,6 @@ protected:
private:
int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const;
Rect getRectForCharInternal(unsigned short theChar) const;
CCBMFontConfiguration * _configuration;

View File

@ -85,8 +85,7 @@ FT_Library FontFreeType::getFTLibrary()
}
FontFreeType::FontFreeType()
: _fontRef(nullptr),
_letterPadding(5)
: _fontRef(nullptr)
,_distanceFieldEnabled(false)
{
}
@ -137,7 +136,9 @@ FontAtlas * FontFreeType::createFontAtlas()
FontAtlas *atlas = new FontAtlas(*this);
if (_usedGlyphs != GlyphCollection::DYNAMIC)
{
atlas->prepareLetterDefinitions(cc_utf8_to_utf16(getCurrentGlyphCollection()));
unsigned short* utf16 = cc_utf8_to_utf16(getCurrentGlyphCollection());
atlas->prepareLetterDefinitions(utf16);
CC_SAFE_DELETE_ARRAY(utf16);
}
this->release();
return atlas;
@ -252,11 +253,6 @@ unsigned char * FontFreeType::getGlyphBitmap(unsigned short theChar, int &outWid
return _fontRef->glyph->bitmap.buffer;
}
int FontFreeType::getLetterPadding() const
{
return _letterPadding;
}
unsigned char * makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height)
{
unsigned int pixelAmount = (width + 2 * FontFreeType::DistanceMapSpread) * (height + 2 * FontFreeType::DistanceMapSpread);
@ -340,8 +336,6 @@ unsigned char * makeDistanceMap( unsigned char *img, unsigned int width, unsigne
void FontFreeType::setDistanceFieldEnabled(bool distanceFieldEnabled)
{
if(distanceFieldEnabled)
_letterPadding += 2 * DistanceMapSpread;
_distanceFieldEnabled = distanceFieldEnabled;
}

View File

@ -54,7 +54,6 @@ public:
unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const override;
virtual int getFontMaxHeight() const override;
virtual int getLetterPadding() const override;
bool getBBOXFotChar(unsigned short theChar, Rect &outRect,int &xAdvance) const;
@ -74,7 +73,6 @@ private:
static FT_Library _FTlibrary;
static bool _FTInitialized;
FT_Face _fontRef;
int _letterPadding;
std::string _fontName;
Data _ttfData;
bool _distanceFieldEnabled;

View File

@ -52,7 +52,7 @@ Label* Label::create()
Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment /* = TextHAlignment::CENTER */, int lineSize /* = 0 */)
{
Label *ret = new Label();
Label *ret = new Label(nullptr,alignment);
if (!ret)
return nullptr;
@ -61,7 +61,8 @@ Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text,
{
if(ttfConfig.distanceFieldEnabled)
ret->setFontSize(ttfConfig.fontSize);
ret->setString(text,alignment,lineSize);
ret->setWidth(lineSize);
ret->setString(text);
ret->autorelease();
return ret;
}
@ -80,14 +81,15 @@ Label* Label::createWithTTF(const std::string& text, const std::string& fontFile
Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment /* = TextHAlignment::CENTER */, int lineSize /* = 0 */)
{
Label *ret = new Label();
Label *ret = new Label(nullptr,alignment);
if (!ret)
return nullptr;
if (ret->setBMFontFilePath(bmfontFilePath))
{
ret->setString(text,alignment,lineSize);
ret->setWidth(lineSize);
ret->setString(text);
ret->autorelease();
return ret;
}
@ -195,7 +197,7 @@ Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,b
, _originalUTF16String(nullptr)
, _horizontalKernings(nullptr)
, _fontAtlas(atlas)
, _isOpacityModifyRGB(true)
, _isOpacityModifyRGB(false)
, _useDistanceField(useDistanceField)
, _useA8Shader(useA8Shader)
, _fontSize(0)
@ -271,8 +273,9 @@ bool Label::initWithFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled /* = fa
if (_fontAtlas)
{
_commonLineHeight = _fontAtlas->getCommonLineHeight();
if (_currentUTF16String)
{
if(_currentUTF16String)
{
resetCurrentString();
alignText();
}
}
@ -304,34 +307,20 @@ bool Label::setBMFontFilePath(const std::string& bmfontFilePath)
return initWithFontAtlas(newAtlas);
}
bool Label::setString(const std::string& text, const TextHAlignment& alignment /* = TextHAlignment::CENTER */, float lineWidth /* = -1 */, bool lineBreakWithoutSpaces /* = false */)
void Label::setString(const std::string& text)
{
if (!_fontAtlas || _commonLineHeight <= 0)
return false;
// carloX
// reset the string
resetCurrentString();
if(lineWidth >= 0)
{
_width = lineWidth;
}
_alignment = alignment;
_lineBreakWithoutSpaces = lineBreakWithoutSpaces;
return ;
unsigned short* utf16String = cc_utf8_to_utf16(text.c_str());
if(!utf16String)
return false;
return ;
_originalUTF8String = text;
setCurrentString(utf16String);
setOriginalString(utf16String);
// align text
alignText();
// done here
return true;
}
void Label::setAlignment(TextHAlignment alignment)
@ -342,11 +331,14 @@ void Label::setAlignment(TextHAlignment alignment)
// store
_alignment = alignment;
// reset the string
resetCurrentString();
// need to align text again
alignText();
if (_currentUTF16String)
{
// reset the string
resetCurrentString();
// need to align text again
alignText();
}
}
}
@ -357,12 +349,14 @@ void Label::setWidth(float width)
// store
_width = width;
// reset the string
resetCurrentString();
// need to align text again
alignText();
if (_currentUTF16String)
{
// reset the string
resetCurrentString();
// need to align text again
alignText();
}
}
}
@ -374,7 +368,11 @@ void Label::setLineBreakWithoutSpace(bool breakWithoutSpace)
_lineBreakWithoutSpaces = breakWithoutSpace;
// need to align text again
alignText();
if(_currentUTF16String)
{
resetCurrentString();
alignText();
}
}
}
@ -430,7 +428,7 @@ float Label::getScaleX() const
}
void Label::alignText()
{
{
if(_textureAtlas)
_textureAtlas->removeAllQuads();
_fontAtlas->prepareLetterDefinitions(_currentUTF16String);
@ -473,6 +471,8 @@ void Label::alignText()
insertQuadFromSprite(_reusedLetter,vaildIndex++);
}
}
updateColor();
}
bool Label::computeHorizontalKernings(unsigned short int *stringToRender)
@ -703,82 +703,19 @@ Sprite * Label::getLetter(int ID)
return nullptr;
}
float Label::getLetterPosXLeft( int index ) const
{
return _lettersInfo[index].position.x * _scaleX;
}
float Label::getLetterPosXRight( int index ) const
{
return (_lettersInfo[index].position.x + _lettersInfo[index].contentSize.width) * _scaleX;
}
int Label::getCommonLineHeight() const
{
return _commonLineHeight;
}
int Label::getKerningInString(int hintPositionInString) const
{
if (_horizontalKernings)
{
return (_horizontalKernings[hintPositionInString]);
}
else
{
return -1;
}
}
int Label::getXOffsetForChar(unsigned short c) const
{
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition);
if (!validDefinition)
return -1;
return (tempDefinition.offsetX);
}
int Label::getYOffsetForChar(unsigned short c) const
{
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition);
if (!validDefinition)
return -1;
return (tempDefinition.offsetY);
}
int Label::getAdvanceForChar(unsigned short c, int hintPositionInString) const
{
if (_horizontalKernings)
{
// not that advance contains the X offset already
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition);
if (!validDefinition)
return -1;
return tempDefinition.xAdvance;
}
else
{
return -1;
}
}
Rect Label::getRectForChar(unsigned short c) const
{
return _fontAtlas->getFont()->getRectForChar(c);
}
// string related stuff
int Label::getStringNumLines() const
{
int quantityOfLines = 1;
unsigned int stringLen = _currentUTF16String ? cc_wcslen(_currentUTF16String) : 0;
unsigned int stringLen = _currentUTF16String ? cc_wcslen(_currentUTF16String) : -1;
if (stringLen < 1)
return stringLen;
if (stringLen == 0)
return (-1);
@ -800,17 +737,12 @@ int Label::getStringLenght() const
return _currentUTF16String ? cc_wcslen(_currentUTF16String) : 0;
}
unsigned short Label::getCharAtStringPosition(int position) const
{
return _currentUTF16String[position];
}
unsigned short * Label::getUTF8String() const
unsigned short * Label::getUTF16String() const
{
return _currentUTF16String;
}
void Label::assignNewUTF8String(unsigned short *newString)
void Label::assignNewUTF16String(unsigned short *newString)
{
setCurrentString(newString);
}
@ -831,17 +763,6 @@ bool Label::breakLineWithoutSpace() const
return _lineBreakWithoutSpaces;
}
Size Label::getLabelContentSize() const
{
return getContentSize();
}
void Label::setLabelContentSize(const Size &newSize)
{
setContentSize(newSize);
}
// RGBA protocol

View File

@ -28,9 +28,9 @@
#define _COCOS2D_CCLABEL_H_
#include "CCSpriteBatchNode.h"
#include "CCLabelTextFormatProtocol.h"
#include "ccTypes.h"
#include "renderer/CCCustomCommand.h"
#include "CCFontAtlas.h"
NS_CC_BEGIN
@ -50,9 +50,13 @@ enum class LabelEffect {
GLOW
};
//fwd
struct FontLetterDefinition;
class FontAtlas;
struct LetterInfo
{
FontLetterDefinition def;
Point position;
Size contentSize;
};
typedef struct _ttfConfig
{
@ -72,15 +76,15 @@ typedef struct _ttfConfig
{}
}TTFConfig;
class CC_DLL Label : public SpriteBatchNode, public LabelTextFormatProtocol
class CC_DLL Label : public SpriteBatchNode, public LabelProtocol
{
public:
static Label* create();
CC_DEPRECATED_ATTRIBUTE static Label* createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0, bool useDistanceField = false);
static Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment = TextHAlignment::CENTER, int lineWidth = 0);
CC_DEPRECATED_ATTRIBUTE static Label* createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::LEFT, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0, bool useDistanceField = false);
static Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment = TextHAlignment::LEFT, int lineWidth = 0);
static Label* createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment = TextHAlignment::CENTER, int lineWidth = 0);
static Label* createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment = TextHAlignment::LEFT, int lineWidth = 0);
static Label * createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
static Label * createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
@ -94,7 +98,7 @@ public:
bool setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
bool setCharMap(const std::string& plistFile);
bool setString(const std::string& text, const TextHAlignment& alignment = TextHAlignment::CENTER, float lineWidth = -1, bool lineBreakWithoutSpaces = false);
virtual void setString(const std::string& text) override;
//only support for TTF
void setLabelEffect(LabelEffect effect,const Color3B& effectColor);
@ -113,49 +117,42 @@ public:
virtual void setColor(const Color3B& color) override;
// CCLabelTextFormat protocol implementation
virtual std::vector<LetterInfo> *getLettersInfo() override { return &_lettersInfo; };
virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) override;
virtual bool recordPlaceholderInfo(int spriteIndex) override;
virtual float getLetterPosXLeft( int index ) const override;
virtual float getLetterPosXRight( int index ) const override;
virtual std::vector<LetterInfo> *getLettersInfo() { return &_lettersInfo; };
virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex);
virtual bool recordPlaceholderInfo(int spriteIndex);
virtual Sprite * getLetter(int ID) override;
virtual Sprite * getLetter(int ID);
// font related stuff
virtual int getCommonLineHeight() const override;
virtual int getKerningInString(int hintPositionInString) const override;
virtual int getXOffsetForChar(unsigned short c) const override;
virtual int getYOffsetForChar(unsigned short c) const override;
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const override;
virtual Rect getRectForChar(unsigned short c) const override;
virtual int getCommonLineHeight() const;
virtual int* getKernings() const { return _horizontalKernings;}
// string related stuff
virtual int getStringNumLines() const override;
virtual int getStringLenght() const override;
virtual unsigned short getCharAtStringPosition(int position) const override;
virtual unsigned short * getUTF8String() const override;
virtual void assignNewUTF8String(unsigned short *newString) override;
virtual TextHAlignment getTextAlignment() const override;
virtual int getStringNumLines() const;
virtual int getStringLenght() const;
virtual unsigned short * getUTF16String() const;
virtual void assignNewUTF16String(unsigned short *newString);
virtual TextHAlignment getTextAlignment() const;
// label related stuff
virtual float getMaxLineWidth() const override;
virtual bool breakLineWithoutSpace() const override;
virtual Size getLabelContentSize() const override;
virtual void setLabelContentSize(const Size &newSize) override;
virtual float getMaxLineWidth() const;
virtual bool breakLineWithoutSpace() const;
// carloX
virtual const std::string& getString() const { static std::string _ret("not implemented"); return _ret; }
virtual const std::string& getString() const override { return _originalUTF8String; }
void addChild(Node * child, int zOrder=0, int tag=0) override;
virtual std::string getDescription() const override;
virtual void draw(void) override;
virtual void onDraw();
virtual FontAtlas* getFontAtlas() const {return _fontAtlas;}
private:
/**
* @js NA
*/
Label(FontAtlas *atlas = nullptr, TextHAlignment alignment = TextHAlignment::CENTER, bool useDistanceField = false,bool useA8Shader = false);
Label(FontAtlas *atlas = nullptr, TextHAlignment alignment = TextHAlignment::LEFT, bool useDistanceField = false,bool useA8Shader = false);
/**
* @js NA
* @lua NA
@ -189,6 +186,7 @@ private:
TextHAlignment _alignment;
unsigned short int * _currentUTF16String;
unsigned short int * _originalUTF16String;
std::string _originalUTF8String;
int * _horizontalKernings;
FontAtlas * _fontAtlas;
bool _isOpacityModifyRGB;

View File

@ -1,87 +0,0 @@
/****************************************************************************
Copyright (c) 2013 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
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 _CCLabelTextFormatProtocol_h_
#define _CCLabelTextFormatProtocol_h_
#include <vector>
#include "CCFontAtlas.h"
#include "CCGeometry.h"
#include "ccTypes.h"
NS_CC_BEGIN
class Sprite;
struct LetterInfo
{
FontLetterDefinition def;
Point position;
Size contentSize;
bool visible;
};
class CC_DLL LabelTextFormatProtocol
{
public:
virtual ~LabelTextFormatProtocol() {}
virtual bool recordLetterInfo(const Point& point,unsigned short int theChar, int spriteIndex) = 0;
virtual bool recordPlaceholderInfo(int spriteIndex) = 0;
virtual std::vector<LetterInfo> *getLettersInfo() = 0;
virtual float getLetterPosXLeft(int index) const = 0;
virtual float getLetterPosXRight(int index) const = 0;
// sprite related stuff
virtual Sprite *getLetter(int ID) = 0;
// font related stuff
virtual int getCommonLineHeight() const = 0;
virtual int getKerningInString(int hintPositionInString) const = 0;
virtual int getXOffsetForChar(unsigned short c) const = 0;
virtual int getYOffsetForChar(unsigned short c) const = 0;
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const = 0;
virtual Rect getRectForChar(unsigned short c) const = 0;
// string related stuff
virtual int getStringNumLines() const = 0;
virtual int getStringLenght() const = 0;
virtual unsigned short getCharAtStringPosition(int position) const = 0;
virtual unsigned short * getUTF8String() const = 0;
virtual void assignNewUTF8String(unsigned short *newString) = 0;
virtual TextHAlignment getTextAlignment() const = 0;
// label related stuff
virtual float getMaxLineWidth() const = 0;
virtual bool breakLineWithoutSpace() const = 0;
virtual cocos2d::Size getLabelContentSize() const = 0;
virtual void setLabelContentSize(const Size &newSize) = 0;
};
NS_CC_END
#endif

View File

@ -28,15 +28,16 @@
#include "ccUTF8.h"
#include "CCLabelTextFormatter.h"
#include "CCDirector.h"
#include "CCLabel.h"
using namespace std;
NS_CC_BEGIN
bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
bool LabelTextFormatter::multilineText(Label *theLabel)
{
int strLen = theLabel->getStringLenght();
auto strWhole = theLabel->getUTF8String();
auto strWhole = theLabel->getUTF16String();
vector<unsigned short> multiline_string;
multiline_string.reserve( strLen );
@ -53,6 +54,9 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
std::vector<LetterInfo> *leterInfo = theLabel->getLettersInfo();
int tIndex = 0;
float scalsX = theLabel->getScaleX();
float lineWidth = theLabel->getMaxLineWidth();
bool breakLineWithoutSpace = theLabel->breakLineWithoutSpace();
for (int j = 0; j+skip < strLen; j++)
{
@ -94,7 +98,7 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
if (!isStartOfWord)
{
startOfWord = theLabel->getLetterPosXLeft( tIndex );
startOfWord = info->position.x * scalsX;
isStartOfWord = true;
}
@ -115,10 +119,11 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
continue;
}
float posRight = (info->position.x + info->contentSize.width) * scalsX;
// Out of bounds.
if (theLabel->getLetterPosXRight( tIndex ) - startOfLine > theLabel->getMaxLineWidth())
if (posRight - startOfLine > lineWidth)
{
if (!theLabel->breakLineWithoutSpace())
if (!breakLineWithoutSpace)
{
last_word.push_back(character);
@ -168,23 +173,25 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
}
strNew[size] = 0;
theLabel->assignNewUTF8String(strNew);
theLabel->assignNewUTF16String(strNew);
return true;
}
bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel)
bool LabelTextFormatter::alignText(Label *theLabel)
{
int i = 0;
int lineNumber = 0;
int strLen = cc_wcslen(theLabel->getUTF8String());
int strLen = cc_wcslen(theLabel->getUTF16String());
vector<unsigned short> lastLine;
std::vector<LetterInfo> *leterInfo = theLabel->getLettersInfo();
auto strWhole = theLabel->getUTF16String();
for (int ctr = 0; ctr <= strLen; ++ctr)
{
unsigned short int currentChar = theLabel->getCharAtStringPosition(ctr);
{
unsigned short currentChar = strWhole[ctr];
if (currentChar == '\n' || currentChar == 0)
{
float lineWidth = 0.0f;
@ -202,16 +209,16 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel)
LetterInfo* info = &leterInfo->at( index );
if(info->def.validDefinition == false)
continue;
lineWidth = info->position.x + info->contentSize.width /2.0f;
lineWidth = info->position.x + info->contentSize.width;
float shift = 0;
switch (theLabel->getTextAlignment())
{
case TextHAlignment::CENTER:
shift = theLabel->getLabelContentSize().width/2.0f - lineWidth/2.0f;
shift = theLabel->getContentSize().width/2.0f - lineWidth/2.0f;
break;
case TextHAlignment::RIGHT:
shift = theLabel->getLabelContentSize().width - lineWidth;
shift = theLabel->getContentSize().width - lineWidth;
break;
default:
break;
@ -227,7 +234,7 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel)
info = &leterInfo->at( index );
if(info)
{
info->position = info->position + Point(shift, 0.0f);
info->position.x += shift;
}
}
}
@ -245,7 +252,7 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel)
return true;
}
bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
bool LabelTextFormatter::createStringSprites(Label *theLabel)
{
// check for string
unsigned int stringLen = theLabel->getStringLenght();
@ -259,37 +266,42 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
unsigned short prev = -1;
Size tmpSize = Size::ZERO;
int longestLine = 0;
unsigned int totalHeight = 0;
int quantityOfLines = theLabel->getStringNumLines();
int commonLineHeight = theLabel->getCommonLineHeight();
totalHeight = commonLineHeight * quantityOfLines;
nextFontPositionY = 0 - (commonLineHeight - totalHeight);
totalHeight = commonLineHeight * quantityOfLines;
nextFontPositionY = totalHeight;
Rect rect;
Rect charRect;
int charXOffset = 0;
int charYOffset = 0;
int charAdvance = 0;
auto strWhole = theLabel->getUTF16String();
FontAtlas* fontAtlas = theLabel->getFontAtlas();
FontLetterDefinition tempDefinition;
auto kernings = theLabel->getKernings();
for (unsigned int i = 0; i < stringLen; i++)
{
// get the current character
unsigned short c = theLabel->getCharAtStringPosition(i);
charXOffset = theLabel->getXOffsetForChar(c);
charYOffset = theLabel->getYOffsetForChar(c);
charAdvance = theLabel->getAdvanceForChar(c, i);
charRect = theLabel->getRectForChar(c);
int kerningAmount = theLabel->getKerningInString(i);
unsigned short c = strWhole[i];
if (fontAtlas->getLetterDefinitionForChar(c, tempDefinition))
{
charXOffset = tempDefinition.offsetX;
charYOffset = tempDefinition.offsetY;
charAdvance = tempDefinition.xAdvance;
}
else
{
charXOffset = -1;
charYOffset = -1;
charAdvance = -1;
}
if (c == '\n')
{
@ -300,11 +312,8 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
continue;
}
// See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!)
int yOffset = commonLineHeight - charYOffset;
Point fontPos = Point((float)nextFontPositionX + charXOffset + kerningAmount,
(float)nextFontPositionY + yOffset);
Point fontPos = Point((float)nextFontPositionX + charXOffset + kernings[i],
(float)nextFontPositionY - charYOffset);
if( theLabel->recordLetterInfo(CC_POINT_PIXELS_TO_POINTS(fontPos),c,i) == false)
{
@ -313,7 +322,7 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
}
// update kerning
nextFontPositionX += charAdvance + kerningAmount;
nextFontPositionX += charAdvance + kernings[i];
prev = c;
if (longestLine < nextFontPositionX)
@ -322,12 +331,13 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
}
}
float lastCharWidth = tempDefinition.width * CC_CONTENT_SCALE_FACTOR();
// If the last character processed has an xAdvance which is less that the width of the characters image, then we need
// to adjust the width of the string to take this into account, or the character will overlap the end of the bounding
// box
if (charAdvance < charRect.size.width)
if(charAdvance < lastCharWidth)
{
tmpSize.width = longestLine + charRect.size.width - charAdvance;
tmpSize.width = longestLine - charAdvance + lastCharWidth;
}
else
{
@ -335,7 +345,7 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
}
tmpSize.height = totalHeight;
theLabel->setLabelContentSize(CC_SIZE_PIXELS_TO_POINTS(tmpSize));
theLabel->setContentSize(CC_SIZE_PIXELS_TO_POINTS(tmpSize));
return true;
}

View File

@ -26,17 +26,17 @@
#ifndef _CCLabelTextFormatter_h_
#define _CCLabelTextFormatter_h_
#include "CCLabelTextFormatProtocol.h"
NS_CC_BEGIN
class Label;
class CC_DLL LabelTextFormatter
{
public:
static bool multilineText(LabelTextFormatProtocol *theLabel);
static bool alignText(LabelTextFormatProtocol *theLabel);
static bool createStringSprites(LabelTextFormatProtocol *theLabel);
static bool multilineText(Label *theLabel);
static bool alignText(Label *theLabel);
static bool createStringSprites(Label *theLabel);
};

View File

@ -100,7 +100,7 @@ void ParallaxNode::addChild(Node *child, int z, const Point& ratio, const Point&
obj->setChild(child);
ccArrayAppendObjectWithResize(_parallaxArray, (Object*)obj);
Point pos = _position;
Point pos = this->absolutePosition();
pos.x = -pos.x + pos.x * ratio.x + offset.x;
pos.y = -pos.y + pos.y * ratio.y + offset.y;
child->setPosition(pos);

View File

@ -290,7 +290,7 @@ void ShaderCache::loadDefaultShader(GLProgram *p, int type)
break;
case kShaderType_PositionTextureColorAlphaTest:
p->initWithVertexShaderByteArray(ccPositionTextureColor_noMVP_vert, ccPositionTextureColorAlphaTest_frag);
p->initWithVertexShaderByteArray(ccPositionTextureColor_vert, ccPositionTextureColorAlphaTest_frag);
p->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION);
p->addAttribute(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR);

View File

@ -293,7 +293,7 @@ void SpriteFrameCache::removeUnusedSpriteFrames()
for (auto iter = _spriteFrames.begin(); iter != _spriteFrames.end(); ++iter)
{
SpriteFrame* spriteFrame = iter->second;
if( spriteFrame->retainCount() == 1 )
if( spriteFrame->getReferenceCount() == 1 )
{
toRemoveFrames.push_back(iter->first);
CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", iter->first.c_str());

View File

@ -250,8 +250,9 @@ public:
inline void setStoringCharacters(bool storingCharacters) { _storingCharacters = storingCharacters; };
/// properties
inline ValueMap getProperties() const { return _properties; };
inline void setProperties(ValueMap properties) {
inline const ValueMap& getProperties() const { return _properties; }
inline ValueMap& getProperties() { return _properties; }
inline void setProperties(const ValueMap& properties) {
_properties = properties;
};

View File

@ -26,7 +26,7 @@ THE SOFTWARE.
#include "CCTextFieldTTF.h"
#include "CCDirector.h"
#include "CCEGLView.h"
#include "CCGLView.h"
NS_CC_BEGIN
@ -126,7 +126,7 @@ bool TextFieldTTF::attachWithIME()
if (ret)
{
// open keyboard
EGLView * pGlView = Director::getInstance()->getOpenGLView();
GLView * pGlView = Director::getInstance()->getOpenGLView();
if (pGlView)
{
pGlView->setIMEKeyboardState(true);
@ -141,7 +141,7 @@ bool TextFieldTTF::detachWithIME()
if (ret)
{
// close keyboard
EGLView * glView = Director::getInstance()->getOpenGLView();
GLView * glView = Director::getInstance()->getOpenGLView();
if (glView)
{
glView->setIMEKeyboardState(false);

View File

@ -544,7 +544,6 @@ bool Texture2D::initWithData(const void *data, ssize_t dataLen, Texture2D::Pixel
_contentSize = contentSize;
_maxS = contentSize.width / (float)(pixelsWide);
_maxT = contentSize.height / (float)(pixelsHigh);
}
bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat pixelFormat, int pixelsWide, int pixelsHigh)

View File

@ -386,7 +386,7 @@ void TextureCache::removeUnusedTextures()
{
for( auto it=_textures.cbegin(); it!=_textures.cend(); /* nothing */) {
Texture2D *tex = it->second;
if( tex->retainCount() == 1 ) {
if( tex->getReferenceCount() == 1 ) {
CCLOG("cocos2d: TextureCache: removing unused texture: %s", it->first.c_str());
tex->release();
@ -485,7 +485,7 @@ std::string TextureCache::getCachedTextureInfo() const
count++;
snprintf(buftmp,sizeof(buftmp)-1,"\"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB\n",
it->first.c_str(),
(long)tex->retainCount(),
(long)tex->getReferenceCount(),
(long)tex->getName(),
(long)tex->getPixelsWide(),
(long)tex->getPixelsHigh(),

View File

@ -7,7 +7,7 @@ set(PLATFORM_SRC
platform/win32/CCFileUtilsWin32.cpp
platform/win32/CCCommon.cpp
platform/win32/CCApplication.cpp
platform/win32/CCEGLView.cpp
platform/win32/CCGLView.cpp
platform/win32/CCImage.cpp
platform/win32/CCDevice.cpp
)
@ -21,7 +21,7 @@ set(PLATFORM_SRC
platform/linux/CCFileUtilsLinux.cpp
platform/linux/CCCommon.cpp
platform/linux/CCApplication.cpp
platform/linux/CCEGLView.cpp
platform/desktop/CCGLView.cpp
platform/linux/CCImage.cpp
platform/linux/CCDevice.cpp
)
@ -134,7 +134,7 @@ set(COCOS2D_SRC
CCDeprecated.cpp
platform/CCSAXParser.cpp
platform/CCThread.cpp
platform/CCEGLViewProtocol.cpp
platform/CCGLViewProtocol.cpp
platform/CCFileUtils.cpp
../../external/edtaa3func/edtaa3func.cpp
renderer/CCCustomCommand.cpp

View File

@ -107,9 +107,9 @@ Color4B::Color4B(GLubyte _r, GLubyte _g, GLubyte _b, GLubyte _a)
{}
Color4B::Color4B(const Color3B& color)
: r(color.r * 255)
, g(color.g * 255)
, b(color.b * 255)
: r(color.r)
, g(color.g)
, b(color.b)
, a(255)
{}

View File

@ -31,7 +31,7 @@ NS_CC_BEGIN
const char* cocos2dVersion()
{
return "3.0-beta";
return "3.0-beta2";
}
NS_CC_END

View File

@ -154,44 +154,44 @@ THE SOFTWARE.
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "platform/ios/CCApplication.h"
#include "platform/ios/CCEGLView.h"
#include "platform/ios/CCGLView.h"
#include "platform/ios/CCGL.h"
#include "platform/ios/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "platform/android/CCApplication.h"
#include "platform/android/CCEGLView.h"
#include "platform/android/CCGLView.h"
#include "platform/android/CCGL.h"
#include "platform/android/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#if (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY)
#include "platform/blackberry/CCApplication.h"
#include "platform/blackberry/CCEGLView.h"
#include "platform/blackberry/CCGLView.h"
#include "platform/blackberry/CCGL.h"
#include "platform/blackberry/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include "platform/win32/CCApplication.h"
#include "platform/win32/CCEGLView.h"
#include "platform/win32/CCGL.h"
#include "platform/win32/CCStdC.h"
#include "platform/win32/CCApplication.h"
#include "platform/desktop/CCGLView.h"
#include "platform/win32/CCGL.h"
#include "platform/win32/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
#include "platform/mac/CCApplication.h"
#include "platform/mac/CCEGLView.h"
#include "platform/mac/CCGL.h"
#include "platform/mac/CCStdC.h"
#include "platform/mac/CCApplication.h"
#include "platform/desktop/CCGLView.h"
#include "platform/mac/CCGL.h"
#include "platform/mac/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC
#if (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
#include "platform/linux/CCApplication.h"
#include "platform/linux/CCEGLView.h"
#include "platform/linux/CCGL.h"
#include "platform/linux/CCStdC.h"
#include "platform/linux/CCApplication.h"
#include "platform/desktop/CCGLView.h"
#include "platform/linux/CCGL.h"
#include "platform/linux/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
// script_support

View File

@ -304,14 +304,14 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="ccUtils.cpp" />
<ClCompile Include="CCVertex.cpp" />
<ClCompile Include="cocos2d.cpp" />
<ClCompile Include="platform\CCEGLViewProtocol.cpp" />
<ClCompile Include="platform\CCGLViewProtocol.cpp" />
<ClCompile Include="platform\CCFileUtils.cpp" />
<ClCompile Include="platform\CCSAXParser.cpp" />
<ClCompile Include="platform\CCThread.cpp" />
<ClCompile Include="platform\desktop\CCGLView.cpp" />
<ClCompile Include="platform\win32\CCApplication.cpp" />
<ClCompile Include="platform\win32\CCCommon.cpp" />
<ClCompile Include="platform\win32\CCDevice.cpp" />
<ClCompile Include="platform\win32\CCEGLView.cpp" />
<ClCompile Include="platform\win32\CCFileUtilsWin32.cpp" />
<ClCompile Include="platform\win32\CCImage.cpp" />
<ClCompile Include="platform\win32\CCStdC.cpp" />
@ -440,7 +440,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="CCLabel.h" />
<ClInclude Include="CCLabelAtlas.h" />
<ClInclude Include="CCLabelBMFont.h" />
<ClInclude Include="CCLabelTextFormatProtocol.h" />
<ClInclude Include="CCLabelTextFormatter.h" />
<ClInclude Include="CCLabelTTF.h" />
<ClInclude Include="CCLayer.h" />
@ -506,14 +505,14 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="platform\CCApplicationProtocol.h" />
<ClInclude Include="platform\CCCommon.h" />
<ClInclude Include="platform\CCDevice.h" />
<ClInclude Include="platform\CCEGLViewProtocol.h" />
<ClInclude Include="platform\CCGLViewProtocol.h" />
<ClInclude Include="platform\CCFileUtils.h" />
<ClInclude Include="platform\CCImage.h" />
<ClInclude Include="platform\CCImageCommon_cpp.h" />
<ClInclude Include="platform\CCSAXParser.h" />
<ClInclude Include="platform\CCThread.h" />
<ClInclude Include="platform\desktop\CCGLView.h" />
<ClInclude Include="platform\win32\CCApplication.h" />
<ClInclude Include="platform\win32\CCEGLView.h" />
<ClInclude Include="platform\win32\CCFileUtilsWin32.h" />
<ClInclude Include="platform\win32\CCGL.h" />
<ClInclude Include="platform\win32\CCPlatformDefine.h" />
@ -537,4 +536,4 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
</Project>

View File

@ -112,6 +112,9 @@
<Filter Include="renderer">
<UniqueIdentifier>{cba0f362-878c-438b-ad0f-43d287516357}</UniqueIdentifier>
</Filter>
<Filter Include="platform\desktop">
<UniqueIdentifier>{32373f63-2c2d-4eab-bc4a-21745ba0b3fb}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\physics\CCPhysicsBody.cpp">
@ -351,9 +354,6 @@
<ClCompile Include="platform\win32\CCDevice.cpp">
<Filter>platform\win32</Filter>
</ClCompile>
<ClCompile Include="platform\win32\CCEGLView.cpp">
<Filter>platform\win32</Filter>
</ClCompile>
<ClCompile Include="platform\win32\CCFileUtilsWin32.cpp">
<Filter>platform\win32</Filter>
</ClCompile>
@ -363,7 +363,7 @@
<ClCompile Include="platform\win32\CCStdC.cpp">
<Filter>platform\win32</Filter>
</ClCompile>
<ClCompile Include="platform\CCEGLViewProtocol.cpp">
<ClCompile Include="platform\CCGLViewProtocol.cpp">
<Filter>platform</Filter>
</ClCompile>
<ClCompile Include="platform\CCFileUtils.cpp">
@ -595,6 +595,9 @@
<ClCompile Include="CCFontCharMap.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="platform\desktop\CCGLView.cpp">
<Filter>platform\desktop</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\physics\CCPhysicsBody.h">
@ -840,9 +843,6 @@
<ClInclude Include="CCLabelBMFont.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="CCLabelTextFormatProtocol.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="CCLabelTextFormatter.h">
<Filter>label_nodes</Filter>
</ClInclude>
@ -855,9 +855,6 @@
<ClInclude Include="platform\win32\CCApplication.h">
<Filter>platform\win32</Filter>
</ClInclude>
<ClInclude Include="platform\win32\CCEGLView.h">
<Filter>platform\win32</Filter>
</ClInclude>
<ClInclude Include="platform\win32\CCFileUtilsWin32.h">
<Filter>platform\win32</Filter>
</ClInclude>
@ -879,7 +876,7 @@
<ClInclude Include="platform\CCDevice.h">
<Filter>platform</Filter>
</ClInclude>
<ClInclude Include="platform\CCEGLViewProtocol.h">
<ClInclude Include="platform\CCGLViewProtocol.h">
<Filter>platform</Filter>
</ClInclude>
<ClInclude Include="platform\CCFileUtils.h">
@ -1201,5 +1198,8 @@
<ClInclude Include="CCFontCharMap.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="platform\desktop\CCGLView.h">
<Filter>platform\desktop</Filter>
</ClInclude>
</ItemGroup>
</Project>
</Project>

View File

@ -7,7 +7,7 @@
<PropertyGroup />
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(EngineRoot)cocos\2d;$(EngineRoot)cocos\2d\renderer;$(EngineRoot)cocos\gui;$(EngineRoot)cocos\base;$(EngineRoot)cocos\physics;$(EngineRoot)cocos\math\kazmath\include;$(EngineRoot)cocos\2d\platform\win32;$(EngineRoot)external\glfw3\include\win32;$(EngineRoot)external\win32-specific\gles\include\OGLES</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>$(EngineRoot)cocos\2d;$(EngineRoot)cocos\2d\renderer;$(EngineRoot)cocos\gui;$(EngineRoot)cocos\base;$(EngineRoot)cocos\physics;$(EngineRoot)cocos\math\kazmath\include;$(EngineRoot)cocos\2d\platform\win32;$(EngineRoot)cocos\2d\platform\desktop;$(EngineRoot)external\glfw3\include\win32;$(EngineRoot)external\win32-specific\gles\include\OGLES</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_VARIADIC_MAX=10;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>

View File

@ -1,149 +0,0 @@
################################################################################
#
# LINUX MAKEFILE
#
# Available options are:
# - CLANG=1 : Compiles with clang instead of gcc. Clang must be in your PATH.
# - V=1 : Enables the verbose mode.
# - DEBUG=1 : Enables the debug mode, disable compiler optimizations.
# - OPENAL=1 : Uses OpenAL instead of FMOD as sound engine.
#
################################################################################
all:
# Remove -Wall, because it enables -Wunused-function, and this warning exists in webp.h
# when enable c++11. I don't know why.
# GCC 4.6 is primary platform for cocos2d v.3, because it's default compiler for Android,
# Blackberry, some Linux distributions.It supports all important features of c++11, but have
# no flag "-std=c++11" (which was turned on in version 4.7).
CCFLAGS += -MMD -Wno-deprecated-declarations -fPIC
CXXFLAGS += -MMD -Wno-deprecated-declarations -fPIC -std=gnu++0x
ifeq ($(CLANG), 1)
CC := clang
CXX := clang++
DEFINES += -D__STRICT_ANSI__ # Allows clang 3.3 to use __float128
else
CC = gcc
CXX = g++
CCFLAGS += -Werror
CXXFLAGS += -Werror
endif
ARFLAGS = cr
DEFINES += -DLINUX -DCC_KEYBOARD_SUPPORT
ifdef USE_BOX2D
DEFINES += -DCC_ENABLE_BOX2D_INTEGRATION=1
else
DEFINES += -DCC_ENABLE_CHIPMUNK_INTEGRATION=1
endif
THIS_MAKEFILE := $(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
ifndef COCOS_ROOT
COCOS_ROOT := $(realpath $(dir $(THIS_MAKEFILE))/../..)
endif
COCOS_SRC = $(COCOS_ROOT)/cocos/2d
OBJ_DIR ?= obj
LIB_DIR = $(COCOS_ROOT)/lib/linux
BIN_DIR = bin
INCLUDES += \
-I$(COCOS_SRC)/ \
-I$(COCOS_SRC)/../math/kazmath/include \
-I$(COCOS_SRC)/platform/linux \
-I$(COCOS_SRC)/../../external/jpeg/include/linux \
-I$(COCOS_SRC)/../../external/tiff/include/linux \
-I$(COCOS_SRC)/../../external/webp/include/linux \
-I$(COCOS_SRC)/../../external/tinyxml2 \
-I$(COCOS_SRC)/../../external/unzip \
-I$(COCOS_SRC)/../../external/glfw3/include/linux \
-I$(COCOS_SRC)/../physics \
-I$(COCOS_SRC)/../base \
-I$(COCOS_SRC)/../../external/chipmunk/include/chipmunk \
-I$(COCOS_SRC)/../../external/freetype2/include/linux \
-I$(COCOS_SRC)/../.. \
-I$(COCOS_SRC)/../audio/include
LBITS := $(shell getconf LONG_BIT)
ifeq ($(DEBUG), 1)
CCFLAGS += -g3 -O0
CXXFLAGS += -g3 -O0
DEFINES += -D_DEBUG -DCOCOS2D_DEBUG=1
OBJ_DIR := $(OBJ_DIR)/debug
LIB_DIR := $(LIB_DIR)/debug
BIN_DIR := $(BIN_DIR)/debug
else
CCFLAGS += -O3
CXXFLAGS += -O3
DEFINES += -DNDEBUG
OBJ_DIR := $(OBJ_DIR)/release
LIB_DIR := $(LIB_DIR)/release
BIN_DIR := $(BIN_DIR)/release
endif
ifndef V
LOG_CC = @echo " CC $@";
LOG_CXX = @echo " CXX $@";
LOG_AR = @echo " AR $@";
LOG_LINK = @echo " LINK $@";
endif
OBJECTS := $(SOURCES:.cpp=.o)
OBJECTS := $(OBJECTS:.c=.o)
OBJECTS := $(subst ../,,$(OBJECTS))
OBJECTS := $(subst $(COCOS_ROOT)/,,$(OBJECTS))
OBJECTS := $(addprefix $(OBJ_DIR)/, $(OBJECTS))
DEPS = $(OBJECTS:.o=.d)
CORE_MAKEFILE_LIST := $(MAKEFILE_LIST)
-include $(DEPS)
STATICLIBS_DIR = $(COCOS_ROOT)/external
ifeq ($(LBITS),64)
POSTFIX = 64-bit
else
POSTFIX = 32-bit
endif
STATICLIBS = $(STATICLIBS_DIR)/freetype2/prebuilt/linux/$(POSTFIX)/libfreetype.a \
$(STATICLIBS_DIR)/jpeg/prebuilt/linux/$(POSTFIX)/libjpeg.a \
$(STATICLIBS_DIR)/tiff/prebuilt/linux/$(POSTFIX)/libtiff.a \
$(STATICLIBS_DIR)/webp/prebuilt/linux/$(POSTFIX)/libwebp.a
ifneq ($(OPENAL),1)
ifeq ($(LBITS),64)
FMOD_LIBDIR = $(COCOS_ROOT)/cocos/audio/third-party/fmod/lib64/api/lib
SHAREDLIBS += -lfmodex64
else
FMOD_LIBDIR = $(COCOS_ROOT)/cocos/audio/third-party/fmod/api/lib
SHAREDLIBS += -lfmodex
endif
endif
SHAREDLIBS += -lGLEW -lfontconfig -lpthread -lGL -lpng `pkg-config --libs glfw3`
SHAREDLIBS += -L$(FMOD_LIBDIR) -Wl,-rpath,$(abspath $(FMOD_LIBDIR))
SHAREDLIBS += -L$(LIB_DIR) -Wl,-rpath,$(abspath $(LIB_DIR))
LIBS = -lrt -lz -lX11
clean:
rm -rf $(OBJ_DIR)
rm -f $(TARGET) core
.PHONY: all clean
# If the parent Makefile defines $(EXECUTABLE) then define this as the target
# and create a 'make run' rule to run the app.
ifdef EXECUTABLE
TARGET := $(BIN_DIR)/$(EXECUTABLE)
all: $(TARGET)
run: $(TARGET)
cd $(dir $^) && ./$(notdir $^)
.PHONY: run
endif

View File

@ -33,6 +33,8 @@ NS_CC_BEGIN
* @{
*/
class EAGLView;
class CC_DLL ApplicationProtocol
{
public:

View File

@ -56,6 +56,7 @@ enum class LanguageType
ITALIAN,
GERMAN,
SPANISH,
DUTCH,
RUSSIAN,
KOREAN,
JAPANESE,

View File

@ -23,7 +23,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCEGLViewProtocol.h"
#include "CCGLViewProtocol.h"
#include "CCTouch.h"
#include "CCDirector.h"
#include "CCSet.h"
@ -71,24 +71,23 @@ namespace {
}
EGLViewProtocol::EGLViewProtocol()
: _delegate(nullptr)
, _scaleX(1.0f)
GLViewProtocol::GLViewProtocol()
: _scaleX(1.0f)
, _scaleY(1.0f)
, _resolutionPolicy(ResolutionPolicy::UNKNOWN)
{
}
EGLViewProtocol::~EGLViewProtocol()
GLViewProtocol::~GLViewProtocol()
{
}
void EGLViewProtocol::pollInputEvents()
void GLViewProtocol::pollInputEvents()
{
}
void EGLViewProtocol::setDesignResolutionSize(float width, float height, ResolutionPolicy resolutionPolicy)
void GLViewProtocol::setDesignResolutionSize(float width, float height, ResolutionPolicy resolutionPolicy)
{
CCASSERT(resolutionPolicy != ResolutionPolicy::UNKNOWN, "should set resolutionPolicy");
@ -107,17 +106,17 @@ void EGLViewProtocol::setDesignResolutionSize(float width, float height, Resolut
_scaleX = _scaleY = MAX(_scaleX, _scaleY);
}
if (resolutionPolicy == ResolutionPolicy::SHOW_ALL)
else if (resolutionPolicy == ResolutionPolicy::SHOW_ALL)
{
_scaleX = _scaleY = MIN(_scaleX, _scaleY);
}
if ( resolutionPolicy == ResolutionPolicy::FIXED_HEIGHT) {
else if ( resolutionPolicy == ResolutionPolicy::FIXED_HEIGHT) {
_scaleX = _scaleY;
_designResolutionSize.width = ceilf(_screenSize.width/_scaleX);
}
if ( resolutionPolicy == ResolutionPolicy::FIXED_WIDTH) {
else if ( resolutionPolicy == ResolutionPolicy::FIXED_WIDTH) {
_scaleY = _scaleX;
_designResolutionSize.height = ceilf(_screenSize.height/_scaleY);
}
@ -131,27 +130,28 @@ void EGLViewProtocol::setDesignResolutionSize(float width, float height, Resolut
_resolutionPolicy = resolutionPolicy;
// reset director's member variables to fit visible rect
Director::getInstance()->_winSizeInPoints = getDesignResolutionSize();
Director::getInstance()->createStatsLabel();
Director::getInstance()->setGLDefaultValues();
auto director = Director::getInstance();
director->_winSizeInPoints = getDesignResolutionSize();
director->createStatsLabel();
director->setGLDefaultValues();
}
const Size& EGLViewProtocol::getDesignResolutionSize() const
const Size& GLViewProtocol::getDesignResolutionSize() const
{
return _designResolutionSize;
}
const Size& EGLViewProtocol::getFrameSize() const
const Size& GLViewProtocol::getFrameSize() const
{
return _screenSize;
}
void EGLViewProtocol::setFrameSize(float width, float height)
void GLViewProtocol::setFrameSize(float width, float height)
{
_designResolutionSize = _screenSize = Size(width, height);
}
Size EGLViewProtocol::getVisibleSize() const
Size GLViewProtocol::getVisibleSize() const
{
if (_resolutionPolicy == ResolutionPolicy::NO_BORDER)
{
@ -163,7 +163,7 @@ Size EGLViewProtocol::getVisibleSize() const
}
}
Point EGLViewProtocol::getVisibleOrigin() const
Point GLViewProtocol::getVisibleOrigin() const
{
if (_resolutionPolicy == ResolutionPolicy::NO_BORDER)
{
@ -176,12 +176,7 @@ Point EGLViewProtocol::getVisibleOrigin() const
}
}
void EGLViewProtocol::setTouchDelegate(EGLTouchDelegate * delegate)
{
_delegate = delegate;
}
void EGLViewProtocol::setViewPortInPoints(float x , float y , float w , float h)
void GLViewProtocol::setViewPortInPoints(float x , float y , float w , float h)
{
glViewport((GLint)(x * _scaleX + _viewPortRect.origin.x),
(GLint)(y * _scaleY + _viewPortRect.origin.y),
@ -189,7 +184,7 @@ void EGLViewProtocol::setViewPortInPoints(float x , float y , float w , float h)
(GLsizei)(h * _scaleY));
}
void EGLViewProtocol::setScissorInPoints(float x , float y , float w , float h)
void GLViewProtocol::setScissorInPoints(float x , float y , float w , float h)
{
glScissor((GLint)(x * _scaleX + _viewPortRect.origin.x),
(GLint)(y * _scaleY + _viewPortRect.origin.y),
@ -197,12 +192,12 @@ void EGLViewProtocol::setScissorInPoints(float x , float y , float w , float h)
(GLsizei)(h * _scaleY));
}
bool EGLViewProtocol::isScissorEnabled()
bool GLViewProtocol::isScissorEnabled()
{
return (GL_FALSE == glIsEnabled(GL_SCISSOR_TEST)) ? false : true;
}
Rect EGLViewProtocol::getScissorRect() const
Rect GLViewProtocol::getScissorRect() const
{
GLfloat params[4];
glGetFloatv(GL_SCISSOR_BOX, params);
@ -213,17 +208,17 @@ Rect EGLViewProtocol::getScissorRect() const
return Rect(x, y, w, h);
}
void EGLViewProtocol::setViewName(const std::string& viewname )
void GLViewProtocol::setViewName(const std::string& viewname )
{
_viewName = viewname;
}
const std::string& EGLViewProtocol::getViewName() const
const std::string& GLViewProtocol::getViewName() const
{
return _viewName;
}
void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float ys[])
void GLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float ys[])
{
int id = 0;
float x = 0.0f;
@ -273,7 +268,7 @@ void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float y
dispatcher->dispatchEvent(&touchEvent);
}
void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[])
void GLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[])
{
int id = 0;
float x = 0.0f;
@ -321,7 +316,7 @@ void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys
dispatcher->dispatchEvent(&touchEvent);
}
void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[])
void GLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[])
{
int id = 0;
float x = 0.0f;
@ -381,27 +376,27 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode
}
}
void EGLViewProtocol::handleTouchesEnd(int num, int ids[], float xs[], float ys[])
void GLViewProtocol::handleTouchesEnd(int num, int ids[], float xs[], float ys[])
{
handleTouchesOfEndOrCancel(EventTouch::EventCode::ENDED, num, ids, xs, ys);
}
void EGLViewProtocol::handleTouchesCancel(int num, int ids[], float xs[], float ys[])
void GLViewProtocol::handleTouchesCancel(int num, int ids[], float xs[], float ys[])
{
handleTouchesOfEndOrCancel(EventTouch::EventCode::CANCELLED, num, ids, xs, ys);
}
const Rect& EGLViewProtocol::getViewPortRect() const
const Rect& GLViewProtocol::getViewPortRect() const
{
return _viewPortRect;
}
float EGLViewProtocol::getScaleX() const
float GLViewProtocol::getScaleX() const
{
return _scaleX;
}
float EGLViewProtocol::getScaleY() const
float GLViewProtocol::getScaleY() const
{
return _scaleY;
}

View File

@ -23,8 +23,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCEGLVIEWPROTOCOL_H__
#define __CCEGLVIEWPROTOCOL_H__
#ifndef __CCGLVIEWPROTOCOL_H__
#define __CCGLVIEWPROTOCOL_H__
#include "ccTypes.h"
#include "CCEventTouch.h"
@ -65,30 +65,30 @@ class EGLTouchDelegate;
* @{
*/
class CC_DLL EGLViewProtocol
class CC_DLL GLViewProtocol
{
public:
/**
* @js ctor
*/
EGLViewProtocol();
GLViewProtocol();
/**
* @js NA
* @lua NA
*/
virtual ~EGLViewProtocol();
virtual ~GLViewProtocol();
/** Force destroying EGL view, subclass must implement this method. */
virtual void end() = 0;
virtual void end() = 0;
/** Get whether opengl render system is ready, subclass must implement this method. */
virtual bool isOpenGLReady() = 0;
virtual bool isOpenGLReady() = 0;
/** Exchanges the front and back buffers, subclass must implement this method. */
virtual void swapBuffers() = 0;
virtual void swapBuffers() = 0;
/** Open or close IME keyboard , subclass must implement this method. */
virtual void setIMEKeyboardState(bool open) = 0;
virtual void setIMEKeyboardState(bool open) = 0;
/**
* Polls input events. Subclass must implement methods if platform
@ -133,9 +133,6 @@ public:
*/
virtual const Size& getDesignResolutionSize() const;
/** Set touch delegate */
virtual void setTouchDelegate(EGLTouchDelegate * delegate);
/**
* Set opengl view port rectangle with points.
*/
@ -184,8 +181,6 @@ public:
protected:
void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]);
EGLTouchDelegate* _delegate;
// real screen size
Size _screenSize;
// resolution size, it is the size appropriate for the app resources.
@ -195,8 +190,8 @@ protected:
// the view name
std::string _viewName;
float _scaleX;
float _scaleY;
float _scaleX;
float _scaleY;
ResolutionPolicy _resolutionPolicy;
};
@ -205,4 +200,4 @@ protected:
NS_CC_END
#endif /* __CCEGLVIEWPROTOCOL_H__ */
#endif /* __CCGLVIEWPROTOCOL_H__ */

View File

@ -10,7 +10,7 @@ LOCAL_SRC_FILES := \
CCApplication.cpp \
CCCommon.cpp \
CCDevice.cpp \
CCEGLView.cpp \
CCGLView.cpp \
CCFileUtilsAndroid.cpp \
CCImage.cpp \
nativeactivity.cpp \

View File

@ -22,11 +22,15 @@ 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.
****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "jni/JniHelper.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
#include "CCApplication.h"
#include "CCDirector.h"
#include "CCEGLView.h"
#include "CCGLView.h"
#include <android/log.h>
#include <jni.h>
#include <cstring>
@ -116,6 +120,10 @@ LanguageType Application::getCurrentLanguage()
{
ret = LanguageType::RUSSIAN;
}
else if (0 == strcmp("nl", pLanguageName))
{
ret = LanguageType::DUTCH;
}
else if (0 == strcmp("ko", pLanguageName))
{
ret = LanguageType::KOREAN;
@ -157,3 +165,6 @@ void Application::applicationScreenSizeChanged(int newWidth, int newHeight) {
}
NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

View File

@ -22,9 +22,13 @@ 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 __CC_APPLICATION_ANDROID_H__
#define __CC_APPLICATION_ANDROID_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "platform/CCCommon.h"
#include "platform/CCApplicationProtocol.h"
@ -87,4 +91,6 @@ protected:
NS_CC_END
#endif // __CC_APPLICATION_ANDROID_H__
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#endif // __CC_APPLICATION_ANDROID_H__

View File

@ -23,6 +23,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "platform/CCCommon.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
#include <android/log.h>
@ -44,3 +47,6 @@ void LuaLog(const char * pszFormat)
}
NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

View File

@ -22,6 +22,10 @@ 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.
****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "platform/CCDevice.h"
#include "jni/DPIJni.h"
#include "nativeactivity.h"
@ -56,3 +60,6 @@ void Device::setAccelerometerInterval(float interval)
}
NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

View File

@ -22,6 +22,10 @@ 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.
****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "CCFileUtilsAndroid.h"
#include "platform/CCCommon.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
@ -353,3 +357,5 @@ string FileUtilsAndroid::getWritablePath() const
}
NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

View File

@ -25,6 +25,9 @@ Copyright (c) 2013-2014 Chukong Technologies Inc.
#ifndef __CC_FILEUTILS_ANDROID_H__
#define __CC_FILEUTILS_ANDROID_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "platform/CCFileUtils.h"
#include "CCPlatformMacros.h"
#include "ccTypes.h"
@ -86,4 +89,6 @@ private:
NS_CC_END
#endif // __CC_FILEUTILS_ANDROID_H__
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#endif // __CC_FILEUTILS_ANDROID_H__

View File

@ -26,6 +26,9 @@ THE SOFTWARE.
#ifndef __CCGL_H__
#define __CCGL_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#define glClearDepth glClearDepthf
#define glDeleteVertexArrays glDeleteVertexArraysOES
#define glGenVertexArrays glGenVertexArraysOES
@ -63,4 +66,6 @@ extern PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOESEXT;
#define glDeleteVertexArraysOES glDeleteVertexArraysOESEXT
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#endif // __CCGL_H__

View File

@ -22,7 +22,11 @@ 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.
****************************************************************************/
#include "CCEGLView.h"
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "CCGLView.h"
#include "CCSet.h"
#include "CCDirector.h"
#include "ccMacros.h"
@ -48,46 +52,79 @@ void initExtensions() {
NS_CC_BEGIN
EGLView::EGLView()
GLView* GLView::createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor)
{
auto ret = new GLView;
if(ret && ret->initWithRect(viewName, rect, frameZoomFactor)) {
ret->autorelease();
return ret;
}
return nullptr;
}
GLView* GLView::create(const std::string& viewName)
{
auto ret = new GLView;
if(ret && ret->initWithFullScreen(viewName)) {
ret->autorelease();
return ret;
}
return nullptr;
}
GLView* GLView::createWithFullScreen(const std::string& viewName)
{
auto ret = new GLView();
if(ret && ret->initWithFullScreen(viewName)) {
ret->autorelease();
return ret;
}
return nullptr;
}
GLView::GLView()
{
initExtensions();
}
EGLView::~EGLView()
GLView::~GLView()
{
}
bool EGLView::isOpenGLReady()
bool GLView::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor)
{
return true;
}
bool GLView::initWithFullScreen(const std::string& viewName)
{
return true;
}
bool GLView::isOpenGLReady()
{
return (_screenSize.width != 0 && _screenSize.height != 0);
}
void EGLView::end()
void GLView::end()
{
terminateProcessJNI();
}
void EGLView::swapBuffers()
void GLView::swapBuffers()
{
}
EGLView* EGLView::getInstance()
{
static EGLView instance;
return &instance;
}
// XXX: deprecated
EGLView* EGLView::sharedOpenGLView()
{
return EGLView::getInstance();
}
void EGLView::setIMEKeyboardState(bool bOpen)
void GLView::setIMEKeyboardState(bool bOpen)
{
setKeyboardStateJNI((int)bOpen);
}
NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

View File

@ -26,41 +26,40 @@ THE SOFTWARE.
#ifndef __CC_EGLVIEW_ANDROID_H__
#define __CC_EGLVIEW_ANDROID_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "CCObject.h"
#include "CCGeometry.h"
#include "platform/CCEGLViewProtocol.h"
#include "platform/CCGLViewProtocol.h"
NS_CC_BEGIN
class CC_DLL EGLView : public EGLViewProtocol
class CC_DLL GLView : public Object, public GLViewProtocol
{
public:
/**
* @js ctor
*/
EGLView();
/**
* @js NA
* @lua NA
*/
virtual ~EGLView();
bool isOpenGLReady();
// keep compatible
void end();
void swapBuffers();
void setIMEKeyboardState(bool bOpen);
// static function
/**
@brief get the shared main open gl window
*/
static EGLView* getInstance();
static GLView* create(const std::string &viewname);
static GLView* createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor = 1.0f);
static GLView* createWithFullScreen(const std::string& viewName);
/** @deprecated Use getInstance() instead */
CC_DEPRECATED_ATTRIBUTE static EGLView* sharedOpenGLView();
bool isOpenGLReady() override;
void end() override;
void swapBuffers() override;
void setIMEKeyboardState(bool bOpen) override;
protected:
GLView();
virtual ~GLView();
bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor);
bool initWithFullScreen(const std::string& viewName);
};
NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#endif // end of __CC_EGLVIEW_ANDROID_H__

View File

@ -23,7 +23,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
//#define COCOS2D_DEBUG 1
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#define __CC_PLATFORM_IMAGE_CPP__
#include "platform/CCImageCommon_cpp.h"
@ -246,3 +247,5 @@ extern "C"
env->GetByteArrayRegion(pixels, 0, size, (jbyte*)bitmapDC._data);
}
};
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

View File

@ -26,6 +26,9 @@ THE SOFTWARE.
#ifndef __CCPLATFORMDEFINE_H__
#define __CCPLATFORMDEFINE_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "android/log.h"
#define CC_DLL
@ -59,4 +62,6 @@ THE SOFTWARE.
#endif
#endif
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#endif /* __CCPLATFORMDEFINE_H__*/

View File

@ -26,6 +26,9 @@ THE SOFTWARE.
#ifndef __CC_STD_C_H__
#define __CC_STD_C_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "CCPlatformMacros.h"
#include <float.h>
#include <math.h>
@ -45,4 +48,6 @@ THE SOFTWARE.
#define MAX(x,y) (((x) < (y)) ? (y) : (x))
#endif // MAX
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#endif // __CC_STD_C_H__

View File

@ -21,6 +21,10 @@ 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.
****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "nativeactivity.h"
#include <jni.h>
@ -43,7 +47,7 @@ THE SOFTWARE.
#include "CCFileUtilsAndroid.h"
#include "jni/JniHelper.h"
#include "CCEGLView.h"
#include "CCGLView.h"
#include "CCDrawingPrimitives.h"
#include "CCShaderCache.h"
#include "CCTextureCache.h"
@ -111,29 +115,27 @@ extern EditTextCallback s_pfEditTextCallback;
extern void* s_ctx;
extern "C" {
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetEditTextDialogResult(JNIEnv * env, jobject obj, jbyteArray text) {
jsize size = env->GetArrayLength(text);
pthread_mutex_lock(&(engine.app->mutex));
if (size > 0) {
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetEditTextDialogResult(JNIEnv * env, jobject obj, jbyteArray text) {
jsize size = env->GetArrayLength(text);
pthread_mutex_lock(&(engine.app->mutex));
if (size > 0) {
jbyte * data = (jbyte*)env->GetByteArrayElements(text, 0);
char* pBuf = (char*)malloc(size+1);
if (pBuf != NULL) {
memcpy(pBuf, data, size);
pBuf[size] = '\0';
editboxText = pBuf;
}
env->ReleaseByteArrayElements(text, data, 0);
jbyte * data = (jbyte*)env->GetByteArrayElements(text, 0);
char* pBuf = (char*)malloc(size+1);
if (pBuf != NULL) {
memcpy(pBuf, data, size);
pBuf[size] = '\0';
editboxText = pBuf;
}
env->ReleaseByteArrayElements(text, data, 0);
} else {
char* pBuf = (char*)malloc(1);
pBuf[0] = '\0';
editboxText = pBuf;
}
pthread_cond_broadcast(&engine.app->cond);
pthread_mutex_unlock(&(engine.app->mutex));
}
} else {
char* pBuf = (char*)malloc(1);
pBuf[0] = '\0';
editboxText = pBuf;
}
pthread_cond_broadcast(&engine.app->cond);
pthread_mutex_unlock(&(engine.app->mutex));
}
}
typedef struct cocos_dimensions {
@ -141,17 +143,21 @@ typedef struct cocos_dimensions {
int h;
} cocos_dimensions;
static void cocos_init(cocos_dimensions d, struct android_app* app) {
static void cocos_init(cocos_dimensions d, struct android_app* app)
{
LOGI("cocos_init(...)");
pthread_t thisthread = pthread_self();
LOGI("pthread_self() = %X", thisthread);
cocos2d::FileUtilsAndroid::setassetmanager(app->activity->assetManager);
if (!cocos2d::Director::getInstance()->getOpenGLView())
auto director = cocos2d::Director::getInstance();
auto glview = director->getOpenGLView();
if (!glview)
{
cocos2d::EGLView *view = cocos2d::EGLView::getInstance();
view->setFrameSize(d.w, d.h);
glview = cocos2d::GLView::create("Android app");
glview->setFrameSize(d.w, d.h);
director->setOpenGLView(glview);
cocos_android_app_init(app);
@ -163,16 +169,18 @@ static void cocos_init(cocos_dimensions d, struct android_app* app) {
cocos2d::ShaderCache::getInstance()->reloadDefaultShaders();
cocos2d::DrawPrimitives::init();
cocos2d::VolatileTextureMgr::reloadAllTextures();
cocos2d::EventCustom foregroundEvent(EVENT_COME_TO_FOREGROUND);
cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&foregroundEvent);
cocos2d::Director::getInstance()->setGLDefaultValues();
director->getEventDispatcher()->dispatchEvent(&foregroundEvent);
director->setGLDefaultValues();
}
}
/**
* Initialize an EGL context for the current display.
*/
static cocos_dimensions engine_init_display(struct engine* engine) {
static cocos_dimensions engine_init_display(struct engine* engine)
{
cocos_dimensions r;
r.w = -1;
r.h = -1;
@ -245,6 +253,7 @@ static cocos_dimensions engine_init_display(struct engine* engine) {
r.w = w;
r.h = h;
return r;
}
@ -275,7 +284,8 @@ static void dispatch_pending_runnables() {
/**
* Just the current frame in the display.
*/
static void engine_draw_frame(struct engine* engine) {
static void engine_draw_frame(struct engine* engine)
{
LOG_RENDER_DEBUG("engine_draw_frame(...)");
pthread_t thisthread = pthread_self();
LOG_RENDER_DEBUG("pthread_self() = %X", thisthread);
@ -293,14 +303,14 @@ static void engine_draw_frame(struct engine* engine) {
/* // Just fill the screen with a color. */
/* glClearColor(((float)engine->state.x)/engine->width, engine->state.angle, */
/* ((float)engine->state.y)/engine->height, 1); */
/* glClear(GL_COLOR_BUFFER_BIT); */
if (s_pfEditTextCallback && editboxText)
{
s_pfEditTextCallback(editboxText, s_ctx);
free(editboxText);
editboxText = NULL;
}
/* glClear(GL_COLOR_BUFFER_BIT); */
if (s_pfEditTextCallback && editboxText)
{
s_pfEditTextCallback(editboxText, s_ctx);
free(editboxText);
editboxText = NULL;
}
eglSwapBuffers(engine->display, engine->surface);
}
@ -308,7 +318,8 @@ static void engine_draw_frame(struct engine* engine) {
/**
* Tear down the EGL context currently associated with the display.
*/
static void engine_term_display(struct engine* engine) {
static void engine_term_display(struct engine* engine)
{
if (engine->display != EGL_NO_DISPLAY) {
eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (engine->context != EGL_NO_CONTEXT) {
@ -390,7 +401,7 @@ static int32_t handle_touch_input(AInputEvent *event) {
int ids[pointerCount];
float xs[pointerCount], ys[pointerCount];
getTouchPos(event, ids, xs, ys);
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys);
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys);
return 1;
}
break;
@ -435,7 +446,7 @@ static int32_t handle_touch_input(AInputEvent *event) {
int ids[pointerCount];
float xs[pointerCount], ys[pointerCount];
getTouchPos(event, ids, xs, ys);
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys);
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys);
return 1;
}
break;
@ -458,7 +469,7 @@ static int32_t handle_key_input(AInputEvent *event)
switch (AKeyEvent_getKeyCode(event))
{
case AKEYCODE_BACK:
case AKEYCODE_BACK:
{
cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_BACKSPACE, false);
dispatcher->dispatchEvent(&event);
@ -494,8 +505,8 @@ static int32_t engine_handle_input(struct android_app* app, AInputEvent* event)
return handle_touch_input(event);
}
else
return handle_key_input(event);
else
return handle_key_input(event);
return 0;
}
@ -533,7 +544,8 @@ void setAccelerometerIntervalJni(float interval) {
/**
* Process the next main command.
*/
static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
static void engine_handle_cmd(struct android_app* app, int32_t cmd)
{
struct engine* engine = (struct engine*)app->userData;
switch (cmd) {
case APP_CMD_SAVE_STATE:
@ -576,7 +588,7 @@ static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
case APP_CMD_GAINED_FOCUS:
if (cocos2d::Director::getInstance()->getOpenGLView()) {
cocos2d::Application::getInstance()->applicationWillEnterForeground();
engine->animating = 1;
engine->animating = 1;
}
break;
@ -594,14 +606,14 @@ static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
}
static void onContentRectChanged(ANativeActivity* activity, const ARect* rect) {
timeRectChanged = std::chrono::steady_clock::now();
isContentRectChanged = true;
timeRectChanged = std::chrono::steady_clock::now();
isContentRectChanged = true;
}
static void process_input(struct android_app* app, struct android_poll_source* source) {
static void process_input(struct android_app* app, struct android_poll_source* source)
{
AInputEvent* event = NULL;
int processed = 0;
while (AInputQueue_hasEvents( app->inputQueue ) && AInputQueue_getEvent(app->inputQueue, &event) >= 0) {
while (AInputQueue_getEvent(app->inputQueue, &event) >= 0) {
LOGV("New input event: type=%d\n", AInputEvent_getType(event));
if (AInputQueue_preDispatchEvent(app->inputQueue, event)) {
continue;
@ -609,10 +621,6 @@ static void process_input(struct android_app* app, struct android_poll_source* s
int32_t handled = 0;
if (app->onInputEvent != NULL) handled = app->onInputEvent(app, event);
AInputQueue_finishEvent(app->inputQueue, event, handled);
processed = 1;
}
if (processed == 0) {
LOGE("Failure reading next input event: %s\n", strerror(errno));
}
}
/**
@ -644,8 +652,8 @@ void android_main(struct android_app* state) {
engine.state = *(struct saved_state*)state->savedState;
}
// Screen size change support
state->activity->callbacks->onContentRectChanged = onContentRectChanged;
// Screen size change support
state->activity->callbacks->onContentRectChanged = onContentRectChanged;
// loop waiting for stuff to do.
@ -735,19 +743,21 @@ void android_main(struct android_app* state) {
LOG_RENDER_DEBUG("android_main : !engine.animating");
}
// Check if screen size changed
if (isContentRectChanged) {
std::chrono::duration<int, std::milli> duration(
std::chrono::duration_cast<std::chrono::duration<int, std::milli>>(std::chrono::steady_clock::now() - timeRectChanged));
// Check if screen size changed
if (isContentRectChanged) {
std::chrono::duration<int, std::milli> duration(
std::chrono::duration_cast<std::chrono::duration<int, std::milli>>(std::chrono::steady_clock::now() - timeRectChanged));
// Wait about 30 ms to get new width and height. Without waiting we can get old values sometime
if (duration.count() > 30) {
isContentRectChanged = false;
// Wait about 30 ms to get new width and height. Without waiting we can get old values sometime
if (duration.count() > 30) {
isContentRectChanged = false;
int32_t newWidth = ANativeWindow_getWidth(engine.app->window);
int32_t newHeight = ANativeWindow_getHeight(engine.app->window);
cocos2d::Application::getInstance()->applicationScreenSizeChanged(newWidth, newHeight);
}
}
int32_t newWidth = ANativeWindow_getWidth(engine.app->window);
int32_t newHeight = ANativeWindow_getHeight(engine.app->window);
cocos2d::Application::getInstance()->applicationScreenSizeChanged(newWidth, newHeight);
}
}
}
}
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

View File

@ -24,6 +24,9 @@ THE SOFTWARE.
#ifndef __COCOSNATIVEACTIVITY_H__
#define __COCOSNATIVEACTIVITY_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
/**
* This is the interface to the Android native activity
*/
@ -32,4 +35,6 @@ void enableAccelerometerJni(void);
void disableAccelerometerJni(void);
void setAccelerometerIntervalJni(float interval);
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#endif // __COCOSNATIVEACTIVITY_H__

View File

@ -23,16 +23,17 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCEGLView.h"
#include "CCSet.h"
#include "ccMacros.h"
#include "CCGLView.h"
#include <unordered_map>
#include "CCDirector.h"
#include "CCIMEDispatcher.h"
#include "CCApplication.h"
#include "CCSet.h"
#include "CCTouch.h"
#include "CCEventDispatcher.h"
#include "CCEventKeyboard.h"
#include "CCEventMouse.h"
#include "CCIMEDispatcher.h"
NS_CC_BEGIN
@ -42,14 +43,13 @@ struct keyCodeItem
EventKeyboard::KeyCode keyCode;
};
static std::map<int, EventKeyboard::KeyCode> g_keyCodeMap;
static std::unordered_map<int, EventKeyboard::KeyCode> g_keyCodeMap;
static keyCodeItem g_keyCodeStructArray[] = {
/* The unknown key */
{ GLFW_KEY_UNKNOWN , EventKeyboard::KeyCode::KEY_NONE },
/* Printable keys */
{ GLFW_KEY_SPACE , EventKeyboard::KeyCode::KEY_SPACE },
{ GLFW_KEY_APOSTROPHE , EventKeyboard::KeyCode::KEY_APOSTROPHE },
{ GLFW_KEY_COMMA , EventKeyboard::KeyCode::KEY_COMMA },
@ -175,37 +175,363 @@ static keyCodeItem g_keyCodeStructArray[] = {
{ GLFW_KEY_LAST , EventKeyboard::KeyCode::KEY_NONE }
};
#if(_MSC_VER >= 1600) // Visual Studio 2010 or higher version.
// Windows Touch define
#define MOUSEEVENTF_FROMTOUCH 0xFF515700
// Windows Touch functions
// Workaround to be able tu run app on Windows XP
typedef WINUSERAPI BOOL (WINAPI *RegisterTouchWindowFn)(_In_ HWND hwnd, _In_ ULONG ulFlags);
typedef WINUSERAPI BOOL (WINAPI *UnregisterTouchWindowFn)(_In_ HWND hwnd);
typedef WINUSERAPI LPARAM (WINAPI *GetMessageExtraInfoFn)(VOID);
typedef WINUSERAPI BOOL (WINAPI *GetTouchInputInfoFn)(_In_ HTOUCHINPUT hTouchInput, _In_ UINT cInputs, __out_ecount(cInputs) PTOUCHINPUT pInputs, _In_ int cbSize);
typedef WINUSERAPI BOOL (WINAPI *CloseTouchInputHandleFn)(_In_ HTOUCHINPUT hTouchInput);
static RegisterTouchWindowFn s_pfRegisterTouchWindowFunction = NULL;
static UnregisterTouchWindowFn s_pfUnregisterTouchWindowFunction = NULL;
static GetMessageExtraInfoFn s_pfGetMessageExtraInfoFunction = NULL;
static GetTouchInputInfoFn s_pfGetTouchInputInfoFunction = NULL;
static CloseTouchInputHandleFn s_pfCloseTouchInputHandleFunction = NULL;
static bool CheckTouchSupport()
//begin GLViewEventHandler
class GLViewEventHandler
{
s_pfRegisterTouchWindowFunction = (RegisterTouchWindowFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "RegisterTouchWindow");
s_pfUnregisterTouchWindowFunction = (UnregisterTouchWindowFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "UnregisterTouchWindow");
s_pfGetMessageExtraInfoFunction = (GetMessageExtraInfoFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "GetMessageExtraInfo");
s_pfGetTouchInputInfoFunction = (GetTouchInputInfoFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "GetTouchInputInfo");
s_pfCloseTouchInputHandleFunction = (CloseTouchInputHandleFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "CloseTouchInputHandle");
public:
static bool s_captured;
static float s_mouseX;
static float s_mouseY;
static void onGLFWError(int errorID, const char* errorDesc);
static void onGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify);
static void onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y);
static void onGLFWMouseScrollCallback(GLFWwindow* window, double x, double y);
static void onGLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
static void onGLFWCharCallback(GLFWwindow* window, unsigned int character);
static void onGLFWWindowPosCallback(GLFWwindow* windows, int x, int y);
static void onGLFWframebuffersize(GLFWwindow* window, int w, int h);
};
return (s_pfRegisterTouchWindowFunction && s_pfUnregisterTouchWindowFunction && s_pfGetMessageExtraInfoFunction && s_pfGetTouchInputInfoFunction && s_pfCloseTouchInputHandleFunction);
bool GLViewEventHandler::s_captured = false;
float GLViewEventHandler::s_mouseX = 0;
float GLViewEventHandler::s_mouseY = 0;
void GLViewEventHandler::onGLFWError(int errorID, const char* errorDesc)
{
CCLOGERROR("GLFWError #%d Happen, %s\n", errorID, errorDesc);
}
#endif /* #if(_MSC_VER >= 1600) */
void GLViewEventHandler::onGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify)
{
GLView* eglView = Director::getInstance()->getOpenGLView();
if(nullptr == eglView) return;
if(GLFW_MOUSE_BUTTON_LEFT == button)
{
if(GLFW_PRESS == action)
{
s_captured = true;
if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY)))
{
int id = 0;
eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY);
}
}
else if(GLFW_RELEASE == action)
{
s_captured = false;
if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY)))
{
int id = 0;
eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY);
}
}
}
if(GLFW_PRESS == action)
{
EventMouse event(EventMouse::MouseEventType::MOUSE_DOWN);
//Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here
event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY);
event.setMouseButton(button);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&event);
}
else if(GLFW_RELEASE == action)
{
EventMouse event(EventMouse::MouseEventType::MOUSE_UP);
//Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here
event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY);
event.setMouseButton(button);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&event);
}
}
void GLViewEventHandler::onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y)
{
GLView* eglView = Director::getInstance()->getOpenGLView();
if(nullptr == eglView) return;
if (eglView->isRetina()) {
x *= 2;
y *= 2;
}
s_mouseX = (float)x;
s_mouseY = (float)y;
s_mouseX /= eglView->getFrameZoomFactor();
s_mouseY /= eglView->getFrameZoomFactor();
if(s_captured)
{
if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY)))
{
int id = 0;
eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY);
}
}
EventMouse event(EventMouse::MouseEventType::MOUSE_MOVE);
//Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here
event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&event);
}
void GLViewEventHandler::onGLFWMouseScrollCallback(GLFWwindow* window, double x, double y)
{
GLView* eglView = Director::getInstance()->getOpenGLView();
if(nullptr == eglView) return;
EventMouse event(EventMouse::MouseEventType::MOUSE_SCROLL);
//Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here
event.setScrollData((float)x, -(float)y);
event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&event);
}
void GLViewEventHandler::onGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods)
{
if (GLFW_REPEAT != action)
{
EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action);
auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&event);
}
}
void GLViewEventHandler::onGLFWCharCallback(GLFWwindow *window, unsigned int character)
{
IMEDispatcher::sharedDispatcher()->dispatchInsertText((const char*) &character, 1);
}
void GLViewEventHandler::onGLFWWindowPosCallback(GLFWwindow *windows, int x, int y)
{
Director::getInstance()->setViewport();
}
void GLViewEventHandler::onGLFWframebuffersize(GLFWwindow* window, int w, int h)
{
auto view = Director::getInstance()->getOpenGLView();
float frameSizeW = view->getFrameSize().width;
float frameSizeH = view->getFrameSize().height;
float factorX = frameSizeW / w * view->getFrameZoomFactor();
float factorY = frameSizeH / h * view->getFrameZoomFactor();;
if (fabs(factorX - 0.5f) < FLT_EPSILON && fabs(factorY - 0.5f) < FLT_EPSILON )
{
view->_isRetina = true;
view->setFrameZoomFactor(2.0f * view->getFrameZoomFactor());
glfwSetWindowSize(window, static_cast<int>(frameSizeW * 0.5f * view->getFrameZoomFactor()) , static_cast<int>(frameSizeH * 0.5f * view->getFrameZoomFactor()));
}
else if(fabs(factorX - 2.0f) < FLT_EPSILON && fabs(factorY - 2.0f) < FLT_EPSILON)
{
view->_isRetina = false;
view->setFrameZoomFactor(0.5f * view->getFrameZoomFactor());
glfwSetWindowSize(window, static_cast<int>(frameSizeW * view->getFrameZoomFactor()), static_cast<int>(frameSizeH * view->getFrameZoomFactor()));
}
}
//end GLViewEventHandler
//////////////////////////////////////////////////////////////////////////
// implement GLView
//////////////////////////////////////////////////////////////////////////
GLView* GLView::create(const std::string& viewName)
{
auto ret = new GLView;
if(ret && ret->initWithRect(viewName, Rect(0, 0, 960, 640), 1)) {
ret->autorelease();
return ret;
}
return nullptr;
}
GLView* GLView::createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor)
{
auto ret = new GLView;
if(ret && ret->initWithRect(viewName, rect, frameZoomFactor)) {
ret->autorelease();
return ret;
}
return nullptr;
}
GLView* GLView::createWithFullScreen(const std::string& viewName)
{
auto ret = new GLView();
if(ret && ret->initWithFullScreen(viewName)) {
ret->autorelease();
return ret;
}
return nullptr;
}
GLView::GLView()
: _captured(false)
, _frameZoomFactor(1.0f)
, _supportTouch(false)
, _isRetina(false)
, _mainWindow(nullptr)
, _primaryMonitor(nullptr)
{
_viewName = "cocos2dx";
g_keyCodeMap.clear();
for (auto& item : g_keyCodeStructArray)
{
g_keyCodeMap[item.glfwKeyCode] = item.keyCode;
}
glfwSetErrorCallback(GLViewEventHandler::onGLFWError);
glfwInit();
}
GLView::~GLView()
{
CCLOGINFO("deallocing GLView: %p", this);
glfwTerminate();
}
bool GLView::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor)
{
setViewName(viewName);
setFrameSize(rect.size.width, rect.size.height);
setFrameZoomFactor(frameZoomFactor);
glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);
_mainWindow = glfwCreateWindow(_screenSize.width * _frameZoomFactor,
_screenSize.height * _frameZoomFactor,
_viewName.c_str(),
_primaryMonitor,
NULL);
glfwMakeContextCurrent(_mainWindow);
int w, h;
glfwGetWindowSize(_mainWindow, &w, &h);
int frameBufferW, frameBufferH;
glfwGetFramebufferSize(_mainWindow, &frameBufferW, &frameBufferH);
if (frameBufferW == 2 * w && frameBufferH == 2 * h)
{
_isRetina = true;
setFrameZoomFactor(frameZoomFactor * 2);
glfwSetWindowSize(_mainWindow, rect.size.width/2 * _frameZoomFactor, rect.size.height/2 * _frameZoomFactor);
}
glfwSetMouseButtonCallback(_mainWindow, GLViewEventHandler::onGLFWMouseCallBack);
glfwSetCursorPosCallback(_mainWindow, GLViewEventHandler::onGLFWMouseMoveCallBack);
glfwSetScrollCallback(_mainWindow, GLViewEventHandler::onGLFWMouseScrollCallback);
glfwSetCharCallback(_mainWindow, GLViewEventHandler::onGLFWCharCallback);
glfwSetKeyCallback(_mainWindow, GLViewEventHandler::onGLFWKeyCallback);
glfwSetWindowPosCallback(_mainWindow, GLViewEventHandler::onGLFWWindowPosCallback);
glfwSetFramebufferSizeCallback(_mainWindow, GLViewEventHandler::onGLFWframebuffersize);
// check OpenGL version at first
const GLubyte* glVersion = glGetString(GL_VERSION);
if ( atof((const char*)glVersion) < 1.5 )
{
char strComplain[256] = {0};
sprintf(strComplain,
"OpenGL 1.5 or higher is required (your version is %s). Please upgrade the driver of your video card.",
glVersion);
MessageBox(strComplain, "OpenGL version too old");
return false;
}
initGlew();
// Enable point size by default.
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
return true;
}
bool GLView::initWithFullScreen(const std::string& viewName)
{
_primaryMonitor = glfwGetPrimaryMonitor();
if (nullptr == _primaryMonitor)
return false;
const GLFWvidmode* videoMode = glfwGetVideoMode(_primaryMonitor);
return initWithRect(viewName, Rect(0, 0, videoMode->width, videoMode->height), 1.0f);
}
bool GLView::isOpenGLReady()
{
return nullptr != _mainWindow;
}
void GLView::end()
{
if(_mainWindow)
glfwSetWindowShouldClose(_mainWindow,1);
}
void GLView::swapBuffers()
{
if(_mainWindow)
glfwSwapBuffers(_mainWindow);
}
bool GLView::windowShouldClose()
{
if(_mainWindow)
return glfwWindowShouldClose(_mainWindow);
else
return true;
}
void GLView::pollEvents()
{
glfwPollEvents();
}
void GLView::setIMEKeyboardState(bool /*bOpen*/)
{
}
void GLView::setFrameZoomFactor(float zoomFactor)
{
_frameZoomFactor = zoomFactor;
Director::getInstance()->setProjection(Director::getInstance()->getProjection());
}
float GLView::getFrameZoomFactor()
{
return _frameZoomFactor;
}
void GLView::setFrameSize(float width, float height)
{
GLViewProtocol::setFrameSize(width, height);
}
void GLView::setViewPortInPoints(float x , float y , float w , float h)
{
glViewport((GLint)(x * _scaleX * _frameZoomFactor + _viewPortRect.origin.x * _frameZoomFactor),
(GLint)(y * _scaleY * _frameZoomFactor + _viewPortRect.origin.y * _frameZoomFactor),
(GLsizei)(w * _scaleX * _frameZoomFactor),
(GLsizei)(h * _scaleY * _frameZoomFactor));
}
void GLView::setScissorInPoints(float x , float y , float w , float h)
{
glScissor((GLint)(x * _scaleX * _frameZoomFactor + _viewPortRect.origin.x * _frameZoomFactor),
(GLint)(y * _scaleY * _frameZoomFactor + _viewPortRect.origin.y * _frameZoomFactor),
(GLsizei)(w * _scaleX * _frameZoomFactor),
(GLsizei)(h * _scaleY * _frameZoomFactor));
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
static bool glew_dynamic_binding()
{
const char *gl_extensions = (const char*)glGetString(GL_EXTENSIONS);
@ -267,201 +593,12 @@ static bool glew_dynamic_binding()
}
return true;
}
//begin EGLViewEventHandler
class EGLViewEventHandler
#endif
// helper
bool GLView::initGlew()
{
public:
static bool s_captured;
static float s_mouseX;
static float s_mouseY;
static void OnGLFWError(int errorID, const char* errorDesc);
static void OnGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify);
static void OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y);
static void OnGLFWMouseScrollCallback(GLFWwindow* window, double x, double y);
static void OnGLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
static void OnGLFWCharCallback(GLFWwindow* window, unsigned int character);
static void OnGLFWWindowPosCallback(GLFWwindow* windows, int x, int y);
};
bool EGLViewEventHandler::s_captured = false;
float EGLViewEventHandler::s_mouseX = 0;
float EGLViewEventHandler::s_mouseY = 0;
void EGLViewEventHandler::OnGLFWError(int errorID, const char* errorDesc)
{
CCLOGERROR("GLFWError #%d Happen, %s\n", errorID, errorDesc);
}
void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify)
{
EGLView* eglView = EGLView::getInstance();
if(nullptr == eglView) return;
if(GLFW_MOUSE_BUTTON_LEFT == button)
{
if(GLFW_PRESS == action)
{
s_captured = true;
if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY)))
{
int id = 0;
eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY);
}
}
else if(GLFW_RELEASE == action)
{
s_captured = false;
if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY)))
{
int id = 0;
eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY);
}
}
}
if(GLFW_PRESS == action)
{
EventMouse event(EventMouse::MouseEventType::MOUSE_DOWN);
event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY);
event.setMouseButton(button);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&event);
}
else if(GLFW_RELEASE == action)
{
EventMouse event(EventMouse::MouseEventType::MOUSE_UP);
event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY);
event.setMouseButton(button);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&event);
}
}
void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y)
{
s_mouseX = (float)x;
s_mouseY = (float)y;
EGLView* eglView = EGLView::getInstance();
if(nullptr == eglView) return;
s_mouseX /= eglView->getFrameZoomFactor();
s_mouseY /= eglView->getFrameZoomFactor();
if(s_captured)
{
if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY)))
{
int id = 0;
eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY);
}
}
EventMouse event(EventMouse::MouseEventType::MOUSE_MOVE);
//Because OpenGL use upper left as origin point, we need to revert the mouse y coordinate here
event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&event);
}
void EGLViewEventHandler::OnGLFWMouseScrollCallback(GLFWwindow* window, double x, double y)
{
EGLView* eglView = EGLView::getInstance();
if(nullptr == eglView) return;
EventMouse event(EventMouse::MouseEventType::MOUSE_SCROLL);
//Because OpenGL use upper left as origin point, we need to revert the mouse y coordinate here
event.setScrollData((float)x, -(float)y);
event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&event);
}
void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods)
{
if (GLFW_REPEAT != action)
{
EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action);
auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&event);
}
}
void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character)
{
IMEDispatcher::sharedDispatcher()->dispatchInsertText((const char*) &character, 1);
}
void EGLViewEventHandler::OnGLFWWindowPosCallback(GLFWwindow *windows, int x, int y)
{
if(Director::getInstance())
{
Director::getInstance()->setViewport();
}
}
//end EGLViewEventHandler
//////////////////////////////////////////////////////////////////////////
// impliment EGLView
//////////////////////////////////////////////////////////////////////////
EGLView* EGLView::s_pEglView = nullptr;
EGLView::EGLView()
: _captured(false)
, _lpfnAccelerometerKeyHook(NULL)
, _frameZoomFactor(1.0f)
, _supportTouch(false)
, _mainWindow(nullptr)
{
CCASSERT(nullptr == s_pEglView, "EGLView is singleton, Should be inited only one time\n");
s_pEglView = this;
g_keyCodeMap.clear();
for (auto& item : g_keyCodeStructArray)
{
g_keyCodeMap.insert(std::make_pair(item.glfwKeyCode, item.keyCode));
}
_viewName = "Cocos2dxWin32";
glfwSetErrorCallback(EGLViewEventHandler::OnGLFWError);
glfwInit();
}
EGLView::~EGLView()
{
glfwTerminate();
s_pEglView = nullptr;
}
bool EGLView::init(const char* viewName, float width, float height, float frameZoomFactor)
{
if(nullptr != _mainWindow) return true;
setViewName(viewName);
setFrameSize(width, height);
setFrameZoomFactor(frameZoomFactor);
glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);
_mainWindow = glfwCreateWindow(_screenSize.width * _frameZoomFactor, _screenSize.height * _frameZoomFactor, _viewName.c_str(), nullptr, nullptr);
glfwMakeContextCurrent(_mainWindow);
glfwGetFramebufferSize(_mainWindow, &_frameBufferSize[0], &_frameBufferSize[1]);
glfwSetMouseButtonCallback(_mainWindow,EGLViewEventHandler::OnGLFWMouseCallBack);
glfwSetCursorPosCallback(_mainWindow,EGLViewEventHandler::OnGLFWMouseMoveCallBack);
glfwSetScrollCallback(_mainWindow, EGLViewEventHandler::OnGLFWMouseScrollCallback);
glfwSetCharCallback(_mainWindow, EGLViewEventHandler::OnGLFWCharCallback);
glfwSetKeyCallback(_mainWindow, EGLViewEventHandler::OnGLFWKeyCallback);
glfwSetWindowPosCallback(_mainWindow, EGLViewEventHandler::OnGLFWWindowPosCallback);
// check OpenGL version at first
const GLubyte* glVersion = glGetString(GL_VERSION);
CCLOG("OpenGL version = %s", glVersion);
if ( atof((const char*)glVersion) < 1.5 )
{
char strComplain[256] = {0};
sprintf(strComplain,
"OpenGL 1.5 or higher is required (your version is %s). Please upgrade the driver of your video card.",
glVersion);
MessageBox(strComplain, "OpenGL version too old");
return false;
}
#if (CC_TARGET_PLATFORM != CC_PLATFORM_MAC)
GLenum GlewInitResult = glewInit();
if (GLEW_OK != GlewInitResult)
{
@ -487,105 +624,17 @@ bool EGLView::init(const char* viewName, float width, float height, float frameZ
log("OpenGL 2.0 not supported");
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
if(glew_dynamic_binding() == false)
{
MessageBox("No OpenGL framebuffer support. Please upgrade the driver of your video card.", "OpenGL error");
return false;
}
}
#endif
// Enable point size by default on windows.
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
#endif // (CC_TARGET_PLATFORM != CC_PLATFORM_MAC)
return true;
}
void EGLView::setAccelerometerKeyHook( LPFN_ACCELEROMETER_KEYHOOK lpfnAccelerometerKeyHook )
{
_lpfnAccelerometerKeyHook=lpfnAccelerometerKeyHook;
}
bool EGLView::isOpenGLReady()
{
return nullptr != _mainWindow;
}
void EGLView::end()
{
if(_mainWindow)
glfwSetWindowShouldClose(_mainWindow,1);
}
void EGLView::swapBuffers()
{
if(_mainWindow)
glfwSwapBuffers(_mainWindow);
}
bool EGLView::windowShouldClose()
{
if(_mainWindow)
return glfwWindowShouldClose(_mainWindow) != 0;
else
return true;
}
void EGLView::pollEvents()
{
glfwPollEvents();
}
void EGLView::setIMEKeyboardState(bool /*bOpen*/)
{
}
void EGLView::setFrameZoomFactor(float fZoomFactor)
{
_frameZoomFactor = fZoomFactor;
Director::getInstance()->setProjection(Director::getInstance()->getProjection());
}
float EGLView::getFrameZoomFactor()
{
return _frameZoomFactor;
}
void EGLView::setFrameSize(float width, float height)
{
EGLViewProtocol::setFrameSize(width, height);
}
void EGLView::setViewPortInPoints(float x , float y , float w , float h)
{
float frameZoomFactorX = _frameBufferSize[0]/_screenSize.width;
float frameZoomFactorY = _frameBufferSize[1]/_screenSize.height;
glViewport((GLint)(x * _scaleX * frameZoomFactorX + _viewPortRect.origin.x * frameZoomFactorX),
(GLint)(y * _scaleY * frameZoomFactorY + _viewPortRect.origin.y * frameZoomFactorY),
(GLsizei)(w * _scaleX * frameZoomFactorX),
(GLsizei)(h * _scaleY * frameZoomFactorY));
}
void EGLView::setScissorInPoints(float x , float y , float w , float h)
{
float frameZoomFactorX = _frameBufferSize[0]/_screenSize.width;
float frameZoomFactorY = _frameBufferSize[1]/_screenSize.height;
glScissor((GLint)(x * _scaleX * frameZoomFactorX + _viewPortRect.origin.x * frameZoomFactorX),
(GLint)(y * _scaleY * frameZoomFactorY + _viewPortRect.origin.y * frameZoomFactorY),
(GLsizei)(w * _scaleX * frameZoomFactorX),
(GLsizei)(h * _scaleY * frameZoomFactorY));
}
EGLView* EGLView::getInstance()
{
CCASSERT(nullptr != s_pEglView, "EGL singleton should not be null");
return s_pEglView;
}
// XXX: deprecated
EGLView* EGLView::sharedOpenGLView()
{
return EGLView::getInstance();
}
NS_CC_END
NS_CC_END // end of namespace cocos2d;

View File

@ -23,82 +23,75 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CC_EGLVIEW_MAC_H__
#define __CC_EGLVIEW_MAC_H__
#ifndef __CC_EGLVIEW_DESKTOP_H__
#define __CC_EGLVIEW_DESKTOP_H__
#include "CCObject.h"
#include "platform/CCCommon.h"
#include "platform/CCEGLViewProtocol.h"
#include "platform/CCGLViewProtocol.h"
#include "glfw3.h"
NS_CC_BEGIN
class CC_DLL EGLView : public EGLViewProtocol
class CC_DLL GLView : public Object, public GLViewProtocol
{
public:
/**
* @js ctor
*/
EGLView();
/**
* @js NA
* @lua NA
*/
virtual ~EGLView();
/* override functions */
virtual bool isOpenGLReady();
virtual void end();
virtual void swapBuffers();
virtual void setFrameSize(float width, float height);
virtual void setIMEKeyboardState(bool bOpen);
static GLView* create(const std::string& viewName);
static GLView* createWithRect(const std::string& viewName, Rect size, float frameZoomFactor = 1.0f);
static GLView* createWithFullScreen(const std::string& viewName);
/*
*frameZoomFactor for frame. This method is for debugging big resolution (e.g.new ipad) app on desktop.
*/
bool init(const std::string& viewName, float width, float height, float frameZoomFactor = 1.0f);
public:
//void resize(int width, int height);
float getFrameZoomFactor();
float getFrameZoomFactor();
//void centerWindow();
virtual void setViewPortInPoints(float x , float y , float w , float h);
virtual void setScissorInPoints(float x , float y , float w , float h);
// static function
/**
@brief get the shared main open gl window
*/
static EGLView* getInstance();
/** @deprecated Use getInstance() instead */
CC_DEPRECATED_ATTRIBUTE static EGLView* sharedOpenGLView();
inline bool isRetina() { return _isRetina; };
bool windowShouldClose();
void pollEvents();
GLFWwindow* getWindow() const { return _mainWindow; }
/* override functions */
virtual bool isOpenGLReady() override;
virtual void end() override;
virtual void swapBuffers() override;
virtual void setFrameSize(float width, float height) override;
virtual void setIMEKeyboardState(bool bOpen) override;
protected:
GLView();
virtual ~GLView();
bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor);
bool initWithFullScreen(const std::string& viewName);
/*
* Set zoom factor for frame. This method is for debugging big resolution (e.g.new ipad) app on desktop.
*/
void setFrameZoomFactor(float zoomFactor);
private:
bool initGlew();
inline bool isRetina() { return _isRetina; };
bool _captured;
bool _supportTouch;
bool _isRetina;
float _frameZoomFactor;
static EGLView* s_pEglView;
public:
bool windowShouldClose();
void pollEvents();
GLFWwindow* getWindow() const { return _mainWindow; }
private:
GLFWwindow* _mainWindow;
friend class EGLViewEventHandler;
GLFWmonitor* _primaryMonitor;
friend class GLViewEventHandler;
private:
CC_DISALLOW_COPY_AND_ASSIGN(GLView);
};
NS_CC_END // end of namespace cocos2d
#endif // end of __CC_EGLVIEW_MAC_H__
#endif // end of __CC_EGLVIEW_DESKTOP_H__

View File

@ -26,6 +26,9 @@ THE SOFTWARE.
#ifndef __CC_APPLICATION_IOS_H__
#define __CC_APPLICATION_IOS_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#include "platform/CCCommon.h"
#include "platform/CCApplicationProtocol.h"
@ -90,4 +93,6 @@ protected:
NS_CC_END
#endif // CC_PLATFORM_IOS
#endif // end of __CC_APPLICATION_IOS_H__

View File

@ -25,6 +25,8 @@
#import "CCApplication.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#import <UIKit/UIKit.h>
#import "CCGeometry.h"
@ -108,6 +110,9 @@ LanguageType Application::getCurrentLanguage()
else if ([languageCode isEqualToString:@"es"]){
ret = LanguageType::SPANISH;
}
else if ([languageCode isEqualToString:@"nl"]){
ret = LanguageType::DUTCH;
}
else if ([languageCode isEqualToString:@"ru"]){
ret = LanguageType::RUSSIAN;
}
@ -152,3 +157,5 @@ void Application::applicationScreenSizeChanged(int newWidth, int newHeight) {
}
NS_CC_END
#endif // CC_PLATFORM_IOS

View File

@ -23,6 +23,9 @@
THE SOFTWARE.
****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#include "platform/CCCommon.h"
#include <stdarg.h>
@ -54,3 +57,5 @@ void LuaLog(const char * format)
}
NS_CC_END
#endif // CC_PLATFORM_IOS

View File

@ -22,6 +22,11 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#include "CCDevice.h"
#include "ccTypes.h"
#include "CCEventDispatcher.h"
@ -174,3 +179,5 @@ void Device::setAccelerometerInterval(float interval)
NS_CC_END
#endif // CC_PLATFORM_IOS

View File

@ -61,6 +61,9 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved.
*/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#import <UIKit/UIKit.h>
#import <OpenGLES/EAGL.h>
#import <OpenGLES/EAGLDrawable.h>
@ -119,9 +122,6 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved.
/** creates an initializes an CCEAGLView with a frame, a color buffer format, a depth buffer format, a sharegroup, and multisamping */
+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples;
// get the view object
+(id) sharedEGLView;
/** Initializes an CCEAGLView with a frame and 0-bit depth buffer, and a RGB565 color buffer */
- (id) initWithFrame:(CGRect)frame; //These also set the current context
/** Initializes an CCEAGLView with a frame, a color buffer format, and 0-bit depth buffer */
@ -155,3 +155,5 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved.
-(void) doAnimationWhenKeyboardMoveWithDuration:(float) duration distance:(float) dis;
-(void) doAnimationWhenAnotherEditBeClicked;
@end
#endif // CC_PLATFORM_IOS

View File

@ -61,22 +61,23 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved.
*/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#import <QuartzCore/QuartzCore.h>
#import "CCEGLView.h"
#import "EAGLView.h"
#import "CCGLView.h"
#import "CCEAGLView.h"
#import "CCES2Renderer.h"
#import "CCDirector.h"
#import "CCSet.h"
#import "CCTouch.h"
#import "CCIMEDispatcher.h"
#import "OpenGL_Internal.h"
#import "CCEGLView.h"
#import "CCGLView.h"
//CLASS IMPLEMENTATIONS:
#define IOS_MAX_TOUCHES_COUNT 10
static CCEAGLView *__view = 0;
@interface CCEAGLView (Private)
- (BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup;
- (unsigned int) convertPixelFormat:(NSString*) pixelFormat;
@ -115,11 +116,6 @@ static CCEAGLView *__view = 0;
return [[[self alloc]initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:retained sharegroup:sharegroup multiSampling:multisampling numberOfSamples:samples] autorelease];
}
+ (id) sharedEGLView
{
return __view;
}
- (id) initWithFrame:(CGRect)frame
{
return [self initWithFrame:frame pixelFormat:kEAGLColorFormatRGB565 depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0];
@ -146,15 +142,13 @@ static CCEAGLView *__view = 0;
return nil;
}
__view = self;
originalRect_ = self.frame;
self.keyboardShowNotification = nil;
if ([__view respondsToSelector:@selector(setContentScaleFactor:)])
if ([self respondsToSelector:@selector(setContentScaleFactor:)])
{
__view.contentScaleFactor = [[UIScreen mainScreen] scale];
self.contentScaleFactor = [[UIScreen mainScreen] scale];
}
}
@ -180,7 +174,6 @@ static CCEAGLView *__view = 0;
}
}
__view = self;
return self;
}
@ -409,11 +402,13 @@ static CCEAGLView *__view = 0;
int i = 0;
for (UITouch *touch in touches) {
ids[i] = touch;
xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;;
ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;;
xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor;;
ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor;;
++i;
}
cocos2d::EGLView::getInstance()->handleTouchesBegin(i, (int*)ids, xs, ys);
auto glview = cocos2d::Director::getInstance()->getOpenGLView();
glview->handleTouchesBegin(i, (int*)ids, xs, ys);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
@ -429,11 +424,13 @@ static CCEAGLView *__view = 0;
int i = 0;
for (UITouch *touch in touches) {
ids[i] = touch;
xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;;
ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;;
xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor;;
ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor;;
++i;
}
cocos2d::EGLView::getInstance()->handleTouchesMove(i, (int*)ids, xs, ys);
auto glview = cocos2d::Director::getInstance()->getOpenGLView();
glview->handleTouchesMove(i, (int*)ids, xs, ys);
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
@ -450,11 +447,13 @@ static CCEAGLView *__view = 0;
int i = 0;
for (UITouch *touch in touches) {
ids[i] = touch;
xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;;
ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;;
xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor;;
ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor;;
++i;
}
cocos2d::EGLView::getInstance()->handleTouchesEnd(i, (int*)ids, xs, ys);
auto glview = cocos2d::Director::getInstance()->getOpenGLView();
glview->handleTouchesEnd(i, (int*)ids, xs, ys);
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
@ -471,11 +470,13 @@ static CCEAGLView *__view = 0;
int i = 0;
for (UITouch *touch in touches) {
ids[i] = touch;
xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;;
ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;;
xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor;;
ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor;;
++i;
}
cocos2d::EGLView::getInstance()->handleTouchesCancel(i, (int*)ids, xs, ys);
auto glview = cocos2d::Director::getInstance()->getOpenGLView();
glview->handleTouchesCancel(i, (int*)ids, xs, ys);
}
#pragma mark - UIView - Responder
@ -794,9 +795,10 @@ static CCEAGLView *__view = 0;
default:
break;
}
float scaleX = cocos2d::EGLView::getInstance()->getScaleX();
float scaleY = cocos2d::EGLView::getInstance()->getScaleY();
auto glview = cocos2d::Director::getInstance()->getOpenGLView();
float scaleX = glview->getScaleX();
float scaleY = glview->getScaleY();
if (self.contentScaleFactor == 2.0f)
@ -807,7 +809,7 @@ static CCEAGLView *__view = 0;
end = CGRectApplyAffineTransform(end, CGAffineTransformScale(CGAffineTransformIdentity, 2.0f, 2.0f));
}
float offestY = cocos2d::EGLView::getInstance()->getViewPortRect().origin.y;
float offestY = glview->getViewPortRect().origin.y;
CCLOG("offestY = %f", offestY);
if (offestY < 0.0f)
{
@ -866,11 +868,12 @@ static CCEAGLView *__view = 0;
[UIView setAnimationDuration:duration];
[UIView setAnimationBeginsFromCurrentState:YES];
//NSLog(@"[animation] dis = %f, scale = %f \n", dis, cocos2d::EGLView::getInstance()->getScaleY());
//NSLog(@"[animation] dis = %f, scale = %f \n", dis, cocos2d::GLView::getInstance()->getScaleY());
if (dis < 0.0f) dis = 0.0f;
dis *= cocos2d::EGLView::getInstance()->getScaleY();
auto glview = cocos2d::Director::getInstance()->getOpenGLView();
dis *= glview->getScaleY();
if (self.contentScaleFactor == 2.0f)
{
@ -912,3 +915,5 @@ static CCEAGLView *__view = 0;
}
@end
#endif // CC_PLATFORM_IOS

View File

@ -1,92 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
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 __CC_EGLVIEW_IPHONE_H__
#define __CC_EGLVIEW_IPHONE_H__
#include "platform/CCCommon.h"
#include "platform/CCEGLViewProtocol.h"
NS_CC_BEGIN
class CC_DLL EGLView : public EGLViewProtocol
{
public:
/**
* @js NA
* @lua NA
*/
EGLView();
/**
* @js NA
* @lua NA
*/
~EGLView();
/**
* @js NA
* @lua NA
*/
virtual bool isOpenGLReady();
/**
* @js NA
* @lua NA
*/
virtual bool setContentScaleFactor(float contentScaleFactor);
// keep compatible
/**
* @js NA
* @lua NA
*/
virtual void end();
/**
* @js NA
* @lua NA
*/
virtual void swapBuffers();
/**
* @js NA
* @lua NA
*/
virtual void setIMEKeyboardState(bool bOpen);
/** returns the singleton
* @js NA
*/
static EGLView* getInstance();
/** @deprecated Use getInstance() instead
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE static EGLView* sharedOpenGLView();
};
NS_CC_END
#endif // end of __CC_EGLVIEW_IPHONE_H__

View File

@ -1,98 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
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.
****************************************************************************/
#include "EAGLView.h"
#include "CCDirectorCaller.h"
#include "CCEGLView.h"
#include "CCSet.h"
#include "CCTouch.h"
NS_CC_BEGIN
EGLView::EGLView()
{
_screenSize.width = _designResolutionSize.width = [[CCEAGLView sharedEGLView] getWidth];
_screenSize.height = _designResolutionSize.height = [[CCEAGLView sharedEGLView] getHeight];
}
EGLView::~EGLView()
{
}
bool EGLView::isOpenGLReady()
{
return [CCEAGLView sharedEGLView] != nullptr;
}
bool EGLView::setContentScaleFactor(float contentScaleFactor)
{
assert(_resolutionPolicy == ResolutionPolicy::UNKNOWN); // cannot enable retina mode
_scaleX = _scaleY = contentScaleFactor;
[[CCEAGLView sharedEGLView] setNeedsLayout];
return true;
}
void EGLView::end()
{
[CCDirectorCaller destroy];
// destroy EAGLView
[[CCEAGLView sharedEGLView] removeFromSuperview];
}
void EGLView::swapBuffers()
{
[[CCEAGLView sharedEGLView] swapBuffers];
}
void EGLView::setIMEKeyboardState(bool bOpen)
{
if (bOpen)
{
[[CCEAGLView sharedEGLView] becomeFirstResponder];
}
else
{
[[CCEAGLView sharedEGLView] resignFirstResponder];
}
}
EGLView* EGLView::getInstance()
{
static EGLView instance;
return &instance;
}
// XXX: deprecated
EGLView* EGLView::sharedOpenGLView()
{
return EGLView::getInstance();
}
NS_CC_END

View File

@ -27,6 +27,10 @@
// Only compile this code on iOS. These files should NOT be included on your Mac project.
// But in case they are included, it won't be compiled.
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#import "CCPlatformMacros.h"
#import "CCESRenderer.h"
#import <OpenGLES/ES2/gl.h>
@ -76,4 +80,4 @@
@end
#endif // CC_PLATFORM_IOS

View File

@ -28,8 +28,11 @@
// Only compile this code on iOS. These files should NOT be included on your Mac project.
// But in case they are included, it won't be compiled.
#import "CCPlatformMacros.h"
#import "CCES2Renderer.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#import "CCPlatformMacros.h"
#import "OpenGL_Internal.h"
#if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0
@ -251,3 +254,5 @@
@end
#endif // CC_PLATFORM_IOS

View File

@ -27,6 +27,10 @@
// Only compile this code on iOS. These files should NOT be included on your Mac project.
// But in case they are included, it won't be compiled.
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#include "CCPlatformMacros.h"
#import <QuartzCore/QuartzCore.h>
@ -48,3 +52,4 @@
- (unsigned int) msaaColorBuffer;
@end
#endif // CC_PLATFORM_IOS

View File

@ -26,6 +26,9 @@ THE SOFTWARE.
#ifndef __PLATFORM_IOS_CCGL_H__
#define __PLATFORM_IOS_CCGL_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#define glClearDepth glClearDepthf
#define glDeleteVertexArrays glDeleteVertexArraysOES
#define glGenVertexArrays glGenVertexArraysOES
@ -39,5 +42,7 @@ THE SOFTWARE.
#include <OpenGLES/ES2/gl.h>
#include <OpenGLES/ES2/glext.h>
#endif // CC_PLATFORM_IOS
#endif // __PLATFORM_IOS_CCGL_H__

View File

@ -0,0 +1,90 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
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 __CC_EGLVIEW_IPHONE_H__
#define __CC_EGLVIEW_IPHONE_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#include "CCObject.h"
#include "platform/CCCommon.h"
#include "platform/CCGLViewProtocol.h"
NS_CC_BEGIN
/** Class that represent the OpenGL View
*/
class CC_DLL GLView : public Object, public GLViewProtocol
{
public:
/** creates a GLView with a objective-c CCEAGLView instance */
static GLView* createWithEAGLView(void* eaglview);
/** creates a GLView with a title name in fullscreen mode */
static GLView* create(const std::string& viewName);
/** creates a GLView with a title name, a rect and the zoom factor */
static GLView* createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor = 1.0f);
/** creates a GLView with a name in fullscreen mode */
static GLView* createWithFullScreen(const std::string& viewName);
/** sets the content scale factor */
bool setContentScaleFactor(float contentScaleFactor);
/** returns the content scale factor */
float getContentScaleFactor() const;
/** returns whether or not the view is in Retina Display mode */
bool isRetinaDisplay() const { return getContentScaleFactor() == 2.0; }
/** returns the objective-c CCEAGLView instance */
void* getEAGLView() const { return _eaglview; }
// overrides
virtual bool isOpenGLReady() override;
virtual void end() override;
virtual void swapBuffers() override;
virtual void setIMEKeyboardState(bool bOpen) override;
protected:
GLView();
virtual ~GLView();
bool initWithEAGLView(void* eaglview);
bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor);
bool initWithFullScreen(const std::string& viewName);
// the objective-c CCEAGLView instance
void *_eaglview;
};
NS_CC_END
#endif // CC_PLATFORM_IOS
#endif // end of __CC_EGLVIEW_IPHONE_H__

View File

@ -0,0 +1,201 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
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.
****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#import <UIKit/UIKit.h>
#include "CCEAGLView.h"
#include "CCDirectorCaller.h"
#include "CCGLView.h"
#include "CCSet.h"
#include "CCTouch.h"
NS_CC_BEGIN
GLView* GLView::createWithEAGLView(void *eaglview)
{
auto ret = new GLView;
if(ret && ret->initWithEAGLView(eaglview)) {
ret->autorelease();
return ret;
}
return nullptr;
}
GLView* GLView::create(const std::string& viewName)
{
auto ret = new GLView;
if(ret && ret->initWithFullScreen(viewName)) {
ret->autorelease();
return ret;
}
return nullptr;
}
GLView* GLView::createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor)
{
auto ret = new GLView;
if(ret && ret->initWithRect(viewName, rect, frameZoomFactor)) {
ret->autorelease();
return ret;
}
return nullptr;
}
GLView* GLView::createWithFullScreen(const std::string& viewName)
{
auto ret = new GLView();
if(ret && ret->initWithFullScreen(viewName)) {
ret->autorelease();
return ret;
}
return nullptr;
}
GLView::GLView()
{
}
GLView::~GLView()
{
CCEAGLView *glview = (CCEAGLView*) _eaglview;
[glview release];
}
bool GLView::initWithEAGLView(void *eaglview)
{
_eaglview = eaglview;
CCEAGLView *glview = (CCEAGLView*) _eaglview;
_screenSize.width = _designResolutionSize.width = [glview getWidth];
_screenSize.height = _designResolutionSize.height = [glview getHeight];
// _scaleX = _scaleY = [glview contentScaleFactor];
return true;
}
bool GLView::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor)
{
CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
CCEAGLView *eaglview = [CCEAGLView viewWithFrame: r
pixelFormat: kEAGLColorFormatRGB565
depthFormat: GL_DEPTH24_STENCIL8_OES
preserveBackbuffer: NO
sharegroup: nil
multiSampling: NO
numberOfSamples: 0];
[eaglview setMultipleTouchEnabled:YES];
_screenSize.width = _designResolutionSize.width = [eaglview getWidth];
_screenSize.height = _designResolutionSize.height = [eaglview getHeight];
// _scaleX = _scaleY = [eaglview contentScaleFactor];
_eaglview = eaglview;
return true;
}
bool GLView::initWithFullScreen(const std::string& viewName)
{
CGRect rect = [[UIScreen mainScreen] bounds];
Rect r;
r.origin.x = rect.origin.x;
r.origin.y = rect.origin.y;
r.size.width = rect.size.width;
r.size.height = rect.size.height;
return initWithRect(viewName, r, 1);
}
bool GLView::isOpenGLReady()
{
return _eaglview != nullptr;
}
bool GLView::setContentScaleFactor(float contentScaleFactor)
{
CC_ASSERT(_resolutionPolicy == ResolutionPolicy::UNKNOWN); // cannot enable retina mode
_scaleX = _scaleY = contentScaleFactor;
CCEAGLView *eaglview = (CCEAGLView*) _eaglview;
[eaglview setNeedsLayout];
return true;
}
float GLView::getContentScaleFactor() const
{
CCEAGLView *eaglview = (CCEAGLView*) _eaglview;
float scaleFactor = [eaglview contentScaleFactor];
// CCASSERT(scaleFactor == _scaleX == _scaleY, "Logic error in GLView::getContentScaleFactor");
return scaleFactor;
}
void GLView::end()
{
[CCDirectorCaller destroy];
// destroy EAGLView
CCEAGLView *eaglview = (CCEAGLView*) _eaglview;
[eaglview removeFromSuperview];
[eaglview release];
}
void GLView::swapBuffers()
{
CCEAGLView *eaglview = (CCEAGLView*) _eaglview;
[eaglview swapBuffers];
}
void GLView::setIMEKeyboardState(bool open)
{
CCEAGLView *eaglview = (CCEAGLView*) _eaglview;
if (open)
{
[eaglview becomeFirstResponder];
}
else
{
[eaglview resignFirstResponder];
}
}
NS_CC_END
#endif // CC_PLATFOR_IOS

View File

@ -22,6 +22,10 @@ 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.
****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#include "CCImageCommon_cpp.h"
#import "CCImage.h"
@ -468,3 +472,5 @@ bool Image::saveToFile(const std::string& filename, bool isToRGB)
NS_CC_END
#endif // CC_PLATFORM_IOS

View File

@ -25,6 +25,9 @@ THE SOFTWARE.
#ifndef __CCPLATFORMDEFINE_H__
#define __CCPLATFORMDEFINE_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#include <assert.h>
#define CC_DLL
@ -44,5 +47,6 @@ THE SOFTWARE.
#endif
#endif // CC_PLATFORM_IOS
#endif /* __CCPLATFORMDEFINE_H__*/

View File

@ -26,6 +26,9 @@ THE SOFTWARE.
#ifndef __CC_STD_C_H__
#define __CC_STD_C_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#include "CCPlatformMacros.h"
#include <float.h>
#include <math.h>
@ -45,4 +48,5 @@ THE SOFTWARE.
#define MAX(x,y) (((x) < (y)) ? (y) : (x))
#endif // MAX
#endif // CC_PLATFORM_IOS
#endif // __CC_STD_C_H__

View File

@ -61,6 +61,9 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved.
*/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
/* Generic error reporting */
#define REPORT_ERROR(__FORMAT__, ...) printf("%s: %s\n", __FUNCTION__, [[NSString stringWithFormat:__FORMAT__, __VA_ARGS__] UTF8String])
@ -79,3 +82,5 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved.
#endif
#define TEST_DELEGATE_METHOD_BIT(__BIT__) (self->__DELEGATE_METHODS_IVAR__ & (1 << __BIT__))
#define SET_DELEGATE_METHOD_BIT(__BIT__, __NAME__) { if([self->__DELEGATE_IVAR__ respondsToSelector:@selector(__NAME__)]) self->__DELEGATE_METHODS_IVAR__ |= (1 << __BIT__); else self->__DELEGATE_METHODS_IVAR__ &= ~(1 << __BIT__); }
#endif // CC_PLATFORM_IOS

View File

@ -23,6 +23,10 @@ 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.
****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#import <TargetConditionals.h>
// when compiling to ARM (iPhone device), hide everything and use system defaults
@ -73,4 +77,6 @@ THE SOFTWARE.
@end
#endif
#endif // !TARGET_CPU_ARM
#endif // CC_PLATFORM_IOS

View File

@ -26,6 +26,8 @@ THE SOFTWARE.
#import "AccelerometerSimulation.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
// when compiling to ARM (iPhone device), hide everything and use system defaults
// if you wish to use simulation mode even on the device, remove the #if/#endif
#if !TARGET_CPU_ARM
@ -263,4 +265,6 @@ static CCAccelerometerSimulation *sharedAccelerometer = NULL;
}
@end
#endif
#endif // !TARGET_CPU_ARM
#endif // CC_PLATFORM_IOS

View File

@ -23,13 +23,16 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
#include "CCApplication.h"
#include <unistd.h>
#include <sys/time.h>
#include <string>
#include "CCDirector.h"
#include "platform/CCFileUtils.h"
#include "CCEGLView.h"
#include "CCGLView.h"
NS_CC_BEGIN
@ -38,61 +41,62 @@ NS_CC_BEGIN
Application * Application::sm_pSharedApplication = 0;
static long getCurrentMillSecond() {
long lLastTime;
struct timeval stCurrentTime;
long lLastTime;
struct timeval stCurrentTime;
gettimeofday(&stCurrentTime,NULL);
lLastTime = stCurrentTime.tv_sec*1000+stCurrentTime.tv_usec*0.001; //millseconds
return lLastTime;
gettimeofday(&stCurrentTime,NULL);
lLastTime = stCurrentTime.tv_sec*1000+stCurrentTime.tv_usec*0.001; //millseconds
return lLastTime;
}
Application::Application()
{
CC_ASSERT(! sm_pSharedApplication);
sm_pSharedApplication = this;
CC_ASSERT(! sm_pSharedApplication);
sm_pSharedApplication = this;
}
Application::~Application()
{
CC_ASSERT(this == sm_pSharedApplication);
sm_pSharedApplication = NULL;
_animationInterval = 1.0f/60.0f*1000.0f;
CC_ASSERT(this == sm_pSharedApplication);
sm_pSharedApplication = NULL;
_animationInterval = 1.0f/60.0f*1000.0f;
}
int Application::run()
{
// Initialize instance and cocos2d.
if (! applicationDidFinishLaunching())
{
return 0;
}
EGLView* pMainWnd = EGLView::getInstance();
while (!pMainWnd->windowShouldClose())
// Initialize instance and cocos2d.
if (! applicationDidFinishLaunching())
{
long iLastTime = getCurrentMillSecond();
Director::getInstance()->mainLoop();
pMainWnd->pollEvents();
long iCurTime = getCurrentMillSecond();
if (iCurTime-iLastTime<_animationInterval){
usleep((_animationInterval - iCurTime+iLastTime)*1000);
}
return 0;
}
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
while (!glview->windowShouldClose())
{
long iLastTime = getCurrentMillSecond();
director->mainLoop();
glview->pollEvents();
long iCurTime = getCurrentMillSecond();
if (iCurTime-iLastTime<_animationInterval){
usleep((_animationInterval - iCurTime+iLastTime)*1000);
}
}
/* Only work on Desktop
* Director::mainLoop is really one frame logic
* when we want to close the window, we should call Director::end();
* then call Director::mainLoop to do release of internal resources
*/
Director::getInstance()->end();
Director::getInstance()->mainLoop();
return -1;
director->end();
director->mainLoop();
return -1;
}
void Application::setAnimationInterval(double interval)
{
//TODO do something else
_animationInterval = interval*1000.0f;
//TODO do something else
_animationInterval = interval*1000.0f;
}
void Application::setResourceRootPath(const std::string& rootResDir)
@ -123,8 +127,8 @@ Application::Platform Application::getTargetPlatform()
//////////////////////////////////////////////////////////////////////////
Application* Application::getInstance()
{
CC_ASSERT(sm_pSharedApplication);
return sm_pSharedApplication;
CC_ASSERT(sm_pSharedApplication);
return sm_pSharedApplication;
}
// @deprecated Use getInstance() instead
@ -171,6 +175,10 @@ LanguageType Application::getCurrentLanguage()
{
ret = LanguageType::SPANISH;
}
else if (0 == strcmp("nl", pLanguageName))
{
ret = LanguageType::DUTCH;
}
else if (0 == strcmp("ru", pLanguageName))
{
ret = LanguageType::RUSSIAN;
@ -188,23 +196,26 @@ LanguageType Application::getCurrentLanguage()
ret = LanguageType::HUNGARIAN;
}
else if (0 == strcmp("pt", pLanguageName))
{
ret = LanguageType::PORTUGUESE;
}
{
ret = LanguageType::PORTUGUESE;
}
else if (0 == strcmp("ar", pLanguageName))
{
ret = LanguageType::ARABIC;
}
else if (0 == strcmp("nb", pLanguageName))
{
ret = LanguageType::NORWEGIAN;
}
else if (0 == strcmp("pl", pLanguageName))
{
ret = LanguageType::POLISH;
}
return ret;
{
ret = LanguageType::ARABIC;
}
else if (0 == strcmp("nb", pLanguageName))
{
ret = LanguageType::NORWEGIAN;
}
else if (0 == strcmp("pl", pLanguageName))
{
ret = LanguageType::POLISH;
}
return ret;
}
NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX

View File

@ -26,6 +26,9 @@ THE SOFTWARE.
#ifndef CCAPLICATION_H_
#define CCAPLICATION_H_
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
#include "platform/CCCommon.h"
#include "platform/CCApplicationProtocol.h"
#include <string>
@ -94,4 +97,6 @@ protected:
NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
#endif /* CCAPLICATION_H_ */

View File

@ -22,6 +22,10 @@ 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.
****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
#include "platform/CCCommon.h"
#include "CCStdC.h"
#include "CCConsole.h"
@ -39,3 +43,5 @@ void LuaLog(const char * format)
}
NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX

View File

@ -22,6 +22,10 @@ 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.
****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
#include "platform/CCDevice.h"
#include <X11/Xlib.h>
#include <stdio.h>
@ -64,3 +68,5 @@ void Device::setAccelerometerInterval(float interval)
}
NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX

View File

@ -1,480 +0,0 @@
/****************************************************************************
Copyright (c) 2011 Laschweinski
Copyright (c) 2013-2014 Chukong Technologies Inc.
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.
****************************************************************************/
#include "CCEGLView.h"
#include "CCGL.h"
#include "ccMacros.h"
#include "CCDirector.h"
#include "CCTouch.h"
#include "CCIMEDispatcher.h"
#include "CCEventDispatcher.h"
#include "CCEventKeyboard.h"
#include "CCEventMouse.h"
#include <unistd.h>
NS_CC_BEGIN
static std::map<int, EventKeyboard::KeyCode> g_keyCodeMap = {
/* The unknown key */
{ GLFW_KEY_UNKNOWN , EventKeyboard::KeyCode::KEY_NONE },
/* Printable keys */
{ GLFW_KEY_SPACE , EventKeyboard::KeyCode::KEY_SPACE },
{ GLFW_KEY_APOSTROPHE , EventKeyboard::KeyCode::KEY_APOSTROPHE },
{ GLFW_KEY_COMMA , EventKeyboard::KeyCode::KEY_COMMA },
{ GLFW_KEY_MINUS , EventKeyboard::KeyCode::KEY_MINUS },
{ GLFW_KEY_PERIOD , EventKeyboard::KeyCode::KEY_PERIOD },
{ GLFW_KEY_SLASH , EventKeyboard::KeyCode::KEY_SLASH },
{ GLFW_KEY_0 , EventKeyboard::KeyCode::KEY_0 },
{ GLFW_KEY_1 , EventKeyboard::KeyCode::KEY_1 },
{ GLFW_KEY_2 , EventKeyboard::KeyCode::KEY_2 },
{ GLFW_KEY_3 , EventKeyboard::KeyCode::KEY_3 },
{ GLFW_KEY_4 , EventKeyboard::KeyCode::KEY_4 },
{ GLFW_KEY_5 , EventKeyboard::KeyCode::KEY_5 },
{ GLFW_KEY_6 , EventKeyboard::KeyCode::KEY_6 },
{ GLFW_KEY_7 , EventKeyboard::KeyCode::KEY_7 },
{ GLFW_KEY_8 , EventKeyboard::KeyCode::KEY_8 },
{ GLFW_KEY_9 , EventKeyboard::KeyCode::KEY_9 },
{ GLFW_KEY_SEMICOLON , EventKeyboard::KeyCode::KEY_SEMICOLON },
{ GLFW_KEY_EQUAL , EventKeyboard::KeyCode::KEY_EQUAL },
{ GLFW_KEY_A , EventKeyboard::KeyCode::KEY_A },
{ GLFW_KEY_B , EventKeyboard::KeyCode::KEY_B },
{ GLFW_KEY_C , EventKeyboard::KeyCode::KEY_C },
{ GLFW_KEY_D , EventKeyboard::KeyCode::KEY_D },
{ GLFW_KEY_E , EventKeyboard::KeyCode::KEY_E },
{ GLFW_KEY_F , EventKeyboard::KeyCode::KEY_F },
{ GLFW_KEY_G , EventKeyboard::KeyCode::KEY_G },
{ GLFW_KEY_H , EventKeyboard::KeyCode::KEY_H },
{ GLFW_KEY_I , EventKeyboard::KeyCode::KEY_I },
{ GLFW_KEY_J , EventKeyboard::KeyCode::KEY_J },
{ GLFW_KEY_K , EventKeyboard::KeyCode::KEY_K },
{ GLFW_KEY_L , EventKeyboard::KeyCode::KEY_L },
{ GLFW_KEY_M , EventKeyboard::KeyCode::KEY_M },
{ GLFW_KEY_N , EventKeyboard::KeyCode::KEY_N },
{ GLFW_KEY_O , EventKeyboard::KeyCode::KEY_O },
{ GLFW_KEY_P , EventKeyboard::KeyCode::KEY_P },
{ GLFW_KEY_Q , EventKeyboard::KeyCode::KEY_Q },
{ GLFW_KEY_R , EventKeyboard::KeyCode::KEY_R },
{ GLFW_KEY_S , EventKeyboard::KeyCode::KEY_S },
{ GLFW_KEY_T , EventKeyboard::KeyCode::KEY_T },
{ GLFW_KEY_U , EventKeyboard::KeyCode::KEY_U },
{ GLFW_KEY_V , EventKeyboard::KeyCode::KEY_V },
{ GLFW_KEY_W , EventKeyboard::KeyCode::KEY_W },
{ GLFW_KEY_X , EventKeyboard::KeyCode::KEY_X },
{ GLFW_KEY_Y , EventKeyboard::KeyCode::KEY_Y },
{ GLFW_KEY_Z , EventKeyboard::KeyCode::KEY_Z },
{ GLFW_KEY_LEFT_BRACKET , EventKeyboard::KeyCode::KEY_LEFT_BRACKET },
{ GLFW_KEY_BACKSLASH , EventKeyboard::KeyCode::KEY_BACK_SLASH },
{ GLFW_KEY_RIGHT_BRACKET , EventKeyboard::KeyCode::KEY_RIGHT_BRACKET },
{ GLFW_KEY_GRAVE_ACCENT , EventKeyboard::KeyCode::KEY_GRAVE },
{ GLFW_KEY_WORLD_1 , EventKeyboard::KeyCode::KEY_GRAVE },
{ GLFW_KEY_WORLD_2 , EventKeyboard::KeyCode::KEY_NONE },
/* Function keys */
{ GLFW_KEY_ESCAPE , EventKeyboard::KeyCode::KEY_ESCAPE },
{ GLFW_KEY_ENTER , EventKeyboard::KeyCode::KEY_KP_ENTER },
{ GLFW_KEY_TAB , EventKeyboard::KeyCode::KEY_TAB },
{ GLFW_KEY_BACKSPACE , EventKeyboard::KeyCode::KEY_BACKSPACE },
{ GLFW_KEY_INSERT , EventKeyboard::KeyCode::KEY_INSERT },
{ GLFW_KEY_DELETE , EventKeyboard::KeyCode::KEY_DELETE },
{ GLFW_KEY_RIGHT , EventKeyboard::KeyCode::KEY_RIGHT_ARROW },
{ GLFW_KEY_LEFT , EventKeyboard::KeyCode::KEY_LEFT_ARROW },
{ GLFW_KEY_DOWN , EventKeyboard::KeyCode::KEY_DOWN_ARROW },
{ GLFW_KEY_UP , EventKeyboard::KeyCode::KEY_UP_ARROW },
{ GLFW_KEY_PAGE_UP , EventKeyboard::KeyCode::KEY_KP_PG_UP },
{ GLFW_KEY_PAGE_DOWN , EventKeyboard::KeyCode::KEY_KP_PG_DOWN },
{ GLFW_KEY_HOME , EventKeyboard::KeyCode::KEY_KP_HOME },
{ GLFW_KEY_END , EventKeyboard::KeyCode::KEY_END },
{ GLFW_KEY_CAPS_LOCK , EventKeyboard::KeyCode::KEY_CAPS_LOCK },
{ GLFW_KEY_SCROLL_LOCK , EventKeyboard::KeyCode::KEY_SCROLL_LOCK },
{ GLFW_KEY_NUM_LOCK , EventKeyboard::KeyCode::KEY_NUM_LOCK },
{ GLFW_KEY_PRINT_SCREEN , EventKeyboard::KeyCode::KEY_PRINT },
{ GLFW_KEY_PAUSE , EventKeyboard::KeyCode::KEY_PAUSE },
{ GLFW_KEY_F1 , EventKeyboard::KeyCode::KEY_F1 },
{ GLFW_KEY_F2 , EventKeyboard::KeyCode::KEY_F2 },
{ GLFW_KEY_F3 , EventKeyboard::KeyCode::KEY_F3 },
{ GLFW_KEY_F4 , EventKeyboard::KeyCode::KEY_F4 },
{ GLFW_KEY_F5 , EventKeyboard::KeyCode::KEY_F5 },
{ GLFW_KEY_F6 , EventKeyboard::KeyCode::KEY_F6 },
{ GLFW_KEY_F7 , EventKeyboard::KeyCode::KEY_F7 },
{ GLFW_KEY_F8 , EventKeyboard::KeyCode::KEY_F8 },
{ GLFW_KEY_F9 , EventKeyboard::KeyCode::KEY_F9 },
{ GLFW_KEY_F10 , EventKeyboard::KeyCode::KEY_F10 },
{ GLFW_KEY_F11 , EventKeyboard::KeyCode::KEY_F11 },
{ GLFW_KEY_F12 , EventKeyboard::KeyCode::KEY_F12 },
{ GLFW_KEY_F13 , EventKeyboard::KeyCode::KEY_NONE },
{ GLFW_KEY_F14 , EventKeyboard::KeyCode::KEY_NONE },
{ GLFW_KEY_F15 , EventKeyboard::KeyCode::KEY_NONE },
{ GLFW_KEY_F16 , EventKeyboard::KeyCode::KEY_NONE },
{ GLFW_KEY_F17 , EventKeyboard::KeyCode::KEY_NONE },
{ GLFW_KEY_F18 , EventKeyboard::KeyCode::KEY_NONE },
{ GLFW_KEY_F19 , EventKeyboard::KeyCode::KEY_NONE },
{ GLFW_KEY_F20 , EventKeyboard::KeyCode::KEY_NONE },
{ GLFW_KEY_F21 , EventKeyboard::KeyCode::KEY_NONE },
{ GLFW_KEY_F22 , EventKeyboard::KeyCode::KEY_NONE },
{ GLFW_KEY_F23 , EventKeyboard::KeyCode::KEY_NONE },
{ GLFW_KEY_F24 , EventKeyboard::KeyCode::KEY_NONE },
{ GLFW_KEY_F25 , EventKeyboard::KeyCode::KEY_NONE },
{ GLFW_KEY_KP_0 , EventKeyboard::KeyCode::KEY_0 },
{ GLFW_KEY_KP_1 , EventKeyboard::KeyCode::KEY_1 },
{ GLFW_KEY_KP_2 , EventKeyboard::KeyCode::KEY_2 },
{ GLFW_KEY_KP_3 , EventKeyboard::KeyCode::KEY_3 },
{ GLFW_KEY_KP_4 , EventKeyboard::KeyCode::KEY_4 },
{ GLFW_KEY_KP_5 , EventKeyboard::KeyCode::KEY_5 },
{ GLFW_KEY_KP_6 , EventKeyboard::KeyCode::KEY_6 },
{ GLFW_KEY_KP_7 , EventKeyboard::KeyCode::KEY_7 },
{ GLFW_KEY_KP_8 , EventKeyboard::KeyCode::KEY_8 },
{ GLFW_KEY_KP_9 , EventKeyboard::KeyCode::KEY_9 },
{ GLFW_KEY_KP_DECIMAL , EventKeyboard::KeyCode::KEY_PERIOD },
{ GLFW_KEY_KP_DIVIDE , EventKeyboard::KeyCode::KEY_KP_DIVIDE },
{ GLFW_KEY_KP_MULTIPLY , EventKeyboard::KeyCode::KEY_KP_MULTIPLY },
{ GLFW_KEY_KP_SUBTRACT , EventKeyboard::KeyCode::KEY_KP_MINUS },
{ GLFW_KEY_KP_ADD , EventKeyboard::KeyCode::KEY_KP_PLUS },
{ GLFW_KEY_KP_ENTER , EventKeyboard::KeyCode::KEY_KP_ENTER },
{ GLFW_KEY_KP_EQUAL , EventKeyboard::KeyCode::KEY_EQUAL },
{ GLFW_KEY_LEFT_SHIFT , EventKeyboard::KeyCode::KEY_SHIFT },
{ GLFW_KEY_LEFT_CONTROL , EventKeyboard::KeyCode::KEY_CTRL },
{ GLFW_KEY_LEFT_ALT , EventKeyboard::KeyCode::KEY_ALT },
{ GLFW_KEY_LEFT_SUPER , EventKeyboard::KeyCode::KEY_HYPER },
{ GLFW_KEY_RIGHT_SHIFT , EventKeyboard::KeyCode::KEY_SHIFT },
{ GLFW_KEY_RIGHT_CONTROL , EventKeyboard::KeyCode::KEY_CTRL },
{ GLFW_KEY_RIGHT_ALT , EventKeyboard::KeyCode::KEY_ALT },
{ GLFW_KEY_RIGHT_SUPER , EventKeyboard::KeyCode::KEY_HYPER },
{ GLFW_KEY_MENU , EventKeyboard::KeyCode::KEY_MENU },
{ GLFW_KEY_LAST , EventKeyboard::KeyCode::KEY_NONE }
};
//begin EGLViewEventHandler
class EGLViewEventHandler
{
public:
static bool s_captured;
static float s_mouseX;
static float s_mouseY;
static void OnGLFWError(int errorID, const char* errorDesc);
static void OnGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify);
static void OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y);
static void OnGLFWMouseScrollCallback(GLFWwindow* window, double x, double y);
static void OnGLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
static void OnGLFWCharCallback(GLFWwindow* window, unsigned int character);
static void OnGLFWWindowPosCallback(GLFWwindow* windows, int x, int y);
};
bool EGLViewEventHandler::s_captured = false;
float EGLViewEventHandler::s_mouseX = 0;
float EGLViewEventHandler::s_mouseY = 0;
void EGLViewEventHandler::OnGLFWError(int errorID, const char* errorDesc)
{
CCLOGERROR("GLFWError #%d Happen, %s\n", errorID, errorDesc);
}
void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify)
{
EGLView* eglView = EGLView::getInstance();
if(nullptr == eglView) return;
if(GLFW_MOUSE_BUTTON_LEFT == button)
{
if(GLFW_PRESS == action)
{
s_captured = true;
if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY)))
{
int id = 0;
eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY);
}
}
else if(GLFW_RELEASE == action)
{
s_captured = false;
if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY)))
{
int id = 0;
eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY);
}
}
}
if(GLFW_PRESS == action)
{
EventMouse event(EventMouse::MouseEventType::MOUSE_DOWN);
event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY);
event.setMouseButton(button);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&event);
}
else if(GLFW_RELEASE == action)
{
EventMouse event(EventMouse::MouseEventType::MOUSE_UP);
event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY);
event.setMouseButton(button);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&event);
}
}
void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y)
{
s_mouseX = (float)x;
s_mouseY = (float)y;
EGLView* eglView = EGLView::getInstance();
if(nullptr == eglView) return;
s_mouseX /= eglView->getFrameZoomFactor();
s_mouseY /= eglView->getFrameZoomFactor();
if(s_captured)
{
if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY)))
{
int id = 0;
eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY);
}
}
EventMouse event(EventMouse::MouseEventType::MOUSE_MOVE);
//Because OpenGL use upper left as origin point, we need to revert the mouse y coordinate here
event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&event);
}
void EGLViewEventHandler::OnGLFWMouseScrollCallback(GLFWwindow* window, double x, double y)
{
EGLView* eglView = EGLView::getInstance();
if(nullptr == eglView) return;
EventMouse event(EventMouse::MouseEventType::MOUSE_SCROLL);
//Because OpenGL use upper left as origin point, we need to revert the mouse y coordinate here
event.setScrollData((float)x, -(float)y);
event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&event);
}
void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods)
{
if (GLFW_REPEAT != action)
{
EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action);
auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&event);
}
}
void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character)
{
IMEDispatcher::sharedDispatcher()->dispatchInsertText((const char*) &character, 1);
}
void EGLViewEventHandler::OnGLFWWindowPosCallback(GLFWwindow *windows, int x, int y)
{
if(Director::getInstance())
{
Director::getInstance()->setViewport();
}
}
//end EGLViewEventHandler
//////////////////////////////////////////////////////////////////////////
// impliment EGLView
//////////////////////////////////////////////////////////////////////////
EGLView* EGLView::s_pEglView = nullptr;
EGLView::EGLView()
: _captured(false)
, _supportTouch(false)
, _frameZoomFactor(1.0f)
, _mainWindow(nullptr)
{
CCASSERT(nullptr == s_pEglView, "EGLView is singleton, Should be inited only one time\n");
s_pEglView = this;
_viewName = "Cocos2dxWin32";
glfwSetErrorCallback(EGLViewEventHandler::OnGLFWError);
glfwInit();
}
EGLView::~EGLView()
{
glfwTerminate();
s_pEglView = nullptr;
}
bool EGLView::init(const char* viewName, float width, float height, float frameZoomFactor)
{
if(nullptr != _mainWindow) return true;
setViewName(viewName);
setFrameSize(width, height);
setFrameZoomFactor(frameZoomFactor);
glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);
_mainWindow = glfwCreateWindow(_screenSize.width * _frameZoomFactor, _screenSize.height * _frameZoomFactor, _viewName.c_str(), nullptr, nullptr);
glfwMakeContextCurrent(_mainWindow);
glfwGetFramebufferSize(_mainWindow, &_frameBufferSize[0], &_frameBufferSize[1]);
glfwSetMouseButtonCallback(_mainWindow,EGLViewEventHandler::OnGLFWMouseCallBack);
glfwSetCursorPosCallback(_mainWindow,EGLViewEventHandler::OnGLFWMouseMoveCallBack);
glfwSetScrollCallback(_mainWindow, EGLViewEventHandler::OnGLFWMouseScrollCallback);
glfwSetCharCallback(_mainWindow, EGLViewEventHandler::OnGLFWCharCallback);
glfwSetKeyCallback(_mainWindow, EGLViewEventHandler::OnGLFWKeyCallback);
glfwSetWindowPosCallback(_mainWindow, EGLViewEventHandler::OnGLFWWindowPosCallback);
// check OpenGL version at first
const GLubyte* glVersion = glGetString(GL_VERSION);
CCLOG("OpenGL version = %s", glVersion);
if ( atof((const char*)glVersion) < 1.5 )
{
char strComplain[256] = {0};
sprintf(strComplain,
"OpenGL 1.5 or higher is required (your version is %s). Please upgrade the driver of your video card.",
glVersion);
MessageBox(strComplain, "OpenGL version too old");
return false;
}
GLenum GlewInitResult = glewInit();
if (GLEW_OK != GlewInitResult)
{
MessageBox((char *)glewGetErrorString(GlewInitResult), "OpenGL error");
return false;
}
if (GLEW_ARB_vertex_shader && GLEW_ARB_fragment_shader)
{
log("Ready for GLSL");
}
else
{
log("Not totally ready :(");
}
if (glewIsSupported("GL_VERSION_2_0"))
{
log("Ready for OpenGL 2.0");
}
else
{
log("OpenGL 2.0 not supported");
}
// if(glew_dynamic_binding() == false)
// {
// MessageBox("No OpenGL framebuffer support. Please upgrade the driver of your video card.", "OpenGL error");
// return false;
// }
//
// Enable point size by default on windows.
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
return true;
}
bool EGLView::isOpenGLReady()
{
return nullptr != _mainWindow;
}
void EGLView::end()
{
if(_mainWindow)
glfwSetWindowShouldClose(_mainWindow,1);
}
void EGLView::swapBuffers()
{
if(_mainWindow)
glfwSwapBuffers(_mainWindow);
}
bool EGLView::windowShouldClose()
{
if(_mainWindow)
return glfwWindowShouldClose(_mainWindow);
else
return true;
}
void EGLView::pollEvents()
{
glfwPollEvents();
}
void EGLView::setIMEKeyboardState(bool /*bOpen*/)
{
}
void EGLView::setFrameZoomFactor(float fZoomFactor)
{
_frameZoomFactor = fZoomFactor;
Director::getInstance()->setProjection(Director::getInstance()->getProjection());
}
float EGLView::getFrameZoomFactor()
{
return _frameZoomFactor;
}
void EGLView::setFrameSize(float width, float height)
{
EGLViewProtocol::setFrameSize(width, height);
}
void EGLView::setViewPortInPoints(float x , float y , float w , float h)
{
float frameZoomFactorX = _frameBufferSize[0]/_screenSize.width;
float frameZoomFactorY = _frameBufferSize[1]/_screenSize.height;
glViewport((GLint)(x * _scaleX * frameZoomFactorX + _viewPortRect.origin.x * frameZoomFactorX),
(GLint)(y * _scaleY * frameZoomFactorY + _viewPortRect.origin.y * frameZoomFactorY),
(GLsizei)(w * _scaleX * frameZoomFactorX),
(GLsizei)(h * _scaleY * frameZoomFactorY));
}
void EGLView::setScissorInPoints(float x , float y , float w , float h)
{
float frameZoomFactorX = _frameBufferSize[0]/_screenSize.width;
float frameZoomFactorY = _frameBufferSize[1]/_screenSize.height;
glScissor((GLint)(x * _scaleX * frameZoomFactorX + _viewPortRect.origin.x * frameZoomFactorX),
(GLint)(y * _scaleY * frameZoomFactorY + _viewPortRect.origin.y * frameZoomFactorY),
(GLsizei)(w * _scaleX * frameZoomFactorX),
(GLsizei)(h * _scaleY * frameZoomFactorY));
}
EGLView* EGLView::getInstance()
{
CCASSERT(nullptr != s_pEglView, "EGL singleton should not be null");
return s_pEglView;
}
// XXX: deprecated
EGLView* EGLView::sharedOpenGLView()
{
return EGLView::getInstance();
}
NS_CC_END

View File

@ -1,103 +0,0 @@
/****************************************************************************
Copyright (c) 2011 Laschweinski
Copyright (c) 2013-2014 Chukong Technologies Inc.
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 EGLVIEW_H_
#define EGLVIEW_H_
#include "platform/CCCommon.h"
#include "CCGeometry.h"
#include "platform/CCEGLViewProtocol.h"
#include "glfw3.h"
#include <set>
bool initExtensions();
NS_CC_BEGIN
class CC_DLL EGLView : public EGLViewProtocol
{
public:
/**
* @js ctor
*/
EGLView();
/**
* @js NA
* @lua NA
*/
virtual ~EGLView();
/* override functions */
virtual bool isOpenGLReady();
virtual void end();
virtual void swapBuffers();
virtual void setFrameSize(float width, float height);
virtual void setIMEKeyboardState(bool bOpen);
/*
*frameZoomFactor for frame. This method is for debugging big resolution (e.g.new ipad) app on desktop.
*/
bool init(const char* viewName, float width, float height, float frameZoomFactor = 1.0f);
public:
//void resize(int width, int height);
float getFrameZoomFactor();
//void centerWindow();
virtual void setViewPortInPoints(float x , float y , float w , float h);
virtual void setScissorInPoints(float x , float y , float w , float h);
// static function
/**
@brief get the shared main open gl window
*/
static EGLView* getInstance();
/** @deprecated Use getInstance() instead */
CC_DEPRECATED_ATTRIBUTE static EGLView* sharedOpenGLView();
protected:
/*
* Set zoom factor for frame. This method is for debugging big resolution (e.g.new ipad) app on desktop.
*/
void setFrameZoomFactor(float fZoomFactor);
private:
bool _captured;
bool _supportTouch;
int _frameBufferSize[2];
float _frameZoomFactor;
static EGLView* s_pEglView;
public:
bool windowShouldClose();
void pollEvents();
GLFWwindow* getWindow() const { return _mainWindow; }
private:
GLFWwindow* _mainWindow;
};
NS_CC_END
#endif /* EGLVIEW_H_ */

View File

@ -22,6 +22,10 @@ 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.
****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
#include "CCFileUtilsLinux.h"
#include "platform/CCCommon.h"
#include "ccMacros.h"
@ -114,3 +118,5 @@ bool FileUtilsLinux::isFileExist(const std::string& strFilePath) const
}
NS_CC_END
#endif CC_TARGET_PLATFORM == CC_PLATFORM_LINUX

View File

@ -25,6 +25,9 @@ THE SOFTWARE.
#ifndef __CC_FILEUTILS_LINUX_H__
#define __CC_FILEUTILS_LINUX_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
#include "platform/CCFileUtils.h"
#include "CCPlatformMacros.h"
#include "ccTypes.h"
@ -56,5 +59,6 @@ public:
NS_CC_END
#endif // __CC_FILEUTILS_LINUX_H__
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
#endif // __CC_FILEUTILS_LINUX_H__

View File

@ -25,8 +25,13 @@ THE SOFTWARE.
#ifndef __CCGL_H__
#define __CCGL_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
#include "GL/glew.h"
#define CC_GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
#endif // __CCGL_H__

View File

@ -22,6 +22,10 @@ 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.
****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
#include <string.h>
#include <algorithm>
@ -450,23 +454,21 @@ static BitmapDC& sharedBitmapDC()
}
bool Image::initWithString(
const char * pText,
int nWidth/* = 0*/,
int nHeight/* = 0*/,
TextAlign eAlignMask/* = kAlignCenter*/,
const char * pFontName/* = nil*/,
int nSize/* = 0*/)
const char * text,
int width/* = 0*/,
int height/* = 0*/,
TextAlign alignMask/* = kAlignCenter*/,
const char * fontName/* = nil*/,
int size/* = 0*/)
{
bool bRet = false;
bool ret = false;
do
{
CC_BREAK_IF(! pText);
CC_BREAK_IF(!text || 0 == strlen(text));
BitmapDC &dc = sharedBitmapDC();
//const char* pFullFontName = FileUtils::getInstance()->fullPathFromRelativePath(pFontName);
CC_BREAK_IF(! dc.getBitmap(pText, nWidth, nHeight, eAlignMask, pFontName, nSize));
CC_BREAK_IF(! dc.getBitmap(text, width, height, alignMask, fontName, size));
// assign the dc._data to _data in order to save time
_data = dc._data;
@ -478,13 +480,15 @@ bool Image::initWithString(
_preMulti = true;
_dataLen = _width * _height * 4;
bRet = true;
ret = true;
dc.reset();
}while (0);
//do nothing
return bRet;
return ret;
}
NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX

View File

@ -22,9 +22,13 @@ 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 __CCPLATFORMDEFINE_H__
#define __CCPLATFORMDEFINE_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
#include <string.h>
#if defined(_USRDLL)
@ -47,5 +51,6 @@ THE SOFTWARE.
#endif
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
#endif /* __CCPLATFORMDEFINE_H__*/

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