Merge pull request #1776 from 2youyou2/v2.3.0

support native renderer
This commit is contained in:
Jare Guo
2019-07-22 17:40:51 +08:00
committed by GitHub
176 changed files with 21660 additions and 5528 deletions
File diff suppressed because it is too large Load Diff
+44 -2
View File
@@ -81,7 +81,7 @@
<ClCompile Include="..\cocos\editor-support\MiddlewareManager.cpp" />
<ClCompile Include="..\cocos\editor-support\IOBuffer.cpp" />
<ClCompile Include="..\cocos\editor-support\IOTypedArray.cpp" />
<ClCompile Include="..\cocos\editor-support\RenderInfoMgr.cpp" />
<ClCompile Include="..\cocos\editor-support\particle\ParticleSimulator.cpp" />
<ClCompile Include="..\cocos\editor-support\spine-creator-support\AttachmentVertices.cpp" />
<ClCompile Include="..\cocos\editor-support\spine-creator-support\SkeletonAnimation.cpp" />
<ClCompile Include="..\cocos\editor-support\spine-creator-support\SkeletonDataMgr.cpp" />
@@ -191,6 +191,7 @@
<ClCompile Include="..\cocos\renderer\renderer\BaseRenderer.cpp" />
<ClCompile Include="..\cocos\renderer\renderer\Camera.cpp" />
<ClCompile Include="..\cocos\renderer\renderer\Config.cpp" />
<ClCompile Include="..\cocos\renderer\renderer\CustomProperties.cpp" />
<ClCompile Include="..\cocos\renderer\renderer\Effect.cpp" />
<ClCompile Include="..\cocos\renderer\renderer\ForwardRenderer.cpp" />
<ClCompile Include="..\cocos\renderer\renderer\InputAssembler.cpp" />
@@ -202,6 +203,24 @@
<ClCompile Include="..\cocos\renderer\renderer\Scene.cpp" />
<ClCompile Include="..\cocos\renderer\renderer\Technique.cpp" />
<ClCompile Include="..\cocos\renderer\renderer\View.cpp" />
<ClCompile Include="..\cocos\renderer\scene\assembler\Assembler.cpp" />
<ClCompile Include="..\cocos\renderer\scene\assembler\AssemblerBase.cpp" />
<ClCompile Include="..\cocos\renderer\scene\assembler\AssemblerSprite.cpp" />
<ClCompile Include="..\cocos\renderer\scene\assembler\CustomAssembler.cpp" />
<ClCompile Include="..\cocos\renderer\scene\assembler\MaskAssembler.cpp" />
<ClCompile Include="..\cocos\renderer\scene\assembler\RenderData.cpp" />
<ClCompile Include="..\cocos\renderer\scene\assembler\RenderDataList.cpp" />
<ClCompile Include="..\cocos\renderer\scene\assembler\SimpleSprite2D.cpp" />
<ClCompile Include="..\cocos\renderer\scene\assembler\SlicedSprite2D.cpp" />
<ClCompile Include="..\cocos\renderer\scene\assembler\TiledMapAssembler.cpp" />
<ClCompile Include="..\cocos\renderer\scene\MemPool.cpp" />
<ClCompile Include="..\cocos\renderer\scene\MeshBuffer.cpp" />
<ClCompile Include="..\cocos\renderer\scene\ModelBatcher.cpp" />
<ClCompile Include="..\cocos\renderer\scene\NodeMemPool.cpp" />
<ClCompile Include="..\cocos\renderer\scene\NodeProxy.cpp" />
<ClCompile Include="..\cocos\renderer\scene\ParallelTask.cpp" />
<ClCompile Include="..\cocos\renderer\scene\RenderFlow.cpp" />
<ClCompile Include="..\cocos\renderer\scene\StencilManager.cpp" />
<ClCompile Include="..\cocos\renderer\Types.cpp" />
<ClCompile Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_audioengine_auto.cpp" />
<ClCompile Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_auto.cpp" />
@@ -209,6 +228,7 @@
<ClCompile Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_editor_support_auto.cpp" />
<ClCompile Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_extension_auto.cpp" />
<ClCompile Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_network_auto.cpp" />
<ClCompile Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_particle_auto.cpp" />
<ClCompile Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_spine_auto.cpp" />
<ClCompile Include="..\cocos\scripting\js-bindings\auto\jsb_gfx_auto.cpp" />
<ClCompile Include="..\cocos\scripting\js-bindings\auto\jsb_renderer_auto.cpp" />
@@ -353,7 +373,7 @@
<ClInclude Include="..\cocos\editor-support\MiddlewareMacro.h" />
<ClInclude Include="..\cocos\editor-support\MiddlewareManager.h" />
<ClInclude Include="..\cocos\editor-support\IOTypedArray.h" />
<ClInclude Include="..\cocos\editor-support\RenderInfoMgr.h" />
<ClInclude Include="..\cocos\editor-support\particle\ParticleSimulator.h" />
<ClInclude Include="..\cocos\editor-support\spine-creator-support\AttachmentVertices.h" />
<ClInclude Include="..\cocos\editor-support\spine-creator-support\SkeletonAnimation.h" />
<ClInclude Include="..\cocos\editor-support\spine-creator-support\SkeletonDataMgr.h" />
@@ -493,9 +513,11 @@
<ClInclude Include="..\cocos\renderer\gfx\VertexBuffer.h" />
<ClInclude Include="..\cocos\renderer\gfx\VertexFormat.h" />
<ClInclude Include="..\cocos\renderer\Macro.h" />
<ClInclude Include="..\cocos\renderer\memop\RecyclePool.hpp" />
<ClInclude Include="..\cocos\renderer\renderer\BaseRenderer.h" />
<ClInclude Include="..\cocos\renderer\renderer\Camera.h" />
<ClInclude Include="..\cocos\renderer\renderer\Config.h" />
<ClInclude Include="..\cocos\renderer\renderer\CustomProperties.hpp" />
<ClInclude Include="..\cocos\renderer\renderer\Effect.h" />
<ClInclude Include="..\cocos\renderer\renderer\ForwardRenderer.h" />
<ClInclude Include="..\cocos\renderer\renderer\INode.h" />
@@ -509,6 +531,25 @@
<ClInclude Include="..\cocos\renderer\renderer\Scene.h" />
<ClInclude Include="..\cocos\renderer\renderer\Technique.h" />
<ClInclude Include="..\cocos\renderer\renderer\View.h" />
<ClInclude Include="..\cocos\renderer\scene\assembler\Assembler.hpp" />
<ClInclude Include="..\cocos\renderer\scene\assembler\AssemblerBase.hpp" />
<ClInclude Include="..\cocos\renderer\scene\assembler\AssemblerSprite.hpp" />
<ClInclude Include="..\cocos\renderer\scene\assembler\CustomAssembler.hpp" />
<ClInclude Include="..\cocos\renderer\scene\assembler\MaskAssembler.hpp" />
<ClInclude Include="..\cocos\renderer\scene\assembler\RenderData.hpp" />
<ClInclude Include="..\cocos\renderer\scene\assembler\RenderDataList.hpp" />
<ClInclude Include="..\cocos\renderer\scene\assembler\SimpleSprite2D.hpp" />
<ClInclude Include="..\cocos\renderer\scene\assembler\SlicedSprite2D.hpp" />
<ClInclude Include="..\cocos\renderer\scene\assembler\TiledMapAssembler.hpp" />
<ClInclude Include="..\cocos\renderer\scene\MemPool.hpp" />
<ClInclude Include="..\cocos\renderer\scene\MeshBuffer.hpp" />
<ClInclude Include="..\cocos\renderer\scene\ModelBatcher.hpp" />
<ClInclude Include="..\cocos\renderer\scene\NodeMemPool.hpp" />
<ClInclude Include="..\cocos\renderer\scene\NodeProxy.hpp" />
<ClInclude Include="..\cocos\renderer\scene\ParallelTask.hpp" />
<ClInclude Include="..\cocos\renderer\scene\RenderFlow.hpp" />
<ClInclude Include="..\cocos\renderer\scene\scene-bindings.h" />
<ClInclude Include="..\cocos\renderer\scene\StencilManager.hpp" />
<ClInclude Include="..\cocos\renderer\Types.h" />
<ClInclude Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_audioengine_auto.hpp" />
<ClInclude Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_auto.hpp" />
@@ -516,6 +557,7 @@
<ClInclude Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_editor_support_auto.hpp" />
<ClInclude Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_extension_auto.hpp" />
<ClInclude Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_network_auto.hpp" />
<ClInclude Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_particle_auto.hpp" />
<ClInclude Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_spine_auto.hpp" />
<ClInclude Include="..\cocos\scripting\js-bindings\auto\jsb_gfx_auto.hpp" />
<ClInclude Include="..\cocos\scripting\js-bindings\auto\jsb_renderer_auto.hpp" />
+144 -66
View File
@@ -422,9 +422,6 @@
<ClCompile Include="..\cocos\editor-support\IOBuffer.cpp">
<Filter>editor-support</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\RenderInfoMgr.cpp">
<Filter>editor-support</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine-creator-support\AttachmentVertices.cpp">
<Filter>editor-support\spine-creator-support</Filter>
</ClCompile>
@@ -593,12 +590,6 @@
<ClCompile Include="..\cocos\editor-support\spine\AttachmentTimeline.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\AttachmentType.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\BlendMode.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\Bone.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
@@ -611,30 +602,18 @@
<ClCompile Include="..\cocos\editor-support\spine\ClippingAttachment.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\Color.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\ColorTimeline.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\Constraint.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\ContainerUtil.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\CurveTimeline.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\Debug.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\DeformTimeline.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\dll.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\DrawOrderTimeline.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
@@ -650,12 +629,6 @@
<ClCompile Include="..\cocos\editor-support\spine\Extension.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\HashMap.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\HasRendererObject.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\IkConstraint.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
@@ -677,12 +650,6 @@
<ClCompile Include="..\cocos\editor-support\spine\MeshAttachment.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\MixBlend.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\MixDirection.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\PathAttachment.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
@@ -704,18 +671,9 @@
<ClCompile Include="..\cocos\editor-support\spine\PointAttachment.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\Pool.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\PositionMode.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\RegionAttachment.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\RotateMode.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\RotateTimeline.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
@@ -755,27 +713,15 @@
<ClCompile Include="..\cocos\editor-support\spine\SlotData.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\SpacingMode.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\spine.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\SpineObject.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\SpineString.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\TextureLoader.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\Timeline.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\TimelineType.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\TransformConstraint.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
@@ -785,9 +731,6 @@
<ClCompile Include="..\cocos\editor-support\spine\TransformConstraintTimeline.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\TransformMode.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\TranslateTimeline.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
@@ -800,21 +743,78 @@
<ClCompile Include="..\cocos\editor-support\spine\Updatable.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\Vector.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\VertexAttachment.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\VertexEffect.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\spine\Vertices.cpp">
<Filter>editor-support\spine</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\MeshBuffer.cpp">
<Filter>editor-support</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\MemPool.cpp">
<Filter>renderer\scene</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\MeshBuffer.cpp">
<Filter>renderer\scene</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\ModelBatcher.cpp">
<Filter>renderer\scene</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\NodeMemPool.cpp">
<Filter>renderer\scene</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\NodeProxy.cpp">
<Filter>renderer\scene</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\ParallelTask.cpp">
<Filter>renderer\scene</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\RenderFlow.cpp">
<Filter>renderer\scene</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\StencilManager.cpp">
<Filter>renderer\scene</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\assembler\Assembler.cpp">
<Filter>renderer\scene\assembler</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\assembler\AssemblerBase.cpp">
<Filter>renderer\scene\assembler</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\assembler\AssemblerSprite.cpp">
<Filter>renderer\scene\assembler</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\assembler\CustomAssembler.cpp">
<Filter>renderer\scene\assembler</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\assembler\MaskAssembler.cpp">
<Filter>renderer\scene\assembler</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\assembler\RenderData.cpp">
<Filter>renderer\scene\assembler</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\assembler\RenderDataList.cpp">
<Filter>renderer\scene\assembler</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\assembler\SimpleSprite2D.cpp">
<Filter>renderer\scene\assembler</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\assembler\SlicedSprite2D.cpp">
<Filter>renderer\scene\assembler</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\scene\assembler\TiledMapAssembler.cpp">
<Filter>renderer\scene\assembler</Filter>
</ClCompile>
<ClCompile Include="..\cocos\renderer\renderer\CustomProperties.cpp">
<Filter>renderer\renderer</Filter>
</ClCompile>
<ClCompile Include="..\cocos\editor-support\particle\ParticleSimulator.cpp">
<Filter>editor-support\particle</Filter>
</ClCompile>
<ClCompile Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_particle_auto.cpp">
<Filter>js-bindings\auto</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\cocos\base\base64.h">
@@ -1517,9 +1517,6 @@
<ClInclude Include="..\cocos\editor-support\IOBuffer.h">
<Filter>editor-support</Filter>
</ClInclude>
<ClInclude Include="..\cocos\editor-support\RenderInfoMgr.h">
<Filter>editor-support</Filter>
</ClInclude>
<ClInclude Include="..\cocos\editor-support\MiddlewareMacro.h">
<Filter>editor-support</Filter>
</ClInclude>
@@ -1769,6 +1766,75 @@
<ClInclude Include="..\cocos\editor-support\MeshBuffer.h">
<Filter>editor-support</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\MemPool.hpp">
<Filter>renderer\scene</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\MeshBuffer.hpp">
<Filter>renderer\scene</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\ModelBatcher.hpp">
<Filter>renderer\scene</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\NodeMemPool.hpp">
<Filter>renderer\scene</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\NodeProxy.hpp">
<Filter>renderer\scene</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\ParallelTask.hpp">
<Filter>renderer\scene</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\RenderFlow.hpp">
<Filter>renderer\scene</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\scene-bindings.h">
<Filter>renderer\scene</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\StencilManager.hpp">
<Filter>renderer\scene</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\assembler\Assembler.hpp">
<Filter>renderer\scene\assembler</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\assembler\AssemblerBase.hpp">
<Filter>renderer\scene\assembler</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\assembler\AssemblerSprite.hpp">
<Filter>renderer\scene\assembler</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\assembler\CustomAssembler.hpp">
<Filter>renderer\scene\assembler</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\assembler\MaskAssembler.hpp">
<Filter>renderer\scene\assembler</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\assembler\RenderData.hpp">
<Filter>renderer\scene\assembler</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\assembler\RenderDataList.hpp">
<Filter>renderer\scene\assembler</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\assembler\SimpleSprite2D.hpp">
<Filter>renderer\scene\assembler</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\assembler\SlicedSprite2D.hpp">
<Filter>renderer\scene\assembler</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\scene\assembler\TiledMapAssembler.hpp">
<Filter>renderer\scene\assembler</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\memop\RecyclePool.hpp">
<Filter>renderer\scene\memop</Filter>
</ClInclude>
<ClInclude Include="..\cocos\renderer\renderer\CustomProperties.hpp">
<Filter>renderer\renderer</Filter>
</ClInclude>
<ClInclude Include="..\cocos\editor-support\particle\ParticleSimulator.h">
<Filter>editor-support\particle</Filter>
</ClInclude>
<ClInclude Include="..\cocos\scripting\js-bindings\auto\jsb_cocos2dx_particle_auto.hpp">
<Filter>js-bindings\auto</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<Filter Include="base">
@@ -1900,6 +1966,18 @@
<Filter Include="editor-support\dragonbones\parser">
<UniqueIdentifier>{adc17345-7ade-411b-abef-14ca3ae30e9f}</UniqueIdentifier>
</Filter>
<Filter Include="renderer\scene">
<UniqueIdentifier>{092e6c27-6094-4ee8-a5fc-7082059c8f93}</UniqueIdentifier>
</Filter>
<Filter Include="renderer\scene\assembler">
<UniqueIdentifier>{6c380106-a041-45b9-90ee-d4b8194c1e2b}</UniqueIdentifier>
</Filter>
<Filter Include="renderer\scene\memop">
<UniqueIdentifier>{241728db-2151-42d2-a002-3fb1fd260a78}</UniqueIdentifier>
</Filter>
<Filter Include="editor-support\particle">
<UniqueIdentifier>{333e24f4-af65-4a68-96a9-a5cccd0b4b81}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<None Include="..\cocos\math\Mat4.inl">
+22 -1
View File
@@ -26,6 +26,7 @@ math/Quaternion.cpp \
math/Vec2.cpp \
math/Vec3.cpp \
math/Vec4.cpp \
math/Mat3.cpp \
base/CCAutoreleasePool.cpp \
base/CCConfiguration.cpp \
base/CCData.cpp \
@@ -136,6 +137,26 @@ renderer/renderer/Scene.cpp \
renderer/renderer/Technique.cpp \
renderer/renderer/View.cpp \
renderer/renderer/ForwardRenderer.cpp \
renderer/scene/assembler/Assembler.cpp \
renderer/scene/assembler/AssemblerBase.cpp \
renderer/scene/assembler/CustomAssembler.cpp \
renderer/scene/assembler/MaskAssembler.cpp \
renderer/scene/assembler/RenderData.cpp \
renderer/scene/assembler/RenderDataList.cpp \
renderer/scene/assembler/TiledMapAssembler.cpp \
renderer/scene/assembler/AssemblerSprite.cpp \
renderer/scene/assembler/SimpleSprite2D.cpp \
renderer/scene/assembler/SlicedSprite2D.cpp \
renderer/scene/MeshBuffer.cpp \
renderer/scene/ModelBatcher.cpp \
renderer/scene/NodeProxy.cpp \
renderer/scene/RenderFlow.cpp \
renderer/scene/StencilManager.cpp \
renderer/scene/MemPool.cpp \
renderer/scene/NodeMemPool.cpp \
renderer/scene/ParallelTask.cpp \
renderer/memop/RecyclePool.hpp \
renderer/renderer/CustomProperties.cpp \
scripting/js-bindings/auto/jsb_gfx_auto.cpp \
scripting/js-bindings/auto/jsb_renderer_auto.cpp \
scripting/js-bindings/manual/jsb_renderer_manual.cpp \
@@ -174,7 +195,7 @@ endif # USE_SOCKET
ifneq ($(USE_MIDDLEWARE),0)
LOCAL_STATIC_LIBRARIES += editor_support_static
endif # USE_SPINE or USE_DRAGONBONES
endif # USE_MIDDLEWARE
LOCAL_C_INCLUDES := $(LOCAL_PATH) \
$(LOCAL_PATH)/.. \
+9 -1
View File
@@ -39,7 +39,7 @@ THE SOFTWARE.
// disable module if you didn't need it, this will reduce package size
#ifndef USE_GFX_RENDERER
#define USE_GFX_RENDERER 0
#define USE_GFX_RENDERER 1
#endif
#ifndef USE_VIDEO
@@ -62,6 +62,8 @@ THE SOFTWARE.
#define USE_MIDDLEWARE 1
#endif
#if USE_GFX_RENDERER > 0 && USE_MIDDLEWARE > 0
#ifndef USE_SPINE
#define USE_SPINE 1
#endif
@@ -70,6 +72,12 @@ THE SOFTWARE.
#define USE_DRAGONBONES 1
#endif
#ifndef USE_PARTICLE
#define USE_PARTICLE 1
#endif
#endif // endif middleware
/** @def CC_ENABLE_STACKABLE_ACTIONS
* If enabled, actions that alter the position property (eg: MoveBy, JumpBy, BezierBy, etc..) will be stacked.
* If you run 2 or more 'position' actions at the same time on a node, then end position will be the sum of all the positions.
-6
View File
@@ -25,9 +25,3 @@ THE SOFTWARE.
****************************************************************************/
#include "base/ccRandom.h"
std::mt19937 &cocos2d::RandomHelper::getEngine() {
static std::random_device seed_gen;
static std::mt19937 engine(seed_gen());
return engine;
}
+5 -1
View File
@@ -59,7 +59,11 @@ public:
return dist(mt);
}
private:
static std::mt19937 &getEngine();
static inline std::mt19937 &getEngine() {
static std::random_device seed_gen;
static std::mt19937 engine(seed_gen());
return engine;
}
};
/**
+6 -1
View File
@@ -10,7 +10,6 @@ LOCAL_ARM_MODE := arm
LOCAL_SRC_FILES := \
../scripting/js-bindings/manual/jsb_helper.cpp \
IOBuffer.cpp \
RenderInfoMgr.cpp \
MeshBuffer.cpp \
middleware-adapter.cpp \
TypedArrayPool.cpp \
@@ -18,6 +17,12 @@ IOTypedArray.cpp \
MiddlewareManager.cpp \
../scripting/js-bindings/auto/jsb_cocos2dx_editor_support_auto.cpp
ifeq ($(USE_PARTICLE),1)
LOCAL_SRC_FILES += \
particle/ParticleSimulator.cpp \
../scripting/js-bindings/auto/jsb_cocos2dx_particle_auto.cpp
endif # USE_PARTICLE
ifeq ($(USE_SPINE),1)
LOCAL_SRC_FILES += \
spine/Animation.cpp \
+53 -24
View File
@@ -24,14 +24,19 @@
#include "MeshBuffer.h"
#include "base/CCGLUtils.h"
#include "renderer/gfx/DeviceGraphics.h"
using namespace cocos2d;
using namespace cocos2d::renderer;
MIDDLEWARE_BEGIN
MeshBuffer::MeshBuffer(int vertexSize)
: _ib(INIT_INDEX_BUFFER_SIZE)
, _vb(MAX_VERTEX_BUFFER_SIZE * vertexSize)
MeshBuffer::MeshBuffer(int vertexFormat)
: _vertexFormat(vertexFormat)
, _ib(INIT_INDEX_BUFFER_SIZE)
, _vb(MAX_VERTEX_BUFFER_SIZE * vertexFormat)
{
_vb.setMaxSize(MAX_VERTEX_BUFFER_SIZE * vertexSize);
_vb.setMaxSize(MAX_VERTEX_BUFFER_SIZE * _vertexFormat);
_vb.setFullCallback([this]
{
uploadVB();
@@ -41,11 +46,25 @@ MeshBuffer::MeshBuffer(int vertexSize)
next();
});
_glIBArr.resize(1);
glGenBuffers(1, &_glIBArr[0]);
auto glIB = new IndexBuffer();
glIB->init(DeviceGraphics::getInstance(), IndexFormat::UINT16, Usage::STATIC, nullptr, 0, (uint32_t)_ib.getCapacity() / sizeof(unsigned short));
_glIBArr.push_back(glIB);
_glVBArr.resize(1);
glGenBuffers(1, &_glVBArr[0]);
auto glVB = new VertexBuffer();
switch(_vertexFormat)
{
case VF_XYUVC:
glVB->init(DeviceGraphics::getInstance(), VertexFormat::XY_UV_Color, Usage::DYNAMIC, nullptr, 0, (uint32_t)_vb.getCapacity() / VertexFormat::XY_UV_Color->getBytes());
break;
case VF_XYUVCC:
glVB->init(DeviceGraphics::getInstance(), VertexFormat::XY_UV_Two_Color, Usage::DYNAMIC, nullptr, 0, (uint32_t)_vb.getCapacity() / VertexFormat::XY_UV_Two_Color->getBytes());
break;
default:
CCASSERT(false, "MeshBuffer constructor unknow vertex format");
break;
}
_glVBArr.push_back(glVB);
}
MeshBuffer::~MeshBuffer()
@@ -53,8 +72,8 @@ MeshBuffer::~MeshBuffer()
auto num = _glVBArr.size();
for (auto i = 0; i < num; i++)
{
cocos2d::ccDeleteBuffers(1, &_glIBArr[i]);
cocos2d::ccDeleteBuffers(1, &_glVBArr[i]);
delete _glIBArr[i];
delete _glVBArr[i];
}
_glIBArr.clear();
_glVBArr.clear();
@@ -64,11 +83,10 @@ void MeshBuffer::uploadVB()
{
auto length = _vb.length();
if (length == 0) return;
auto glVB = _glVBArr[_bufferPos];
cocos2d::ccBindBuffer(GL_ARRAY_BUFFER, glVB);
glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)length, _vb.getBuffer(), GL_DYNAMIC_DRAW);
cocos2d::ccBindBuffer(GL_ARRAY_BUFFER, 0);
glVB->setBytes((uint32_t)length);
glVB->update(0, _vb.getBuffer(), length);
}
void MeshBuffer::uploadIB()
@@ -76,13 +94,9 @@ void MeshBuffer::uploadIB()
auto length = _ib.length();
if (length == 0) return;
GLint _oldGLID = 0;
glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &_oldGLID);
auto glIB = _glIBArr[_bufferPos];
cocos2d::ccBindBuffer(GL_ELEMENT_ARRAY_BUFFER, glIB);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)length, _ib.getBuffer(), GL_STATIC_DRAW);
cocos2d::ccBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _oldGLID);
glIB->setBytes((uint32_t)length);
glIB->update(0, _ib.getBuffer(), length);
}
void MeshBuffer::next()
@@ -90,14 +104,29 @@ void MeshBuffer::next()
_bufferPos++;
if (_glIBArr.size() <= _bufferPos)
{
_glIBArr.resize(_bufferPos + 1);
glGenBuffers(1, &_glIBArr[_bufferPos]);
auto glIB = new IndexBuffer();
glIB->init(DeviceGraphics::getInstance(), IndexFormat::UINT16, Usage::STATIC, nullptr, 0, (uint32_t)_ib.getCapacity() / sizeof(unsigned short));
_glIBArr.push_back(glIB);
}
if (_glVBArr.size() <= _bufferPos)
{
_glVBArr.resize(_bufferPos + 1);
glGenBuffers(1, &_glVBArr[_bufferPos]);
auto glVB = new VertexBuffer();
switch(_vertexFormat)
{
case VF_XYUVC:
glVB->init(DeviceGraphics::getInstance(), VertexFormat::XY_UV_Color, Usage::DYNAMIC, nullptr, 0, (uint32_t)_vb.getCapacity() / VertexFormat::XY_UV_Color->getBytes());
break;
case VF_XYUVCC:
glVB->init(DeviceGraphics::getInstance(), VertexFormat::XY_UV_Two_Color, Usage::DYNAMIC, nullptr, 0, (uint32_t)_vb.getCapacity() / VertexFormat::XY_UV_Two_Color->getBytes());
break;
default:
CCASSERT(false, "MeshBuffer constructor unknow vertex format");
break;
}
_glVBArr.push_back(glVB);
}
}
+7 -4
View File
@@ -25,6 +25,8 @@
#include "IOBuffer.h"
#include <vector>
#include "renderer/gfx/VertexBuffer.h"
#include "renderer/gfx/IndexBuffer.h"
MIDDLEWARE_BEGIN
@@ -34,12 +36,12 @@ public:
MeshBuffer(int vertexFormat);
~MeshBuffer();
uint32_t getGLVB()
inline cocos2d::renderer::VertexBuffer* getGLVB()
{
return _glVBArr[_bufferPos];
}
uint32_t getGLIB()
inline cocos2d::renderer::IndexBuffer* getGLIB()
{
return _glIBArr[_bufferPos];
}
@@ -60,12 +62,13 @@ public:
private:
void next();
private:
std::vector<uint32_t> _glIBArr;
std::vector<uint32_t> _glVBArr;
std::vector<cocos2d::renderer::IndexBuffer*> _glIBArr;
std::vector<cocos2d::renderer::VertexBuffer*> _glVBArr;
std::size_t _bufferPos = 0;
IOBuffer _vb;
IOBuffer _ib;
int _vertexFormat = 0;
};
MIDDLEWARE_END
@@ -26,8 +26,7 @@
#define INIT_INDEX_BUFFER_SIZE 1024000
// max vertex buffer size
#define MAX_VERTEX_BUFFER_SIZE 65535
// render info int capacity
#define INIT_RENDER_INFO_BUFFER_SIZE 1024000
// fill debug data max capacity
#define MAX_DEBUG_BUFFER_SIZE 409600
// type array pool min size
@@ -24,7 +24,6 @@
#include "MiddlewareManager.h"
#include "base/CCGLUtils.h"
#include "scripting/js-bindings/jswrapper/SeApi.h"
#include "RenderInfoMgr.h"
MIDDLEWARE_BEGIN
@@ -59,26 +58,23 @@ MeshBuffer* MiddlewareManager::getMeshBuffer(int format)
return mb;
}
void MiddlewareManager::update(float dt)
void MiddlewareManager::_clearRemoveList()
{
for (auto it : _mbMap)
for (std::size_t i = 0; i < _removeList.size(); i++)
{
auto buffer = it.second;
if (buffer)
auto editor = _removeList[i];
auto it = _updateMap.find(editor);
if (it != _updateMap.end())
{
buffer->reset();
_updateMap.erase(it);
}
}
// reset render info
auto renderInfoMgr = RenderInfoMgr::getInstance();
renderInfoMgr->reset();
auto renderInfo = renderInfoMgr->getBuffer();
if (renderInfo)
{
renderInfo->writeUint32(0);
}
_removeList.clear();
}
void MiddlewareManager::update(float dt)
{
isUpdating = true;
for (auto it = _updateMap.begin(); it != _updateMap.end(); it++)
@@ -100,17 +96,40 @@ void MiddlewareManager::update(float dt)
isUpdating = false;
for (std::size_t i = 0; i < _removeList.size(); i++)
_clearRemoveList();
}
void MiddlewareManager::render(float dt)
{
for (auto it : _mbMap)
{
auto editor = _removeList[i];
auto it = _updateMap.find(editor);
if (it != _updateMap.end())
auto buffer = it.second;
if (buffer)
{
_updateMap.erase(it);
buffer->reset();
}
}
_removeList.clear();
isRendering = true;
for (auto it = _updateMap.begin(); it != _updateMap.end(); it++)
{
auto editor = it->first;
if (_removeList.size() > 0)
{
auto removeIt = std::find(_removeList.begin(), _removeList.end(), editor);
if (removeIt == _removeList.end())
{
editor->render(dt);
}
}
else
{
editor->render(dt);
}
}
isRendering = false;
for (auto it : _mbMap)
{
@@ -121,6 +140,8 @@ void MiddlewareManager::update(float dt)
buffer->uploadVB();
}
}
_clearRemoveList();
}
void MiddlewareManager::addTimer(IMiddleware* editor)
@@ -135,7 +156,7 @@ void MiddlewareManager::addTimer(IMiddleware* editor)
void MiddlewareManager::removeTimer(IMiddleware* editor)
{
if (isUpdating)
if (isUpdating || isRendering)
{
_removeList.push_back(editor);
}
@@ -36,9 +36,10 @@ MIDDLEWARE_BEGIN
*/
class IMiddleware {
public:
IMiddleware(){}
virtual ~IMiddleware(){}
IMiddleware() {}
virtual ~IMiddleware() {}
virtual void update(float dt) = 0;
virtual void render(float dt) = 0;
};
/**
@@ -66,11 +67,24 @@ public:
}
}
static uint8_t generateModuleID()
{
static uint8_t uniqueId = 0;
uniqueId++;
return uniqueId;
}
/**
* update by js
* @brief update all elements
* @param[in] dt Delta time.
*/
void update(float dt);
/**
* @brief render all elements
*/
void render(float dt);
/**
* @brief Third party module add in _updateMap,it will update perframe.
* @param[in] editor Module must implement IMiddleware interface.
@@ -88,10 +102,13 @@ public:
MiddlewareManager();
~MiddlewareManager();
// If manager is traversing _updateMap,will set the flag,untill traverse is finished.
// If manager is traversing _updateMap, will set the flag untill traverse is finished.
bool isRendering = false;
bool isUpdating = false;
private:
void _clearRemoveList();
private:
std::map<IMiddleware*, bool> _updateMap;
std::vector<IMiddleware*> _removeList;
std::map<int, MeshBuffer*> _mbMap;
@@ -23,10 +23,16 @@
#include "dragonbones-creator-support/CCArmatureDisplay.h"
#include "dragonbones-creator-support/CCSlot.h"
#include "MiddlewareMacro.h"
#include "RenderInfoMgr.h"
#include "renderer/renderer/Pass.h"
#include "renderer/renderer/Technique.h"
USING_NS_CC;
USING_NS_MW;
using namespace cocos2d::renderer;
static const std::string techStage = "opaque";
static const std::string textureKey = "texture";
static const uint8_t moduleID = MiddlewareManager::generateModuleID();
DRAGONBONES_NAMESPACE_BEGIN
@@ -46,23 +52,30 @@ CCArmatureDisplay* CCArmatureDisplay::create()
CCArmatureDisplay::CCArmatureDisplay()
{
_renderInfoOffset = new IOTypedArray(se::Object::TypedArrayType::UINT32, sizeof(uint32_t));
}
CCArmatureDisplay::~CCArmatureDisplay()
{
dispose();
if (_renderInfoOffset)
{
delete _renderInfoOffset;
_renderInfoOffset = nullptr;
}
if (_debugBuffer)
{
delete _debugBuffer;
_debugBuffer = nullptr;
}
CC_SAFE_RELEASE(_nodeProxy);
CC_SAFE_RELEASE(_effect);
}
void CCArmatureDisplay::dispose(bool disposeProxy)
{
if (_armature != nullptr)
{
_armature->dispose();
_armature = nullptr;
}
}
void CCArmatureDisplay::dbInit(Armature* armature)
@@ -76,62 +89,43 @@ void CCArmatureDisplay::dbClear()
release();
}
void CCArmatureDisplay::dispose(bool disposeProxy)
{
if (_armature != nullptr)
{
_armature->dispose();
_armature = nullptr;
}
}
void CCArmatureDisplay::dbUpdate() {}
void CCArmatureDisplay::dbUpdate()
void CCArmatureDisplay::dbRender()
{
_renderInfoOffset->reset();
_renderInfoOffset->clear();
if (this->_armature->getParent())
return;
auto mgr = MiddlewareManager::getInstance();
if (!mgr->isUpdating) return;
if (!mgr->isRendering) return;
if (_nodeProxy == nullptr)
{
return;
}
auto renderMgr = RenderInfoMgr::getInstance();
auto renderInfo = renderMgr->getBuffer();
if (renderInfo == nullptr) return;
// store renderInfo offset
_renderInfoOffset->writeUint32((uint32_t)renderInfo->getCurPos() / sizeof(uint32_t));
_assembler = (CustomAssembler*)_nodeProxy->getAssembler();
if (_assembler == nullptr)
{
return;
}
_assembler->reset();
_assembler->setUseModel(!_batch);
_preBlendMode = -1;
_preTextureIndex = -1;
_curTextureIndex = -1;
_curBlendSrc = -1;
_curBlendDst = -1;
_preISegWritePos = -1;
_preISegWritePos = -1;
_curISegLen = 0;
_debugSlotsLen = 0;
_materialLen = 0;
// check enough space
renderInfo->checkSpace(sizeof(uint32_t) * 2, true);
// write border
renderInfo->writeUint32(0xffffffff);
_materialLenOffset = renderInfo->getCurPos();
// Reserved space to save material len
renderInfo->writeUint32(0);
// Traverse all aramture to fill vertex and index buffer.
traverseArmature(_armature);
renderInfo->writeUint32(_materialLenOffset, _materialLen);
if (_preISegWritePos != -1)
{
renderInfo->writeUint32(_preISegWritePos, _curISegLen);
_assembler->updateIARange(_materialLen - 1, _preISegWritePos, _curISegLen);
}
if (_debugDraw)
@@ -172,7 +166,7 @@ void CCArmatureDisplay::dbUpdate()
{
_debugBuffer->writeFloat32(0, 0);
cocos2d::log("Dragonbones debug data is too large,debug buffer has no space to put in it!!!!!!!!!!");
cocos2d::log("You can adjust MAX_DEBUG_BUFFER_SIZE in Macro");
cocos2d::log("You can adjust MAX_DEBUG_BUFFER_SIZE in MiddlewareMacro");
}
}
}
@@ -211,18 +205,20 @@ CCArmatureDisplay* CCArmatureDisplay::getRootDisplay()
void CCArmatureDisplay::traverseArmature(Armature* armature, float parentOpacity)
{
static cocos2d::Mat4 matrixTemp;
const cocos2d::Mat4& nodeWorldMat = _nodeProxy->getWorldMatrix();
auto& slots = armature->getSlots();
auto mgr = MiddlewareManager::getInstance();
MeshBuffer* mb = mgr->getMeshBuffer(VF_XYUVC);
middleware::MeshBuffer* mb = mgr->getMeshBuffer(VF_XYUVC);
IOBuffer& vb = mb->getVB();
IOBuffer& ib = mb->getIB();
auto renderMgr = RenderInfoMgr::getInstance();
auto renderInfo = renderMgr->getBuffer();
if (!renderInfo) return;
float realOpacity = _nodeProxy->getRealOpacity() / 255.0f;
float r, g, b, a;
float r, g, b, a;
CCSlot* slot = nullptr;
middleware::Texture2D* texture = nullptr;
middleware::Texture2D* texture = nullptr;
int isFull = 0;
auto flush = [&]()
@@ -230,51 +226,85 @@ void CCArmatureDisplay::traverseArmature(Armature* armature, float parentOpacity
// fill pre segment count field
if (_preISegWritePos != -1)
{
renderInfo->writeUint32(_preISegWritePos, _curISegLen);
_assembler->updateIARange(_materialLen - 1, _preISegWritePos, _curISegLen);
}
// prepare to fill new segment field
switch (slot->_blendMode)
{
case BlendMode::Add:
_curBlendSrc = _premultipliedAlpha ? GL_ONE : GL_SRC_ALPHA;
_curBlendDst = GL_ONE;
_curBlendSrc = _premultipliedAlpha ? BlendFactor::ONE : BlendFactor::SRC_ALPHA;
_curBlendDst = BlendFactor::ONE;
break;
case BlendMode::Multiply:
_curBlendSrc = GL_DST_COLOR;
_curBlendDst = GL_ONE_MINUS_SRC_ALPHA;
_curBlendSrc = BlendFactor::DST_COLOR;
_curBlendDst = BlendFactor::ONE_MINUS_SRC_ALPHA;
break;
case BlendMode::Screen:
_curBlendSrc = GL_ONE;
_curBlendDst = GL_ONE_MINUS_SRC_COLOR;
_curBlendSrc = BlendFactor::ONE;
_curBlendDst = BlendFactor::ONE_MINUS_SRC_COLOR;
break;
default:
_curBlendSrc = _premultipliedAlpha ? GL_ONE : GL_SRC_ALPHA;
_curBlendDst = GL_ONE_MINUS_SRC_ALPHA;
_curBlendSrc = _premultipliedAlpha ? BlendFactor::ONE : BlendFactor::SRC_ALPHA;
_curBlendDst = BlendFactor::ONE_MINUS_SRC_ALPHA;
break;
}
// check enough space
renderInfo->checkSpace(sizeof(uint32_t) * 7, true);
double curHash = _curTextureIndex + (moduleID << 16) + ((uint8_t)slot->_blendMode << 24);
// fill new texture index
renderInfo->writeUint32(_curTextureIndex);
// fill new blend src and dst
renderInfo->writeUint32(_curBlendSrc);
renderInfo->writeUint32(_curBlendDst);
// fill new index and vertex buffer id
auto glIB = mb->getGLIB();
auto glVB = mb->getGLVB();
renderInfo->writeUint32(glIB);
renderInfo->writeUint32(glVB);
// fill new index offset
renderInfo->writeUint32((uint32_t)ib.getCurPos() / sizeof(unsigned short));
// save new segment count pos field
_preISegWritePos = (int)renderInfo->getCurPos();
// reserve indice segamentation count
renderInfo->writeUint32(0);
Effect* renderEffect = _assembler->getEffect(_materialLen);
Technique::Parameter* param = nullptr;
Pass* pass = nullptr;
if (renderEffect)
{
double renderHash = renderEffect->getHash();
if (abs(renderHash - curHash) >= 0.01)
{
param = (Technique::Parameter*)&(renderEffect->getProperty(textureKey));
Technique* tech = renderEffect->getTechnique(techStage);
Vector<Pass*>& passes = (Vector<Pass*>&)tech->getPasses();
pass = *(passes.begin());
}
}
else
{
if (_effect == nullptr)
{
cocos2d::log("ArmatureDisplay:update get effect failed");
_assembler->reset();
return;
}
auto effect = new cocos2d::renderer::Effect();
effect->autorelease();
effect->copy(_effect);
Technique* tech = effect->getTechnique(techStage);
Vector<Pass*>& passes = (Vector<Pass*>&)tech->getPasses();
pass = *(passes.begin());
_assembler->updateEffect(_materialLen, effect);
renderEffect = effect;
param = (Technique::Parameter*)&(renderEffect->getProperty(textureKey));
}
if (param)
{
param->setTexture(texture->getNativeTexture());
}
if (pass)
{
pass->setBlend(BlendOp::ADD, _curBlendSrc, _curBlendDst,
BlendOp::ADD, _curBlendSrc, _curBlendDst);
}
renderEffect->updateHash(curHash);
// save new segment count pos field
_preISegWritePos = (int)ib.getCurPos()/sizeof(unsigned short);
// save new segment vb and ib
_assembler->updateIABuffer(_materialLen, mb->getGLVB(), mb->getGLIB());
// reset pre blend mode to current
_preBlendMode = (int)slot->_blendMode;
// reset pre texture index to current
@@ -319,7 +349,7 @@ void CCArmatureDisplay::traverseArmature(Armature* armature, float parentOpacity
}
// Calculation vertex color.
a = _nodeColor.a * slot->color.a * parentOpacity;
a = realOpacity * slot->color.a * parentOpacity;
float multiplier = _premultipliedAlpha ? a / 255.0f : 1.0f;
r = _nodeColor.r * slot->color.r * multiplier;
g = _nodeColor.g * slot->color.g * multiplier;
@@ -327,14 +357,21 @@ void CCArmatureDisplay::traverseArmature(Armature* armature, float parentOpacity
// Transform component matrix to global matrix
middleware::Triangles& triangles = slot->triangles;
cocos2d::Mat4& worldMatrix = slot->worldMatrix;
cocos2d::Mat4* worldMatrix = &slot->worldMatrix;
if (_batch) {
cocos2d::Mat4::multiply(nodeWorldMat, *worldMatrix, &matrixTemp);
worldMatrix = &matrixTemp;
}
middleware::V2F_T2F_C4B* worldTriangles = slot->worldVerts;
for (int v = 0, w = 0, vn = triangles.vertCount; v < vn; ++v, w += 2)
{
middleware::V2F_T2F_C4B* vertex = triangles.verts + v;
middleware::V2F_T2F_C4B* worldVertex = worldTriangles + v;
worldVertex->vertex.x = vertex->vertex.x * worldMatrix.m[0] + vertex->vertex.y * worldMatrix.m[4] + worldMatrix.m[12];
worldVertex->vertex.y = vertex->vertex.x * worldMatrix.m[1] + vertex->vertex.y * worldMatrix.m[5] + worldMatrix.m[13];
worldVertex->vertex.x = vertex->vertex.x * worldMatrix->m[0] + vertex->vertex.y * worldMatrix->m[4] + worldMatrix->m[12];
worldVertex->vertex.y = vertex->vertex.x * worldMatrix->m[1] + vertex->vertex.y * worldMatrix->m[5] + worldMatrix->m[13];
worldVertex->color.r = (GLubyte)r;
worldVertex->color.g = (GLubyte)g;
worldVertex->color.b = (GLubyte)b;
@@ -32,6 +32,11 @@
#include "dragonbones-creator-support/CCSlot.h"
#include "IOTypedArray.h"
#include "MiddlewareManager.h"
#include "renderer/scene/NodeProxy.hpp"
#include "base/CCMap.h"
#include "middleware-adapter.h"
#include "renderer/scene/assembler/CustomAssembler.hpp"
#include "renderer/Types.h"
DRAGONBONES_NAMESPACE_BEGIN
/**
@@ -72,6 +77,10 @@ public:
* @inheritDoc
*/
virtual void dbUpdate() override;
/**
* @inheritDoc
*/
virtual void dbRender() override;
/**
* @inheritDoc
*/
@@ -120,17 +129,19 @@ public:
return nullptr;
}
/**
* @return render info offset,it's a Uint32Array,
* format |render info offset|
*/
se_object_ptr getRenderInfoOffset() const
void bindNodeProxy(cocos2d::renderer::NodeProxy* node)
{
if (_renderInfoOffset)
{
return _renderInfoOffset->getTypeArray();
}
return nullptr;
CC_SAFE_RELEASE(_nodeProxy);
_nodeProxy = node;
CC_SAFE_RETAIN(_nodeProxy);
}
void setEffect(cocos2d::renderer::Effect* effect)
{
if (effect == _effect) return;
CC_SAFE_RELEASE(_effect);
_effect = effect;
CC_SAFE_RETAIN(_effect);
}
void setColor(cocos2d::Color4B& color)
@@ -146,6 +157,11 @@ public:
_debugDraw = enabled;
}
void setBatchEnabled (bool enabled)
{
_batch = enabled;
}
void setOpacityModifyRGB (bool value)
{
_premultipliedAlpha = value;
@@ -171,25 +187,27 @@ public:
private:
std::map<std::string,bool> _listenerIDMap;
cocos2d::middleware::IOTypedArray* _renderInfoOffset = nullptr;
cocos2d::middleware::IOTypedArray* _debugBuffer = nullptr;
cocos2d::Color4F _nodeColor = cocos2d::Color4F::WHITE;
int _preBlendMode = -1;
int _preTextureIndex = -1;
int _curTextureIndex = -1;
int _curBlendSrc = -1;
int _curBlendDst = -1;
cocos2d::renderer::BlendFactor _curBlendSrc;
cocos2d::renderer::BlendFactor _curBlendDst;
int _preISegWritePos = -1;
int _curISegLen = 0;
int _debugSlotsLen = 0;
int _materialLen = 0;
std::size_t _materialLenOffset = -1;
bool _batch = false;
bool _premultipliedAlpha = false;
dbEventCallback _dbEventCallback = nullptr;
cocos2d::renderer::NodeProxy* _nodeProxy = nullptr;
cocos2d::renderer::Effect* _effect = nullptr;
cocos2d::renderer::CustomAssembler* _assembler = nullptr;
};
DRAGONBONES_NAMESPACE_END
@@ -119,6 +119,11 @@ public:
_dragonBonesInstance->advanceTime(dt);
}
virtual void render(float dt) override
{
_dragonBonesInstance->render();
}
/**
* @note When script engine clean up is trigger,will stop dragonbones timer.
*/
@@ -35,7 +35,6 @@ void CCSlot::_onClear()
_localMatrix.setIdentity();
worldMatrix.setIdentity();
_worldMatDirty = true;
_textureScale = 1.0f;
}
void CCSlot::disposeTriangles()
@@ -109,7 +108,7 @@ void CCSlot::_addDisplay()
void CCSlot::_replaceDisplay(void* value, bool isArmatureDisplay)
{
_textureScale = 1.0f;
}
void CCSlot::_removeDisplay()
@@ -224,8 +223,6 @@ void CCSlot::_updateFrame()
vertexIndices[i] = intArray[currentVerticesData->offset + (unsigned)BinaryOffset::MeshVertexIndices + i];
}
_textureScale = 1.0f;
const auto isSkinned = currentVerticesData->weight != nullptr;
if (isSkinned)
{
@@ -373,7 +370,7 @@ void CCSlot::_updateMesh()
const auto intArray = data->intArray;
const auto floatArray = data->floatArray;
const auto vertexCount = (std::size_t)intArray[verticesData->offset + (unsigned)BinaryOffset::MeshVertexCount];
int vertexOffset = (std::size_t)intArray[verticesData->offset + (unsigned)BinaryOffset::MeshFloatOffset];
std::size_t vertexOffset = (std::size_t)intArray[verticesData->offset + (unsigned)BinaryOffset::MeshFloatOffset];
if (vertexCount > triangles.vertCount) {
return;
@@ -430,27 +427,19 @@ void CCSlot::_updateMesh()
void CCSlot::_updateTransform()
{
_localMatrix.m[0] = globalTransformMatrix.a;
_localMatrix.m[1] = -globalTransformMatrix.b;
_localMatrix.m[1] = globalTransformMatrix.b;
_localMatrix.m[4] = -globalTransformMatrix.c;
_localMatrix.m[5] = globalTransformMatrix.d;
_localMatrix.m[5] = -globalTransformMatrix.d;
if (_childArmature)
{
_localMatrix.m[12] = globalTransformMatrix.tx;
_localMatrix.m[13] = -globalTransformMatrix.ty;
_localMatrix.m[13] = globalTransformMatrix.ty;
}
else
{
if (_textureScale != 1.0f)
{
_localMatrix.m[0] *= _textureScale;
_localMatrix.m[1] *= _textureScale;
_localMatrix.m[4] *= _textureScale;
_localMatrix.m[5] *= _textureScale;
}
_localMatrix.m[12] = globalTransformMatrix.tx - (globalTransformMatrix.a * _pivotX - globalTransformMatrix.c * _pivotY);
_localMatrix.m[13] = -(globalTransformMatrix.ty - (globalTransformMatrix.b * _pivotX - globalTransformMatrix.d * _pivotY));
_localMatrix.m[13] = globalTransformMatrix.ty - (globalTransformMatrix.b * _pivotX - globalTransformMatrix.d * _pivotY);
}
_worldMatDirty = true;
@@ -501,8 +490,8 @@ void CCSlot::_identityTransform()
{
_localMatrix.m[0] = 1.0f;
_localMatrix.m[1] = 0.0f;
_localMatrix.m[4] = 0.0f;
_localMatrix.m[5] = 1.0f;
_localMatrix.m[4] = -0.0f;
_localMatrix.m[5] = -1.0f;
_localMatrix.m[12] = 0.0f;
_localMatrix.m[13] = 0.0f;
@@ -56,7 +56,6 @@ public:
cocos2d::Color4B color;
cocos2d::Rect boundsRect;
private:
float _textureScale = 1.0f;
cocos2d::Mat4 _localMatrix;
private:
void disposeTriangles();
@@ -60,6 +60,19 @@ public:
* @language zh_CN
*/
virtual void advanceTime(float passedTime) = 0;
/**
* - Render.
* @version Cocos creator 2.3
* @language en_US
*/
/**
* - 渲染。
* @version Cocos creator 2.3
* @language zh_CN
*/
virtual void render() = 0;
/**
* - The Wordclock instance to which the current belongs.
* @example
@@ -113,6 +113,17 @@ void WorldClock::remove(IAnimatable* value)
}
}
void WorldClock::render()
{
for (const auto animatable : _animatebles)
{
if (animatable != nullptr)
{
animatable->render();
}
}
}
void WorldClock::clear()
{
for (const auto animatable : _animatebles)
@@ -130,6 +130,18 @@ public:
* @language zh_CN
*/
virtual void advanceTime(float passedTime) override;
/**
* - render all IAnimatable instances.
* @version Cocos creator 2.3
* @language en_US
*/
/**
* - 渲染所有的 IAnimatable 实例。
* @version Cocos creator 2.3
* @language zh_CN
*/
virtual void render() override;
/**
* - Check whether contains a specific instance of IAnimatable.
* @param value - The IAnimatable instance.
@@ -273,6 +273,14 @@ void Armature::advanceTime(float passedTime)
_proxy->dbUpdate();
}
void Armature::render()
{
if (_proxy)
{
_proxy->dbRender();
}
}
void Armature::invalidUpdate(const std::string& boneName, bool updateSlot)
{
if (!boneName.empty())
@@ -189,6 +189,10 @@ public:
* @inheritDoc
*/
void advanceTime(float passedTime) override;
/**
* @inheritDoc
*/
void render() override;
/**
* - Forces a specific bone or its owning slot to update the transform or display property in the next frame.
* @param boneName - The bone name. (If not set, all bones will be update)
@@ -25,6 +25,7 @@
#include "../core/DragonBones.h"
#include "../event/IEventDispatcher.h"
#include "MiddlewareManager.h"
DRAGONBONES_NAMESPACE_BEGIN
/**
@@ -56,6 +57,10 @@ public:
* @internal
*/
virtual void dbUpdate() = 0;
/**
* @internal
*/
virtual void dbRender() = 0;
/**
* - Dispose the instance and the Armature instance. (The Armature instance will return to the object pool)
* @example
@@ -239,10 +239,10 @@ void Slot::_updateDisplayData()
_pivotY += _helpPoint.y;
}
//if (!DragonBones::yDown)
//{
if (!DragonBones::yDown)
{
_pivotY = (_textureData->rotated ? _textureData->region.width : _textureData->region.height) * scale - _pivotY;
//}
}
}
else
{
@@ -9,7 +9,7 @@ DRAGONBONES_NAMESPACE_BEGIN
const std::string DragonBones::VEISION = "5.6.300";
bool DragonBones::yDown = true;
bool DragonBones::yDown = false;
bool DragonBones::debug = false;
bool DragonBones::debugDraw = false;
bool DragonBones::webAssembly = false;
@@ -73,6 +73,11 @@ void DragonBones::advanceTime(float passedTime)
_clock->advanceTime(passedTime);
}
void DragonBones::render()
{
_clock->render();
}
void DragonBones::bufferEvent(EventObject* value)
{
_events.push_back(value);
@@ -471,6 +471,7 @@ public:
virtual ~DragonBones();
void advanceTime(float passedTime);
void render();
void bufferEvent(EventObject* value);
void bufferObject(BaseObject* object);
@@ -550,7 +550,7 @@ bool BaseFactory::replaceSlotDisplayList(const std::string& dragonBonesName, con
return true;
}
bool BaseFactory::replaceSkin(Armature* armature, SkinData* skin, bool isOverride, const std::vector<std::string>* exclude) const
bool BaseFactory::replaceSkin(Armature* armature, SkinData* skin, bool isOverride, const std::vector<std::string>& exclude) const
{
DRAGONBONES_ASSERT(armature && skin, "Arguments error.");
@@ -559,7 +559,7 @@ bool BaseFactory::replaceSkin(Armature* armature, SkinData* skin, bool isOverrid
for (const auto slot : armature->getSlots())
{
if (exclude != nullptr && std::find(exclude->cbegin(), exclude->cend(), slot->getName()) != exclude->cend())
if (std::find(exclude.cbegin(), exclude.cend(), slot->getName()) != exclude.cend())
{
continue;
}
@@ -478,7 +478,7 @@ public:
* @version DragonBones 5.6
* @language zh_CN
*/
virtual bool replaceSkin(Armature* armature, SkinData* skin, bool isOverride = false, const std::vector<std::string>* exclude = nullptr) const;
virtual bool replaceSkin(Armature* armature, SkinData* skin, bool isOverride, const std::vector<std::string>& exclude) const;
/**
* - Replaces the existing animation data for a specific armature with the animation data for the specific armature data.
* This enables you to make a armature template so that other armature without animations can share it's animations.
@@ -559,7 +559,7 @@ public:
* @deprecated
* @language zh_CN
*/
inline bool changeSkin(Armature* armature, SkinData* skin, const std::vector<std::string>* exclude = nullptr) const
inline bool changeSkin(Armature* armature, SkinData* skin, const std::vector<std::string>& exclude) const
{
return replaceSkin(armature, skin, false, exclude);
}
@@ -23,6 +23,10 @@
****************************************************************************/
#include "middleware-adapter.h"
#include "base/ccMacros.h"
#include "renderer/gfx/Texture.h"
using namespace cocos2d;
using namespace cocos2d::renderer;
MIDDLEWARE_BEGIN
@@ -33,7 +37,8 @@ Texture2D::Texture2D()
Texture2D::~Texture2D()
{
CC_SAFE_RELEASE(_texture);
_texParamCallback = nullptr;
}
int Texture2D::getPixelsWide() const
@@ -79,6 +84,19 @@ void Texture2D::setTexParameters(const TexParams& texParams)
}
}
void Texture2D::setNativeTexture(Texture* texture)
{
if (_texture == texture) return;
CC_SAFE_RELEASE(_texture);
_texture = texture;
CC_SAFE_RETAIN(_texture);
}
Texture* Texture2D::getNativeTexture() const
{
return _texture;
}
SpriteFrame* SpriteFrame::createWithTexture(Texture2D *texture, const cocos2d::Rect& rect)
{
SpriteFrame *spriteFrame = new (std::nothrow) SpriteFrame();
@@ -27,6 +27,7 @@
#include "base/ccTypes.h"
#include <functional>
#include "MiddlewareMacro.h"
#include "renderer/renderer/Effect.h"
MIDDLEWARE_BEGIN
/**
@@ -105,7 +106,7 @@ public:
virtual ~Texture2D();
/**
Extension to set the Min / Mag filter
*/
*/
typedef struct _TexParams
{
GLuint minFilter;
@@ -121,16 +122,16 @@ public:
/** Sets the min filter, mag filter, wrap s and wrap t texture parameters.
If the texture size is NPOT (non power of 2), then in can only use GL_CLAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T}.
@warning Calling this method could allocate additional texture memory.
@since v0.8
* @code
* When this function bound into js or lua,the input parameter will be changed
* In js: var setBlendFunc(var arg1, var arg2, var arg3, var arg4)
* In lua: local setBlendFunc(local arg1, local arg2, local arg3, local arg4)
* @endcode
*/
@warning Calling this method could allocate additional texture memory.
@since v0.8
* @code
* When this function bound into js or lua,the input parameter will be changed
* In js: var setBlendFunc(var arg1, var arg2, var arg3, var arg4)
* In lua: local setBlendFunc(local arg1, local arg2, local arg3, local arg4)
* @endcode
*/
void setTexParameters(const TexParams& texParams);
/** Gets the width of the texture in pixels. */
@@ -153,6 +154,12 @@ public:
/** Sets texture param callback*/
void setTexParamCallback(const texParamCallback& callback);
/** Sets texture native ptr*/
void setNativeTexture(cocos2d::renderer::Texture* texture);
/** Gets texture native ptr*/
cocos2d::renderer::Texture* getNativeTexture() const;
private:
/** width in pixels */
@@ -165,6 +172,8 @@ private:
int _realTextureIndex = 0;
texParamCallback _texParamCallback = nullptr;
cocos2d::renderer::Texture* _texture = nullptr;
};
///////////////////////////////////////////////////////////////////////
@@ -0,0 +1,462 @@
/****************************************************************************
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "ParticleSimulator.h"
#include "base/ccRandom.h"
#include <algorithm>
#include "base/ccMacros.h"
#include "math/Mat4.h"
#include "MiddlewareManager.h"
#include "middleware-adapter.h"
#include "renderer/scene/assembler/CustomAssembler.hpp"
#include "math/Vec2.h"
USING_NS_MW;
NS_CC_BEGIN
// global particle pool
static ParticlePool _pool;
void Particle::reset()
{
pos = cocos2d::Vec3::ZERO;
startPos = cocos2d::Vec3::ZERO;
color = cocos2d::Color4B::BLACK;
deltaColor = cocos2d::Color4B::BLACK;
size = 0;
deltaSize = 0;
rotation = 0;
deltaRotation = 0;
timeToLive = 0;
drawPos = cocos2d::Vec3::ZERO;
// Mode A
dir = cocos2d::Vec3::ZERO;
radialAccel = 0;
tangentialAccel = 0;
// Mode B
angle = 0;
degreesPerSecond = 0;
radius = 0;
deltaRadius = 0;
}
ParticlePool::ParticlePool()
{
}
ParticlePool::~ParticlePool()
{
for (auto particle : _pool)
{
delete particle;
}
_pool.clear();
}
ParticleSimulator::ParticleSimulator()
{
}
ParticleSimulator::~ParticleSimulator()
{
onDisable();
CC_SAFE_RELEASE(_effect);
CC_SAFE_RELEASE(_nodeProxy);
for (auto particle : _particles)
{
delete particle;
}
_particles.clear();
}
void ParticleSimulator::stop()
{
_active = false;
_elapsed = duration;
_emitCounter = 0;
}
void ParticleSimulator::reset()
{
_active = true;
_elapsed = 0;
_emitCounter = 0;
_finished = false;
for (auto particle : _particles)
{
_pool.put(particle);
}
_particles.clear();
}
void ParticleSimulator::emitParticle(cocos2d::Vec3 &pos)
{
auto& particle = *_pool.get();
_particles.push_back(&particle);
// Init particle
// timeToLive
// no negative life. prevent division by 0
particle.timeToLive = life + lifeVar * random(-1.0f, 1.0f);
// avoid divide zero
float timeToLive = particle.timeToLive = std::max(0.001f, particle.timeToLive);
// position
particle.pos.x = _sourcePos.x + _posVar.x * random(-1.0f, 1.0f);
particle.pos.y = _sourcePos.y + _posVar.y * random(-1.0f, 1.0f);
// Color
GLubyte sr, sg, sb, sa;
particle.color.r = sr = clampf(_startColor.r + _startColorVar.r * random(-1.0f, 1.0f), 0, 255);
particle.color.g = sg = clampf(_startColor.g + _startColorVar.g * random(-1.0f, 1.0f), 0, 255);
particle.color.b = sb = clampf(_startColor.b + _startColorVar.b * random(-1.0f, 1.0f), 0, 255);
particle.color.a = sa = clampf(_startColor.a + _startColorVar.a * random(-1.0f, 1.0f), 0, 255);
particle.deltaColor.r = (clampf(_endColor.r + _endColorVar.r * random(-1.0f, 1.0f), 0, 255) - sr) / timeToLive;
particle.deltaColor.g = (clampf(_endColor.g + _endColorVar.g * random(-1.0f, 1.0f), 0, 255) - sg) / timeToLive;
particle.deltaColor.b = (clampf(_endColor.b + _endColorVar.b * random(-1.0f, 1.0f), 0, 255) - sb) / timeToLive;
particle.deltaColor.a = (clampf(_endColor.a + _endColorVar.a * random(-1.0f, 1.0f), 0, 255) - sa) / timeToLive;
// size
float startS = startSize + startSizeVar * random(-1.0f, 1.0f);
startS = std::max(0.0f, startS); // No negative value
particle.size = startS;
if (endSize == START_SIZE_EQUAL_TO_END_SIZE)
{
particle.deltaSize = 0;
}
else
{
float endS = endSize + endSizeVar * random(-1.0f, 1.0f);
endS = std::max(0.0f, endS); // No negative values
particle.deltaSize = (endS - startS) / timeToLive;
}
// rotation
float startA = startSpin + startSpinVar * random(-1.0f, 1.0f);
float endA = endSpin + endSpinVar * random(-1.0f, 1.0f);
particle.rotation = startA;
particle.deltaRotation = (endA - startA) / timeToLive;
// position
particle.startPos.x = pos.x;
particle.startPos.y = pos.y;
// direction
float a = CC_DEGREES_TO_RADIANS(angle + angleVar * random(-1.0f, 1.0f));
// Mode Gravity: A
if (emitterMode == EmitterMode::GRAVITY)
{
float s = speed + speedVar * random(-1.0f, 1.0f);
// direction
particle.dir.x = cos(a);
particle.dir.y = sin(a);
particle.dir.scale(s);
// radial accel
particle.radialAccel = radialAccel + radialAccelVar * random(-1.0f, 1.0f);
// tangential accel
particle.tangentialAccel = tangentialAccel + tangentialAccelVar * random(-1.0f, 1.0f);
// rotation is dir
if (rotationIsDir)
{
particle.rotation = -CC_RADIANS_TO_DEGREES(atan2(particle.dir.y, particle.dir.x));
}
}
// Mode Radius: B
else
{
// Set the default diameter of the particle from the source position
float tempStartRadius = startRadius + startRadiusVar * random(-1.0f, 1.0f);
float tempEndRadius = endRadius + endRadiusVar * random(-1.0f, 1.0f);
particle.radius = tempStartRadius;
particle.deltaRadius = (endRadius == START_RADIUS_EQUAL_TO_END_RADIUS) ? 0 : (tempEndRadius - tempStartRadius) / timeToLive;
particle.angle = a;
particle.degreesPerSecond = CC_DEGREES_TO_RADIANS(rotatePerS + rotatePerSVar * random(-1.0f, 1.0f));
}
}
void ParticleSimulator::onEnable()
{
MiddlewareManager::getInstance()->addTimer(this);
}
void ParticleSimulator::onDisable()
{
MiddlewareManager::getInstance()->removeTimer(this);
}
void ParticleSimulator::render(float dt)
{
// uv size must equal 8,because per particle has 4 vertex.
if (_uv.size() != 8)
{
return;
}
if (_nodeProxy == nullptr)
{
return;
}
renderer::CustomAssembler* assembler = (renderer::CustomAssembler*)_nodeProxy->getAssembler();
if (assembler == nullptr)
{
return;
}
assembler->reset();
assembler->updateEffect(0, _effect);
// avoid other place call update.
auto mgr = MiddlewareManager::getInstance();
if (!mgr->isRendering) return;
middleware::MeshBuffer* mb = mgr->getMeshBuffer(VF_XYUVC);
middleware::IOBuffer& vb = mb->getVB();
middleware::IOBuffer& ib = mb->getIB();
// Calculate pos
auto worldMatrix = _nodeProxy->getWorldMatrix();
cocos2d::Vec3 pos;
cocos2d::Vec3 tpa;
cocos2d::Vec3 tpb;
cocos2d::Vec3 tpc;
if (positionType == PositionType::FREE)
{
worldMatrix.transformPoint(&pos);
}
else if (positionType == PositionType::RELATIVE)
{
_nodeProxy->getPosition(&pos);
}
// Get world to node trans only once
worldMatrix.inverse();
// Emission
if (_active && emissionRate)
{
float rate = 1.0 / emissionRate;
//issue #1201, prevent bursts of particles, due to too high emitCounter
if (_particles.size() < totalParticles)
_emitCounter += dt;
while ((_particles.size() < totalParticles) && (_emitCounter > rate))
{
emitParticle(pos);
_emitCounter -= rate;
}
_elapsed += dt;
if (duration != -1 && duration < _elapsed)
{
_stopCallback();
}
}
// Used to reduce memory allocation / creation within the loop
std::size_t particleIdx = 0;
std::size_t particleSize = _particles.size();
vb.checkSpace(particleSize * 4 * sizeof (middleware::V2F_T2F_C4B));
ib.checkSpace(particleSize * 6 * sizeof (unsigned short));
std::size_t vbOffset = vb.getCurPos() / sizeof (middleware::V2F_T2F_C4B);
uint32_t indexStart = (uint32_t)ib.getCurPos()/sizeof(unsigned short);
uint32_t indexCount = 0;
while (particleIdx < particleSize)
{
// Reset temporary vectors
tpa.x = tpa.y = tpb.x = tpb.y = tpc.x = tpc.y = 0;
auto& particle = *_particles[particleIdx];
// life
particle.timeToLive -= dt;
if (particle.timeToLive > 0)
{
// Mode A: gravity, direction, tangential accel & radial accel
if (emitterMode == EmitterMode::GRAVITY)
{
auto& tmp = tpc;
auto& radial = tpa;
auto& tangential = tpb;
// radial acceleration
if (particle.pos.x || particle.pos.y)
{
radial.set(particle.pos);
radial.normalize();
}
tangential.set(radial);
radial.scale(particle.radialAccel);
// tangential acceleration
auto newy = tangential.x;
tangential.x = -tangential.y;
tangential.y = newy;
tangential.scale(particle.tangentialAccel);
tmp.set(radial);
tmp.add(tangential);
tmp.add(_gravity.x, _gravity.y, _gravity.z);
tmp.scale(dt);
particle.dir.add(tmp);
tmp.set(particle.dir);
tmp.scale(dt);
particle.pos.add(tmp);
}
// Mode B: radius movement
else
{
// Update the angle and radius of the particle.
particle.angle += particle.degreesPerSecond * dt;
particle.radius += particle.deltaRadius * dt;
particle.pos.x = -cos(particle.angle) * particle.radius;
particle.pos.y = -sin(particle.angle) * particle.radius;
}
// color
particle.color.r += particle.deltaColor.r * dt;
particle.color.g += particle.deltaColor.g * dt;
particle.color.b += particle.deltaColor.b * dt;
particle.color.a += particle.deltaColor.a * dt;
// size
particle.size += particle.deltaSize * dt;
if (particle.size < 0)
{
particle.size = 0;
}
// angle
particle.rotation += particle.deltaRotation * dt;
// update values in quad buffer
auto& newPos = tpa;
if (positionType == PositionType::FREE || positionType == PositionType::RELATIVE)
{
auto& diff = tpb;
auto& startPos = tpc;
// current Position convert To Node Space
worldMatrix.transformPoint(pos, &diff);
// start Position convert To Node Space
worldMatrix.transformPoint(particle.startPos, &startPos);
diff.add(-startPos.x, -startPos.y, -startPos.z);
newPos.set(particle.pos);
newPos.add(-diff.x, -diff.y, -diff.z);
}
else
{
newPos.set(particle.pos);
}
auto x = newPos.x, y = newPos.y;
auto size_2 = particle.size * 0.5;
auto x1 = -size_2, y1 = -size_2;
auto x2 = size_2, y2 = size_2;
auto rad = -CC_DEGREES_TO_RADIANS(particle.rotation);
auto cr = cos(rad), sr = sin(rad);
uint32_t tempColor = ((particle.color.a << 24) & 0xff000000) +
((particle.color.b << 16) & 0x00ff0000) +
((particle.color.g << 8) & 0x0000ff00) +
((particle.color.r) & 0x000000ff);
// bl
vb.writeFloat32(x1 * cr - y1 * sr + x);
vb.writeFloat32(x1 * sr + y1 * cr + y);
vb.writeFloat32(_uv[0]);
vb.writeFloat32(_uv[1]);
vb.writeUint32(tempColor);
// br
vb.writeFloat32(x2 * cr - y1 * sr + x);
vb.writeFloat32(x2 * sr + y1 * cr + y);
vb.writeFloat32(_uv[2]);
vb.writeFloat32(_uv[3]);
vb.writeUint32(tempColor);
// tl
vb.writeFloat32(x1 * cr - y2 * sr + x);
vb.writeFloat32(x1 * sr + y2 * cr + y);
vb.writeFloat32(_uv[4]);
vb.writeFloat32(_uv[5]);
vb.writeUint32(tempColor);
// tr
vb.writeFloat32(x2 * cr - y2 * sr + x);
vb.writeFloat32(x2 * sr + y2 * cr + y);
vb.writeFloat32(_uv[6]);
vb.writeFloat32(_uv[7]);
vb.writeUint32(tempColor);
ib.writeUint16(vbOffset);
ib.writeUint16(vbOffset + 1);
ib.writeUint16(vbOffset + 2);
ib.writeUint16(vbOffset + 1);
ib.writeUint16(vbOffset + 3);
ib.writeUint16(vbOffset + 2);
vbOffset += 4;
indexCount += 6;
// update particle counter
++particleIdx;
}
else
{
// life < 0
auto deadParticle = _particles[particleIdx];
if (particleIdx != particleSize - 1)
{
_particles[particleIdx] = _particles[particleSize - 1];
}
_pool.put(deadParticle);
particleSize--;
_particles.resize(particleSize);
}
}
assembler->updateIABuffer(0, mb->getGLVB(), mb->getGLIB());
assembler->updateIARange(0, indexStart, indexCount);
if (_particles.size() == 0 && !_active)
{
_finished = true;
if (_finishedCallback)
{
_finishedCallback();
}
}
}
NS_CC_END
@@ -0,0 +1,281 @@
/****************************************************************************
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "MiddlewareMacro.h"
#include "math/Vec3.h"
#include "base/ccTypes.h"
#include <vector>
#include "IOBuffer.h"
#include "renderer/scene/NodeProxy.hpp"
#include "renderer/renderer/Effect.h"
#include "MiddlewareManager.h"
#include "scripting/js-bindings/jswrapper/SeApi.h"
NS_CC_BEGIN
struct Particle {
public:
cocos2d::Vec3 pos;
cocos2d::Vec3 startPos;
cocos2d::Color4B color = cocos2d::Color4B::BLACK;
cocos2d::Color4B deltaColor = cocos2d::Color4B::BLACK;
float size = 0.0f;
float deltaSize = 0.0f;
float rotation = 0.0f;
float deltaRotation = 0.0f;
float timeToLive = 0.0f;
cocos2d::Vec3 drawPos;
// Mode A
cocos2d::Vec3 dir;
float radialAccel = 0.0f;
float tangentialAccel = 0.0f;
// Mode B
float angle = 0.0f;
float degreesPerSecond = 0.0f;
float radius = 0.0f;
float deltaRadius = 0.0f;
bool inPool = false;
void reset();
};
class ParticlePool {
public:
ParticlePool();
~ParticlePool();
void put(Particle* particle)
{
CCASSERT(!particle->inPool, "Particle is in pool already");
_pool.push_back(particle);
particle->inPool = true;
particle->reset();
}
Particle* get()
{
Particle* obj = nullptr;
if (_pool.size() > 0)
{
obj = _pool.back();
_pool.pop_back();
obj->inPool = false;
} else {
obj = new Particle();
}
return obj;
}
private:
std::vector<Particle*> _pool;
};
enum PositionType
{
FREE = 0,
RELATIVE = 1,
GROUPED = 2
};
enum EmitterMode
{
GRAVITY = 0,
RADIUS = 1
};
class ParticleSimulator : public cocos2d::middleware::IMiddleware, public cocos2d::Ref {
//* @enum
enum {
/** The Particle emitter lives forever. */
DURATION_INFINITY = -1,
/** The starting size of the particle is equal to the ending size. */
START_SIZE_EQUAL_TO_END_SIZE = -1,
/** The starting radius of the particle is equal to the ending radius. */
START_RADIUS_EQUAL_TO_END_RADIUS = -1,
};
public:
ParticleSimulator();
~ParticleSimulator();
void stop();
void reset();
void emitParticle(cocos2d::Vec3& pos);
void update(float dt) override {}
void render(float dt) override;
void onEnable();
void onDisable();
typedef std::function<void()> finishedCallback;
void setFinishedCallback(finishedCallback callback)
{
_finishedCallback = callback;
}
typedef std::function<void()> stopCallback;
void setStopCallback(stopCallback callback)
{
_stopCallback = callback;
}
void bindNodeProxy(cocos2d::renderer::NodeProxy* node)
{
CC_SAFE_RELEASE(_nodeProxy);
_nodeProxy = node;
CC_SAFE_RETAIN(_nodeProxy);
}
void setEffect(cocos2d::renderer::Effect* effect)
{
CC_SAFE_RELEASE(_effect);
_effect = effect;
CC_SAFE_RETAIN(_effect);
}
void updateUVs(const std::vector<float>& uv)
{
_uv = uv;
}
std::size_t getParticleCount()
{
return _particles.size();
}
bool active()
{
return _active;
}
void setGravity(float x, float y, float z)
{
_gravity.x = x;
_gravity.y = y;
_gravity.z = z;
}
void setSourcePos(float x, float y, float z)
{
_sourcePos.x = x;
_sourcePos.y = y;
_sourcePos.z = z;
}
void setPosVar(float x, float y, float z)
{
_posVar.x = x;
_posVar.y = y;
_posVar.z = z;
}
void setStartColor(GLubyte r, GLubyte g, GLubyte b, GLubyte a)
{
_startColor.r = r;
_startColor.g = g;
_startColor.b = b;
_startColor.a = a;
}
void setStartColorVar(GLubyte r, GLubyte g, GLubyte b, GLubyte a)
{
_startColorVar.r = r;
_startColorVar.g = g;
_startColorVar.b = b;
_startColorVar.a = a;
}
void setEndColor(GLubyte r, GLubyte g, GLubyte b, GLubyte a)
{
_endColor.r = r;
_endColor.g = g;
_endColor.b = b;
_endColor.a = a;
}
void setEndColorVar(GLubyte r, GLubyte g, GLubyte b, GLubyte a)
{
_endColorVar.r = r;
_endColorVar.g = g;
_endColorVar.b = b;
_endColorVar.a = a;
}
private:
std::vector<Particle*> _particles;
bool _active = false;
bool _finished = false;
float _elapsed = 0;
float _emitCounter = 0;
std::size_t _uvFilled = 0;
finishedCallback _finishedCallback = nullptr;
stopCallback _stopCallback = nullptr;
cocos2d::renderer::NodeProxy* _nodeProxy = nullptr;
cocos2d::renderer::Effect* _effect = nullptr;
std::vector<float> _uv;
cocos2d::Vec3 _gravity;
cocos2d::Vec3 _sourcePos;
cocos2d::Vec3 _posVar;
cocos2d::Color4B _startColor = cocos2d::Color4B::BLACK;
cocos2d::Color4B _startColorVar = cocos2d::Color4B::WHITE;
cocos2d::Color4B _endColor = cocos2d::Color4B::BLACK;
cocos2d::Color4B _endColorVar = cocos2d::Color4B::WHITE;
public:
int positionType = PositionType::FREE;
float emissionRate = 0.0f;
std::size_t totalParticles = 0;
float duration = -1.0f;
int emitterMode = EmitterMode::GRAVITY;
float life = 0.0f;
float lifeVar = 0.0f;
float startSize = 0.0f;
float startSizeVar = 0.0f;
float endSize = 0.0f;
float endSizeVar = 0.0f;
float startSpin = 0.0f;
float startSpinVar = 0.0f;
float endSpin = 0.0f;
float endSpinVar = 0.0f;
float angle = 0.0f;
float angleVar = 0.0f;
float speed = 0.0f;
float speedVar = 0.0f;
float radialAccel = 0.0f;
float radialAccelVar = 0.0f;
float tangentialAccel = 0.0f;
float tangentialAccelVar = 0.0f;
bool rotationIsDir = false;
float startRadius = 0.0f;
float startRadiusVar = 0.0f;
float endRadius = 0.0f;
float endRadiusVar = 0.0f;
float rotatePerS = 0.0f;
float rotatePerSVar = 0.0f;
};
NS_CC_END
@@ -1,343 +1,342 @@
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated May 1, 2019. Replaces all prior versions.
*
* Copyright (c) 2013-2019, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS
* INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#include "spine-creator-support/SkeletonAnimation.h"
#include "spine-creator-support/spine-cocos2dx.h"
#include "spine/extension.h"
#include <algorithm>
USING_NS_CC;
using std::min;
using std::max;
using std::vector;
namespace spine {
typedef struct _TrackEntryListeners {
StartListener startListener;
InterruptListener interruptListener;
EndListener endListener;
DisposeListener disposeListener;
CompleteListener completeListener;
EventListener eventListener;
} _TrackEntryListeners;
void animationCallback (AnimationState* state, EventType type, TrackEntry* entry, Event* event) {
((SkeletonAnimation*)state->getRendererObject())->onAnimationStateEvent(entry, type, event);
}
void trackEntryCallback (AnimationState* state, EventType type, TrackEntry* entry, Event* event) {
((SkeletonAnimation*)state->getRendererObject())->onTrackEntryEvent(entry, type, event);
if (type == EventType_Dispose)
if (entry->getRendererObject()) delete (spine::_TrackEntryListeners*)entry->getRendererObject();
}
static _TrackEntryListeners* getListeners (TrackEntry* entry) {
if (!entry->getRendererObject()) {
entry->setRendererObject(new spine::_TrackEntryListeners());
entry->setListener(trackEntryCallback);
}
return (_TrackEntryListeners*)entry->getRendererObject();
}
static float globalTimeScale = 1.0f;
void SkeletonAnimation::setGlobalTimeScale(float timeScale) {
globalTimeScale = timeScale;
}
SkeletonAnimation* SkeletonAnimation::create() {
SkeletonAnimation* skeleton = new SkeletonAnimation();
skeleton->autorelease();
return skeleton;
}
SkeletonAnimation* SkeletonAnimation::createWithData (SkeletonData* skeletonData, bool ownsSkeletonData) {
SkeletonAnimation* node = new SkeletonAnimation();
node->initWithData(skeletonData, ownsSkeletonData);
node->autorelease();
return node;
}
SkeletonAnimation* SkeletonAnimation::createWithJsonFile (const std::string& skeletonJsonFile, Atlas* atlas, float scale) {
SkeletonAnimation* node = new SkeletonAnimation();
node->initWithJsonFile(skeletonJsonFile, atlas, scale);
node->autorelease();
return node;
}
SkeletonAnimation* SkeletonAnimation::createWithJsonFile (const std::string& skeletonJsonFile, const std::string& atlasFile, float scale) {
SkeletonAnimation* node = new SkeletonAnimation();
node->initWithJsonFile(skeletonJsonFile, atlasFile, scale);
node->autorelease();
return node;
}
SkeletonAnimation* SkeletonAnimation::createWithBinaryFile (const std::string& skeletonBinaryFile, Atlas* atlas, float scale) {
SkeletonAnimation* node = new SkeletonAnimation();
node->initWithBinaryFile(skeletonBinaryFile, atlas, scale);
node->autorelease();
return node;
}
SkeletonAnimation* SkeletonAnimation::createWithBinaryFile (const std::string& skeletonBinaryFile, const std::string& atlasFile, float scale) {
SkeletonAnimation* node = new SkeletonAnimation();
node->initWithBinaryFile(skeletonBinaryFile, atlasFile, scale);
node->autorelease();
return node;
}
void SkeletonAnimation::initialize () {
super::initialize();
_ownsAnimationStateData = true;
_state = new (__FILE__, __LINE__) AnimationState(new (__FILE__, __LINE__) AnimationStateData(_skeleton->getData()));
_state->setRendererObject(this);
_state->setListener(animationCallback);
}
SkeletonAnimation::SkeletonAnimation ()
: SkeletonRenderer() {
}
SkeletonAnimation::~SkeletonAnimation () {
_startListener = nullptr;
_interruptListener = nullptr;
_endListener = nullptr;
_disposeListener = nullptr;
_completeListener = nullptr;
_eventListener = nullptr;
if (_state) {
clearTracks();
if (_ownsAnimationStateData) delete _state->getData();
delete _state;
}
}
void SkeletonAnimation::update (float deltaTime) {
if (!_skeleton) return;
if (!_paused) {
deltaTime *= _timeScale * globalTimeScale;
if (_ownsSkeleton) _skeleton->update(deltaTime);
_state->update(deltaTime);
_state->apply(*_skeleton);
_skeleton->updateWorldTransform();
}
super::update(deltaTime);
}
void SkeletonAnimation::setAnimationStateData (AnimationStateData* stateData) {
CCASSERT(stateData, "stateData cannot be null.");
if (_state) {
if (_ownsAnimationStateData) delete _state->getData();
delete _state;
}
_ownsAnimationStateData = false;
_state = new (__FILE__, __LINE__) AnimationState(stateData);
_state->setRendererObject(this);
_state->setListener(animationCallback);
}
void SkeletonAnimation::setMix (const std::string& fromAnimation, const std::string& toAnimation, float duration) {
if (_state) {
_state->getData()->setMix(fromAnimation.c_str(), toAnimation.c_str(), duration);
}
}
TrackEntry* SkeletonAnimation::setAnimation (int trackIndex, const std::string& name, bool loop) {
if (!_skeleton) return 0;
Animation* animation = _skeleton->getData()->findAnimation(name.c_str());
if (!animation) {
log("Spine: Animation not found: %s", name.c_str());
return 0;
}
auto trackEntry = _state->setAnimation(trackIndex, animation, loop);
_state->apply(*_skeleton);
return trackEntry;
}
TrackEntry* SkeletonAnimation::addAnimation (int trackIndex, const std::string& name, bool loop, float delay) {
if (!_skeleton) return 0;
Animation* animation = _skeleton->getData()->findAnimation(name.c_str());
if (!animation) {
log("Spine: Animation not found: %s", name.c_str());
return 0;
}
return _state->addAnimation(trackIndex, animation, loop, delay);
}
TrackEntry* SkeletonAnimation::setEmptyAnimation (int trackIndex, float mixDuration) {
if (_state) {
return _state->setEmptyAnimation(trackIndex, mixDuration);
}
return nullptr;
}
void SkeletonAnimation::setEmptyAnimations (float mixDuration) {
if (_state) {
_state->setEmptyAnimations(mixDuration);
}
}
TrackEntry* SkeletonAnimation::addEmptyAnimation (int trackIndex, float mixDuration, float delay) {
if (_state) {
return _state->addEmptyAnimation(trackIndex, mixDuration, delay);
}
return nullptr;
}
Animation* SkeletonAnimation::findAnimation(const std::string& name) const {
if (_skeleton) {
return _skeleton->getData()->findAnimation(name.c_str());
}
return nullptr;
}
TrackEntry* SkeletonAnimation::getCurrent (int trackIndex) {
if (_state) {
return _state->getCurrent(trackIndex);
}
return nullptr;
}
void SkeletonAnimation::clearTracks () {
if (_state) {
_state->clearTracks();
}
}
void SkeletonAnimation::clearTrack (int trackIndex) {
if (_state) {
_state->clearTrack(trackIndex);
}
}
void SkeletonAnimation::onAnimationStateEvent (TrackEntry* entry, EventType type, Event* event) {
switch (type) {
case EventType_Start:
if (_startListener) _startListener(entry);
break;
case EventType_Interrupt:
if (_interruptListener) _interruptListener(entry);
break;
case EventType_End:
if (_endListener) _endListener(entry);
break;
case EventType_Dispose:
if (_disposeListener) _disposeListener(entry);
break;
case EventType_Complete:
if (_completeListener) _completeListener(entry);
break;
case EventType_Event:
if (_eventListener) _eventListener(entry, event);
break;
}
}
void SkeletonAnimation::onTrackEntryEvent (TrackEntry* entry, EventType type, Event* event) {
if (!entry->getRendererObject()) return;
_TrackEntryListeners* listeners = (_TrackEntryListeners*)entry->getRendererObject();
switch (type) {
case EventType_Start:
if (listeners->startListener) listeners->startListener(entry);
break;
case EventType_Interrupt:
if (listeners->interruptListener) listeners->interruptListener(entry);
break;
case EventType_End:
if (listeners->endListener) listeners->endListener(entry);
break;
case EventType_Dispose:
if (listeners->disposeListener) listeners->disposeListener(entry);
break;
case EventType_Complete:
if (listeners->completeListener) listeners->completeListener(entry);
break;
case EventType_Event:
if (listeners->eventListener) listeners->eventListener(entry, event);
break;
}
}
void SkeletonAnimation::setStartListener (const StartListener& listener) {
_startListener = listener;
}
void SkeletonAnimation::setInterruptListener (const InterruptListener& listener) {
_interruptListener = listener;
}
void SkeletonAnimation::setEndListener (const EndListener& listener) {
_endListener = listener;
}
void SkeletonAnimation::setDisposeListener (const DisposeListener& listener) {
_disposeListener = listener;
}
void SkeletonAnimation::setCompleteListener (const CompleteListener& listener) {
_completeListener = listener;
}
void SkeletonAnimation::setEventListener (const EventListener& listener) {
_eventListener = listener;
}
void SkeletonAnimation::setTrackStartListener (TrackEntry* entry, const StartListener& listener) {
getListeners(entry)->startListener = listener;
}
void SkeletonAnimation::setTrackInterruptListener (TrackEntry* entry, const InterruptListener& listener) {
getListeners(entry)->interruptListener = listener;
}
void SkeletonAnimation::setTrackEndListener (TrackEntry* entry, const EndListener& listener) {
getListeners(entry)->endListener = listener;
}
void SkeletonAnimation::setTrackDisposeListener (TrackEntry* entry, const DisposeListener& listener) {
getListeners(entry)->disposeListener = listener;
}
void SkeletonAnimation::setTrackCompleteListener (TrackEntry* entry, const CompleteListener& listener) {
getListeners(entry)->completeListener = listener;
}
void SkeletonAnimation::setTrackEventListener (TrackEntry* entry, const EventListener& listener) {
getListeners(entry)->eventListener = listener;
}
AnimationState* SkeletonAnimation::getState() const {
return _state;
}
}
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated May 1, 2019. Replaces all prior versions.
*
* Copyright (c) 2013-2019, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS
* INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#include "spine-creator-support/SkeletonAnimation.h"
#include "spine-creator-support/spine-cocos2dx.h"
#include "spine/extension.h"
#include <algorithm>
USING_NS_CC;
using std::min;
using std::max;
using std::vector;
namespace spine {
typedef struct _TrackEntryListeners {
StartListener startListener;
InterruptListener interruptListener;
EndListener endListener;
DisposeListener disposeListener;
CompleteListener completeListener;
EventListener eventListener;
} _TrackEntryListeners;
void animationCallback (AnimationState* state, EventType type, TrackEntry* entry, Event* event) {
((SkeletonAnimation*)state->getRendererObject())->onAnimationStateEvent(entry, type, event);
}
void trackEntryCallback (AnimationState* state, EventType type, TrackEntry* entry, Event* event) {
((SkeletonAnimation*)state->getRendererObject())->onTrackEntryEvent(entry, type, event);
if (type == EventType_Dispose)
if (entry->getRendererObject()) delete (spine::_TrackEntryListeners*)entry->getRendererObject();
}
static _TrackEntryListeners* getListeners (TrackEntry* entry) {
if (!entry->getRendererObject()) {
entry->setRendererObject(new spine::_TrackEntryListeners());
entry->setListener(trackEntryCallback);
}
return (_TrackEntryListeners*)entry->getRendererObject();
}
static float globalTimeScale = 1.0f;
void SkeletonAnimation::setGlobalTimeScale(float timeScale) {
globalTimeScale = timeScale;
}
SkeletonAnimation* SkeletonAnimation::create() {
SkeletonAnimation* skeleton = new SkeletonAnimation();
skeleton->autorelease();
return skeleton;
}
SkeletonAnimation* SkeletonAnimation::createWithData (SkeletonData* skeletonData, bool ownsSkeletonData) {
SkeletonAnimation* node = new SkeletonAnimation();
node->initWithData(skeletonData, ownsSkeletonData);
node->autorelease();
return node;
}
SkeletonAnimation* SkeletonAnimation::createWithJsonFile (const std::string& skeletonJsonFile, Atlas* atlas, float scale) {
SkeletonAnimation* node = new SkeletonAnimation();
node->initWithJsonFile(skeletonJsonFile, atlas, scale);
node->autorelease();
return node;
}
SkeletonAnimation* SkeletonAnimation::createWithJsonFile (const std::string& skeletonJsonFile, const std::string& atlasFile, float scale) {
SkeletonAnimation* node = new SkeletonAnimation();
node->initWithJsonFile(skeletonJsonFile, atlasFile, scale);
node->autorelease();
return node;
}
SkeletonAnimation* SkeletonAnimation::createWithBinaryFile (const std::string& skeletonBinaryFile, Atlas* atlas, float scale) {
SkeletonAnimation* node = new SkeletonAnimation();
node->initWithBinaryFile(skeletonBinaryFile, atlas, scale);
node->autorelease();
return node;
}
SkeletonAnimation* SkeletonAnimation::createWithBinaryFile (const std::string& skeletonBinaryFile, const std::string& atlasFile, float scale) {
SkeletonAnimation* node = new SkeletonAnimation();
node->initWithBinaryFile(skeletonBinaryFile, atlasFile, scale);
node->autorelease();
return node;
}
void SkeletonAnimation::initialize () {
super::initialize();
_ownsAnimationStateData = true;
_state = new (__FILE__, __LINE__) AnimationState(new (__FILE__, __LINE__) AnimationStateData(_skeleton->getData()));
_state->setRendererObject(this);
_state->setListener(animationCallback);
}
SkeletonAnimation::SkeletonAnimation ()
: SkeletonRenderer() {
}
SkeletonAnimation::~SkeletonAnimation () {
_startListener = nullptr;
_interruptListener = nullptr;
_endListener = nullptr;
_disposeListener = nullptr;
_completeListener = nullptr;
_eventListener = nullptr;
if (_state) {
clearTracks();
if (_ownsAnimationStateData) delete _state->getData();
delete _state;
}
}
void SkeletonAnimation::update (float deltaTime) {
if (!_skeleton) return;
if (!_paused) {
deltaTime *= _timeScale * globalTimeScale;
if (_ownsSkeleton) _skeleton->update(deltaTime);
_state->update(deltaTime);
_state->apply(*_skeleton);
_skeleton->updateWorldTransform();
}
}
void SkeletonAnimation::setAnimationStateData (AnimationStateData* stateData) {
CCASSERT(stateData, "stateData cannot be null.");
if (_state) {
if (_ownsAnimationStateData) delete _state->getData();
delete _state;
}
_ownsAnimationStateData = false;
_state = new (__FILE__, __LINE__) AnimationState(stateData);
_state->setRendererObject(this);
_state->setListener(animationCallback);
}
void SkeletonAnimation::setMix (const std::string& fromAnimation, const std::string& toAnimation, float duration) {
if (_state) {
_state->getData()->setMix(fromAnimation.c_str(), toAnimation.c_str(), duration);
}
}
TrackEntry* SkeletonAnimation::setAnimation (int trackIndex, const std::string& name, bool loop) {
if (!_skeleton) return 0;
Animation* animation = _skeleton->getData()->findAnimation(name.c_str());
if (!animation) {
log("Spine: Animation not found: %s", name.c_str());
return 0;
}
auto trackEntry = _state->setAnimation(trackIndex, animation, loop);
_state->apply(*_skeleton);
return trackEntry;
}
TrackEntry* SkeletonAnimation::addAnimation (int trackIndex, const std::string& name, bool loop, float delay) {
if (!_skeleton) return 0;
Animation* animation = _skeleton->getData()->findAnimation(name.c_str());
if (!animation) {
log("Spine: Animation not found: %s", name.c_str());
return 0;
}
return _state->addAnimation(trackIndex, animation, loop, delay);
}
TrackEntry* SkeletonAnimation::setEmptyAnimation (int trackIndex, float mixDuration) {
if (_state) {
return _state->setEmptyAnimation(trackIndex, mixDuration);
}
return nullptr;
}
void SkeletonAnimation::setEmptyAnimations (float mixDuration) {
if (_state) {
_state->setEmptyAnimations(mixDuration);
}
}
TrackEntry* SkeletonAnimation::addEmptyAnimation (int trackIndex, float mixDuration, float delay) {
if (_state) {
return _state->addEmptyAnimation(trackIndex, mixDuration, delay);
}
return nullptr;
}
Animation* SkeletonAnimation::findAnimation(const std::string& name) const {
if (_skeleton) {
return _skeleton->getData()->findAnimation(name.c_str());
}
return nullptr;
}
TrackEntry* SkeletonAnimation::getCurrent (int trackIndex) {
if (_state) {
return _state->getCurrent(trackIndex);
}
return nullptr;
}
void SkeletonAnimation::clearTracks () {
if (_state) {
_state->clearTracks();
}
}
void SkeletonAnimation::clearTrack (int trackIndex) {
if (_state) {
_state->clearTrack(trackIndex);
}
}
void SkeletonAnimation::onAnimationStateEvent (TrackEntry* entry, EventType type, Event* event) {
switch (type) {
case EventType_Start:
if (_startListener) _startListener(entry);
break;
case EventType_Interrupt:
if (_interruptListener) _interruptListener(entry);
break;
case EventType_End:
if (_endListener) _endListener(entry);
break;
case EventType_Dispose:
if (_disposeListener) _disposeListener(entry);
break;
case EventType_Complete:
if (_completeListener) _completeListener(entry);
break;
case EventType_Event:
if (_eventListener) _eventListener(entry, event);
break;
}
}
void SkeletonAnimation::onTrackEntryEvent (TrackEntry* entry, EventType type, Event* event) {
if (!entry->getRendererObject()) return;
_TrackEntryListeners* listeners = (_TrackEntryListeners*)entry->getRendererObject();
switch (type) {
case EventType_Start:
if (listeners->startListener) listeners->startListener(entry);
break;
case EventType_Interrupt:
if (listeners->interruptListener) listeners->interruptListener(entry);
break;
case EventType_End:
if (listeners->endListener) listeners->endListener(entry);
break;
case EventType_Dispose:
if (listeners->disposeListener) listeners->disposeListener(entry);
break;
case EventType_Complete:
if (listeners->completeListener) listeners->completeListener(entry);
break;
case EventType_Event:
if (listeners->eventListener) listeners->eventListener(entry, event);
break;
}
}
void SkeletonAnimation::setStartListener (const StartListener& listener) {
_startListener = listener;
}
void SkeletonAnimation::setInterruptListener (const InterruptListener& listener) {
_interruptListener = listener;
}
void SkeletonAnimation::setEndListener (const EndListener& listener) {
_endListener = listener;
}
void SkeletonAnimation::setDisposeListener (const DisposeListener& listener) {
_disposeListener = listener;
}
void SkeletonAnimation::setCompleteListener (const CompleteListener& listener) {
_completeListener = listener;
}
void SkeletonAnimation::setEventListener (const EventListener& listener) {
_eventListener = listener;
}
void SkeletonAnimation::setTrackStartListener (TrackEntry* entry, const StartListener& listener) {
getListeners(entry)->startListener = listener;
}
void SkeletonAnimation::setTrackInterruptListener (TrackEntry* entry, const InterruptListener& listener) {
getListeners(entry)->interruptListener = listener;
}
void SkeletonAnimation::setTrackEndListener (TrackEntry* entry, const EndListener& listener) {
getListeners(entry)->endListener = listener;
}
void SkeletonAnimation::setTrackDisposeListener (TrackEntry* entry, const DisposeListener& listener) {
getListeners(entry)->disposeListener = listener;
}
void SkeletonAnimation::setTrackCompleteListener (TrackEntry* entry, const CompleteListener& listener) {
getListeners(entry)->completeListener = listener;
}
void SkeletonAnimation::setTrackEventListener (TrackEntry* entry, const EventListener& listener) {
getListeners(entry)->eventListener = listener;
}
AnimationState* SkeletonAnimation::getState() const {
return _state;
}
}
@@ -29,6 +29,7 @@
#include "SkeletonDataMgr.h"
#include <algorithm>
#include <vector>
using namespace spine;
@@ -61,6 +62,7 @@ public:
SkeletonData* data = nullptr;
Atlas* atlas = nullptr;
AttachmentLoader* attachmentLoader = nullptr;
std::vector<int> texturesIndex;
std::string _uuid;
};
@@ -71,7 +73,7 @@ bool SkeletonDataMgr::hasSkeletonData (const std::string& uuid) {
return it != _dataMap.end();
}
void SkeletonDataMgr::setSkeletonData (const std::string& uuid, SkeletonData* data, Atlas* atlas, AttachmentLoader* attachmentLoader) {
void SkeletonDataMgr::setSkeletonData (const std::string& uuid, SkeletonData* data, Atlas* atlas, AttachmentLoader* attachmentLoader, const std::vector<int>& texturesIndex) {
auto it = _dataMap.find(uuid);
if (it != _dataMap.end()) {
releaseByUUID(uuid);
@@ -80,13 +82,13 @@ void SkeletonDataMgr::setSkeletonData (const std::string& uuid, SkeletonData* da
info->data = data;
info->atlas = atlas;
info->attachmentLoader = attachmentLoader;
info->texturesIndex = texturesIndex;
_dataMap[uuid] = info;
}
SkeletonData* SkeletonDataMgr::retainByUUID (const std::string& uuid) {
auto dataIt = _dataMap.find(uuid);
if (dataIt == _dataMap.end())
{
if (dataIt == _dataMap.end()) {
return nullptr;
}
dataIt->second->retain();
@@ -102,6 +104,12 @@ void SkeletonDataMgr::releaseByUUID (const std::string& uuid) {
// If info reference count is 1, then info will be destroy.
if (info->getReferenceCount() == 1) {
_dataMap.erase(dataIt);
if (_destroyCallback) {
auto& texturesIndex = info->texturesIndex;
for (auto it = texturesIndex.begin(); it != texturesIndex.end(); it++) {
_destroyCallback(*it);
}
}
}
info->release();
}
@@ -59,11 +59,18 @@ public:
SkeletonDataMgr () {}
virtual ~SkeletonDataMgr () {}
bool hasSkeletonData (const std::string& uuid);
void setSkeletonData (const std::string& uuid, SkeletonData* data, Atlas* atlas, AttachmentLoader* attachmentLoader);
void setSkeletonData (const std::string& uuid, SkeletonData* data, Atlas* atlas, AttachmentLoader* attachmentLoader, const std::vector<int>& texturesIndex);
SkeletonData* retainByUUID (const std::string& uuid);
void releaseByUUID (const std::string& uuid);
typedef std::function<void(int)> destroyCallback;
void setDestroyCallback(destroyCallback callback)
{
_destroyCallback = callback;
}
private:
static SkeletonDataMgr* _instance;
destroyCallback _destroyCallback = nullptr;
};
}
@@ -31,12 +31,12 @@
#include "spine-creator-support/AttachmentVertices.h"
#include "spine-creator-support/spine-cocos2dx.h"
#include <algorithm>
#include "platform/CCApplication.h"
#include "base/CCScheduler.h"
#include "MiddlewareMacro.h"
#include "MeshBuffer.h"
#include "renderer/renderer/Pass.h"
#include "renderer/renderer/Technique.h"
#include "renderer/scene/assembler/CustomAssembler.hpp"
#include "SkeletonDataMgr.h"
#include "RenderInfoMgr.h"
USING_NS_CC;
USING_NS_MW;
@@ -44,6 +44,12 @@ USING_NS_MW;
using std::min;
using std::max;
using namespace spine;
using namespace cocos2d;
using namespace cocos2d::renderer;
static const std::string techStage = "opaque";
static const std::string textureKey = "texture";
static const uint8_t moduleID = MiddlewareManager::generateModuleID();
static Cocos2dTextureLoader textureLoader;
@@ -88,12 +94,7 @@ void SkeletonRenderer::initialize () {
if (_clipper == nullptr) {
_clipper = new (__FILE__, __LINE__) SkeletonClipping();
}
if (_renderInfoOffset == nullptr) {
// store global TypedArray begin and end offset
_renderInfoOffset = new IOTypedArray(se::Object::TypedArrayType::UINT32, sizeof(uint32_t));
}
_skeleton->setToSetupPose();
_skeleton->updateWorldTransform();
beginSchedule();
@@ -113,11 +114,6 @@ void SkeletonRenderer::onDisable() {
void SkeletonRenderer::stopSchedule() {
MiddlewareManager::getInstance()->removeTimer(this);
if (_renderInfoOffset) {
_renderInfoOffset->reset();
_renderInfoOffset->clear();
}
if (_debugBuffer) {
_debugBuffer->reset();
_debugBuffer->clear();
@@ -150,7 +146,6 @@ SkeletonRenderer::SkeletonRenderer (const std::string& skeletonDataFile, const s
SkeletonRenderer::~SkeletonRenderer () {
CC_SAFE_RELEASE(_effectDelegate);
if (_ownsSkeletonData) delete _skeleton->getData();
if (_ownsSkeleton) delete _skeleton;
if (_ownsAtlas && _atlas) delete _atlas;
@@ -158,16 +153,13 @@ SkeletonRenderer::~SkeletonRenderer () {
if (_uuid != "") SkeletonDataMgr::getInstance()->releaseByUUID(_uuid);
if (_clipper) delete _clipper;
if (_renderInfoOffset) {
delete _renderInfoOffset;
_renderInfoOffset = nullptr;
}
if (_debugBuffer) {
delete _debugBuffer;
_debugBuffer = nullptr;
}
CC_SAFE_RELEASE(_nodeProxy);
CC_SAFE_RELEASE(_effect);
stopSchedule();
}
@@ -264,67 +256,68 @@ void SkeletonRenderer::initWithBinaryFile (const std::string& skeletonDataFile,
initialize();
}
void SkeletonRenderer::update (float deltaTime) {
void SkeletonRenderer::render (float deltaTime) {
if (!_skeleton) return;
_renderInfoOffset->reset();
_renderInfoOffset->clear();
// avoid other place call update.
auto mgr = MiddlewareManager::getInstance();
if (!mgr->isUpdating) return;
if (!mgr->isRendering) return;
auto renderMgr = RenderInfoMgr::getInstance();
auto renderInfo = renderMgr->getBuffer();
if (!renderInfo) return;
// store renderInfo offset
_renderInfoOffset->writeUint32((uint32_t)renderInfo->getCurPos() / sizeof(uint32_t));
// check enough space
renderInfo->checkSpace(sizeof(uint32_t) * 2, true);
// write border
renderInfo->writeUint32(0xffffffff);
std::size_t materialLenOffset = renderInfo->getCurPos();
//reserved space to save material len
renderInfo->writeUint32(0);
// If opacity is 0,then return.
if (_skeleton->getColor().a == 0) {
if (_nodeProxy == nullptr) {
return;
}
CustomAssembler* assembler = (CustomAssembler*)_nodeProxy->getAssembler();
if (assembler == nullptr) {
return;
}
assembler->reset();
assembler->setUseModel(!_batch);
_nodeColor.a = _nodeProxy->getRealOpacity() / (float)255;
// If opacity is 0,then return.
if (_skeleton->getColor().a == 0) {
return;
}
Color4F color;
Color4F darkColor;
AttachmentVertices* attachmentVertices = nullptr;
bool inRange = _startSlotIndex != -1 || _endSlotIndex != -1 ? false : true;
auto vertexFormat = _useTint? VF_XYUVCC : VF_XYUVC;
MeshBuffer* mb = mgr->getMeshBuffer(vertexFormat);
middleware::MeshBuffer* mb = mgr->getMeshBuffer(vertexFormat);
middleware::IOBuffer& vb = mb->getVB();
middleware::IOBuffer& ib = mb->getIB();
// vertex size in floats with one color
int vs1 = sizeof(V2F_T2F_C4B) / sizeof(float);
// vertex size int bytes with one color
int vbs1 = sizeof(V2F_T2F_C4B);
// vertex size in floats with one color
int vs1 = vbs1 / sizeof(float);
// vertex size int bytes with two color
int vbs2 = sizeof(V2F_T2F_C4B_C4B);
// verex size in floats with two color
int vs2 = sizeof(V2F_T2F_C4B_C4B) / sizeof(float);
int vs2 = vbs2 / sizeof(float);
const cocos2d::Mat4& nodeWorldMat = _nodeProxy->getWorldMatrix();
int vbSize = 0;
int vbSize = 0;
int ibSize = 0;
int preTextureIndex = -1;
BlendFactor curBlendSrc = BlendFactor::ONE;
BlendFactor curBlendDst = BlendFactor::ZERO;
int curBlendMode = -1;
int preBlendMode = -1;
int curBlendSrc = -1;
int curBlendDst = -1;
int preTextureIndex = -1;
int curTextureIndex = -1;
int preISegWritePos = -1;
int preISegWritePos = -1;
int curISegLen = 0;
int materialLen = 0;
Slot* slot = nullptr;
int isFull = 0;
middleware::Texture2D* texture = nullptr;
if (_debugSlots || _debugBones || _debugMesh) {
// If enable debug draw,then init debug buffer.
if (_debugBuffer == nullptr) {
@@ -336,49 +329,77 @@ void SkeletonRenderer::update (float deltaTime) {
auto flush = [&]() {
// fill pre segment count field
if (preISegWritePos != -1) {
renderInfo->writeUint32(preISegWritePos, curISegLen);
assembler->updateIARange(materialLen - 1, preISegWritePos, curISegLen);
}
// prepare to fill new segment field
switch (slot->getData().getBlendMode()) {
curBlendMode = slot->getData().getBlendMode();
switch (curBlendMode) {
case BlendMode_Additive:
curBlendSrc = _premultipliedAlpha ? GL_ONE : GL_SRC_ALPHA;
curBlendDst = GL_ONE;
curBlendSrc = _premultipliedAlpha ? BlendFactor::ONE : BlendFactor::SRC_ALPHA;
curBlendDst = BlendFactor::ONE;
break;
case BlendMode_Multiply:
curBlendSrc = GL_DST_COLOR;
curBlendDst = GL_ONE_MINUS_SRC_ALPHA;
curBlendSrc = BlendFactor::DST_COLOR;
curBlendDst = BlendFactor::ONE_MINUS_SRC_ALPHA;
break;
case BlendMode_Screen:
curBlendSrc = GL_ONE;
curBlendDst = GL_ONE_MINUS_SRC_COLOR;
curBlendSrc = BlendFactor::ONE;
curBlendDst = BlendFactor::ONE_MINUS_SRC_COLOR;
break;
default:
curBlendSrc = _premultipliedAlpha ? GL_ONE : GL_SRC_ALPHA;
curBlendDst = GL_ONE_MINUS_SRC_ALPHA;
curBlendSrc = _premultipliedAlpha ? BlendFactor::ONE : BlendFactor::SRC_ALPHA;
curBlendDst = BlendFactor::ONE_MINUS_SRC_ALPHA;
}
// check enough space
renderInfo->checkSpace(sizeof(uint32_t) * 7, true);
double curHash = curTextureIndex + (moduleID << 16) + (curBlendMode << 24) + ((int)_useTint << 25) + ((int)_batch << 27);
Effect* renderEffect = assembler->getEffect(materialLen);
Technique::Parameter* param = nullptr;
Pass* pass = nullptr;
// fill new texture index
renderInfo->writeUint32(curTextureIndex);
// fill new blend src and dst
renderInfo->writeUint32(curBlendSrc);
renderInfo->writeUint32(curBlendDst);
// fill new index and vertex buffer id
auto glIB = mb->getGLIB();
auto glVB = mb->getGLVB();
renderInfo->writeUint32(glIB);
renderInfo->writeUint32(glVB);
// fill new index offset
renderInfo->writeUint32((uint32_t)ib.getCurPos() / sizeof(unsigned short));
if (renderEffect) {
double renderHash = renderEffect->getHash();
if (abs(renderHash - curHash) >= 0.01) {
param = (Technique::Parameter*)&(renderEffect->getProperty(textureKey));
Technique* tech = renderEffect->getTechnique(techStage);
cocos2d::Vector<Pass*>& passes = (cocos2d::Vector<Pass*>&)tech->getPasses();
pass = *(passes.begin());
}
}
else {
if (_effect == nullptr) {
cocos2d::log("SkeletonRenderer:update get effect failed");
assembler->reset();
return;
}
auto effect = new cocos2d::renderer::Effect();
effect->autorelease();
effect->copy(_effect);
Technique* tech = effect->getTechnique(techStage);
cocos2d::Vector<Pass*>& passes = (cocos2d::Vector<Pass*>&)tech->getPasses();
pass = *(passes.begin());
assembler->updateEffect(materialLen, effect);
renderEffect = effect;
param = (Technique::Parameter*)&(renderEffect->getProperty(textureKey));
}
if (param) {
param->setTexture(texture->getNativeTexture());
}
if (pass) {
pass->setBlend(BlendOp::ADD, curBlendSrc, curBlendDst,
BlendOp::ADD, curBlendSrc, curBlendDst);
}
renderEffect->updateHash(curHash);
// save new segment count pos field
preISegWritePos = (int)renderInfo->getCurPos();
// reserve indice segamentation count
renderInfo->writeUint32(0);
preISegWritePos = (int)ib.getCurPos() / sizeof(unsigned short);
// save new segment vb and ib
assembler->updateIABuffer(materialLen, mb->getGLVB(), mb->getGLIB());
// reset pre blend mode to current
preBlendMode = (int)slot->getData().getBlendMode();
// reset pre texture index to current
@@ -426,10 +447,6 @@ void SkeletonRenderer::update (float deltaTime) {
continue;
}
if (!slot->getAttachment()) {
continue;
}
Triangles triangles;
TwoColorTriangles trianglesTwoColor;
@@ -794,6 +811,7 @@ void SkeletonRenderer::update (float deltaTime) {
}
}
texture = attachmentVertices->_texture;
curTextureIndex = attachmentVertices->_texture->getRealTextureIndex();
// If texture or blendMode change,will change material.
if (preTextureIndex != curTextureIndex || preBlendMode != slot->getData().getBlendMode() || isFull) {
@@ -801,9 +819,25 @@ void SkeletonRenderer::update (float deltaTime) {
}
if (vbSize > 0 && ibSize > 0) {
auto vertexOffset = vb.getCurPos() / sizeof(middleware::V2F_T2F_C4B);
auto vbs = vbs1;
auto vertexOffset = vb.getCurPos() / vbs1;
if (_useTint) {
vertexOffset = vb.getCurPos() / sizeof(middleware::V2F_T2F_C4B_C4B);
vbs = vbs2;
vertexOffset = vb.getCurPos() / vbs2;
}
if (_batch) {
uint8_t* vbBuffer = vb.getCurBuffer();
cocos2d::Vec3* point = nullptr;
float tempZ = 0.0f;
for (int ii = 0, nn = vbSize; ii < nn; ii += vbs)
{
point = (cocos2d::Vec3*)(vbBuffer + ii);
tempZ = point->z;
point->z = 0;
nodeWorldMat.transformPoint(point);
point->z = tempZ;
}
}
if (vertexOffset > 0) {
@@ -827,11 +861,10 @@ void SkeletonRenderer::update (float deltaTime) {
if (effect) effect->end();
renderInfo->writeUint32(materialLenOffset, materialLen);
if (preISegWritePos != -1) {
renderInfo->writeUint32(preISegWritePos, curISegLen);
if (preISegWritePos != -1) {
assembler->updateIARange(materialLen - 1, preISegWritePos, curISegLen);
}
if (_debugBones) {
auto& bones = _skeleton->getBones();
size_t bonesCount = bones.size();
@@ -1005,6 +1038,10 @@ void SkeletonRenderer::setColor (cocos2d::Color4B& color) {
_nodeColor.a = color.a / 255.0f;
}
void SkeletonRenderer::setBatchEnabled (bool enabled) {
_batch = enabled;
}
void SkeletonRenderer::setDebugBonesEnabled (bool enabled) {
_debugBones = enabled;
}
@@ -1,181 +1,192 @@
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated May 1, 2019. Replaces all prior versions.
*
* Copyright (c) 2013-2019, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS
* INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#pragma once
#include "spine/spine.h"
#include "base/CCRef.h"
#include "base/ccTypes.h"
#include <vector>
#include "scripting/js-bindings/jswrapper/Object.hpp"
#include "IOTypedArray.h"
#include "MiddlewareManager.h"
#include "spine-creator-support/VertexEffectDelegate.h"
namespace spine {
class AttachmentVertices;
/** Draws a skeleton.
*/
class SkeletonRenderer: public cocos2d::middleware::IMiddleware, public cocos2d::Ref {
public:
static SkeletonRenderer* create ();
static SkeletonRenderer* createWithSkeleton(Skeleton* skeleton, bool ownsSkeleton = false, bool ownsSkeletonData = false);
static SkeletonRenderer* createWithData (SkeletonData* skeletonData, bool ownsSkeletonData = false);
static SkeletonRenderer* createWithFile (const std::string& skeletonDataFile, Atlas* atlas, float scale = 1);
static SkeletonRenderer* createWithFile (const std::string& skeletonDataFile, const std::string& atlasFile, float scale = 1);
virtual void update (float deltaTime);
virtual cocos2d::Rect getBoundingBox () const;
Skeleton* getSkeleton() const;
void setTimeScale (float scale);
float getTimeScale () const;
void updateWorldTransform ();
void setToSetupPose ();
void setBonesToSetupPose ();
void setSlotsToSetupPose ();
void paused (bool value);
/* Returns 0 if the bone was not found. */
Bone* findBone (const std::string& boneName) const;
/* Returns 0 if the slot was not found. */
Slot* findSlot (const std::string& slotName) const;
/* Sets the skin used to look up attachments not found in the SkeletonData defaultSkin. Attachments from the new skin are
* attached if the corresponding attachment from the old skin was attached.
* @param skin May be empty string ("") for no skin.*/
void setSkin (const std::string& skinName);
/** @param skin May be 0 for no skin.*/
void setSkin (const char* skinName);
/* Returns 0 if the slot or attachment was not found. */
Attachment* getAttachment (const std::string& slotName, const std::string& attachmentName) const;
/* Returns false if the slot or attachment was not found.
* @param attachmentName May be empty string ("") for no attachment. */
bool setAttachment (const std::string& slotName, const std::string& attachmentName);
/* @param attachmentName May be 0 for no attachment. */
bool setAttachment (const std::string& slotName, const char* attachmentName);
/* Enables/disables two color tinting for this instance. May break batching */
void setUseTint(bool enabled);
/* Sets the vertex effect to be used, set to 0 to disable vertex effects */
void setVertexEffectDelegate(VertexEffectDelegate* effectDelegate);
/* Sets the range of slots that should be rendered. Use -1, -1 to clear the range */
void setSlotsRange(int startSlotIndex, int endSlotIndex);
/**
* @return debug data,it's a Float32Array,
* format |debug bones length|[beginX|beginY|toX|toY|...loop...]
*/
se_object_ptr getDebugData() const {
if (_debugBuffer) {
return _debugBuffer->getTypeArray();
}
return nullptr;
}
/**
* @return render info offset,it's a Uint32Array,
* format |render info offset|
*/
se_object_ptr getRenderInfoOffset() const {
if (_renderInfoOffset) {
return _renderInfoOffset->getTypeArray();
}
return nullptr;
}
void setColor (cocos2d::Color4B& color);
void setDebugBonesEnabled (bool enabled);
void setDebugSlotsEnabled (bool enabled);
void setDebugMeshEnabled (bool enabled);
void setOpacityModifyRGB (bool value);
bool isOpacityModifyRGB () const;
void beginSchedule();
void stopSchedule();
void onEnable();
void onDisable();
CC_CONSTRUCTOR_ACCESS:
SkeletonRenderer ();
SkeletonRenderer(Skeleton* skeleton, bool ownsSkeleton = false, bool ownsSkeletonData = false, bool ownsAtlas = false);
SkeletonRenderer (SkeletonData* skeletonData, bool ownsSkeletonData = false);
SkeletonRenderer (const std::string& skeletonDataFile, Atlas* atlas, float scale = 1);
SkeletonRenderer (const std::string& skeletonDataFile, const std::string& atlasFile, float scale = 1);
virtual ~SkeletonRenderer ();
void initWithUUID(const std::string& uuid);
void initWithSkeleton(Skeleton* skeleton, bool ownsSkeleton = false, bool ownsSkeletonData = false, bool ownsAtlas = false);
void initWithData (SkeletonData* skeletonData, bool ownsSkeletonData = false);
void initWithJsonFile (const std::string& skeletonDataFile, Atlas* atlas, float scale = 1);
void initWithJsonFile (const std::string& skeletonDataFile, const std::string& atlasFile, float scale = 1);
void initWithBinaryFile (const std::string& skeletonDataFile, Atlas* atlas, float scale = 1);
void initWithBinaryFile (const std::string& skeletonDataFile, const std::string& atlasFile, float scale = 1);
virtual void initialize ();
protected:
void setSkeletonData (SkeletonData* skeletonData, bool ownsSkeletonData);
bool _ownsSkeletonData = false;
bool _ownsSkeleton = false;
bool _ownsAtlas = false;
Atlas* _atlas = nullptr;
AttachmentLoader* _attachmentLoader = nullptr;
Skeleton* _skeleton = nullptr;
VertexEffectDelegate* _effectDelegate = nullptr;
float _timeScale = 1;
bool _paused = false;
bool _debugMesh = false;
bool _debugSlots = false;
bool _debugBones = false;
cocos2d::Color4F _nodeColor = cocos2d::Color4F::WHITE;
bool _premultipliedAlpha = false;
SkeletonClipping* _clipper = nullptr;
bool _useTint = false;
std::string _uuid = "";
int _startSlotIndex = -1;
int _endSlotIndex = -1;
cocos2d::middleware::IOTypedArray* _renderInfoOffset = nullptr;
cocos2d::middleware::IOTypedArray* _debugBuffer = nullptr;
};
}
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated May 1, 2019. Replaces all prior versions.
*
* Copyright (c) 2013-2019, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS
* INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#pragma once
#include "spine/spine.h"
#include "base/CCRef.h"
#include "base/ccTypes.h"
#include <vector>
#include "scripting/js-bindings/jswrapper/Object.hpp"
#include "IOTypedArray.h"
#include "MiddlewareManager.h"
#include "spine-creator-support/VertexEffectDelegate.h"
#include "renderer/scene/NodeProxy.hpp"
#include "base/CCMap.h"
#include "middleware-adapter.h"
#include "base/ccMacros.h"
namespace spine {
class AttachmentVertices;
/** Draws a skeleton.
*/
class SkeletonRenderer: public cocos2d::middleware::IMiddleware, public cocos2d::Ref {
public:
static SkeletonRenderer* create ();
static SkeletonRenderer* createWithSkeleton(Skeleton* skeleton, bool ownsSkeleton = false, bool ownsSkeletonData = false);
static SkeletonRenderer* createWithData (SkeletonData* skeletonData, bool ownsSkeletonData = false);
static SkeletonRenderer* createWithFile (const std::string& skeletonDataFile, Atlas* atlas, float scale = 1);
static SkeletonRenderer* createWithFile (const std::string& skeletonDataFile, const std::string& atlasFile, float scale = 1);
virtual void update (float deltaTime) override {}
virtual void render (float deltaTime) override;
virtual cocos2d::Rect getBoundingBox () const;
Skeleton* getSkeleton() const;
void setTimeScale (float scale);
float getTimeScale () const;
void updateWorldTransform ();
void setToSetupPose ();
void setBonesToSetupPose ();
void setSlotsToSetupPose ();
void paused (bool value);
/* Returns 0 if the bone was not found. */
Bone* findBone (const std::string& boneName) const;
/* Returns 0 if the slot was not found. */
Slot* findSlot (const std::string& slotName) const;
/* Sets the skin used to look up attachments not found in the SkeletonData defaultSkin. Attachments from the new skin are
* attached if the corresponding attachment from the old skin was attached.
* @param skin May be empty string ("") for no skin.*/
void setSkin (const std::string& skinName);
/** @param skin May be 0 for no skin.*/
void setSkin (const char* skinName);
/* Returns 0 if the slot or attachment was not found. */
Attachment* getAttachment (const std::string& slotName, const std::string& attachmentName) const;
/* Returns false if the slot or attachment was not found.
* @param attachmentName May be empty string ("") for no attachment. */
bool setAttachment (const std::string& slotName, const std::string& attachmentName);
/* @param attachmentName May be 0 for no attachment. */
bool setAttachment (const std::string& slotName, const char* attachmentName);
/* Enables/disables two color tinting for this instance. May break batching */
void setUseTint(bool enabled);
/* Sets the vertex effect to be used, set to 0 to disable vertex effects */
void setVertexEffectDelegate(VertexEffectDelegate* effectDelegate);
/* Sets the range of slots that should be rendered. Use -1, -1 to clear the range */
void setSlotsRange(int startSlotIndex, int endSlotIndex);
/**
* @return debug data,it's a Float32Array,
* format |debug bones length|[beginX|beginY|toX|toY|...loop...]
*/
se_object_ptr getDebugData() const {
if (_debugBuffer) {
return _debugBuffer->getTypeArray();
}
return nullptr;
}
void bindNodeProxy(cocos2d::renderer::NodeProxy* node) {
if (node == _nodeProxy) return;
CC_SAFE_RELEASE(_nodeProxy);
_nodeProxy = node;
CC_SAFE_RETAIN(_nodeProxy);
}
void setEffect(cocos2d::renderer::Effect* effect) {
if (effect == _effect) return;
CC_SAFE_RELEASE(_effect);
_effect = effect;
CC_SAFE_RETAIN(_effect);
}
void setColor (cocos2d::Color4B& color);
void setBatchEnabled (bool enabled);
void setDebugBonesEnabled (bool enabled);
void setDebugSlotsEnabled (bool enabled);
void setDebugMeshEnabled (bool enabled);
void setOpacityModifyRGB (bool value);
bool isOpacityModifyRGB () const;
void beginSchedule();
void stopSchedule();
void onEnable();
void onDisable();
CC_CONSTRUCTOR_ACCESS:
SkeletonRenderer ();
SkeletonRenderer(Skeleton* skeleton, bool ownsSkeleton = false, bool ownsSkeletonData = false, bool ownsAtlas = false);
SkeletonRenderer (SkeletonData* skeletonData, bool ownsSkeletonData = false);
SkeletonRenderer (const std::string& skeletonDataFile, Atlas* atlas, float scale = 1);
SkeletonRenderer (const std::string& skeletonDataFile, const std::string& atlasFile, float scale = 1);
virtual ~SkeletonRenderer ();
void initWithUUID(const std::string& uuid);
void initWithSkeleton(Skeleton* skeleton, bool ownsSkeleton = false, bool ownsSkeletonData = false, bool ownsAtlas = false);
void initWithData (SkeletonData* skeletonData, bool ownsSkeletonData = false);
void initWithJsonFile (const std::string& skeletonDataFile, Atlas* atlas, float scale = 1);
void initWithJsonFile (const std::string& skeletonDataFile, const std::string& atlasFile, float scale = 1);
void initWithBinaryFile (const std::string& skeletonDataFile, Atlas* atlas, float scale = 1);
void initWithBinaryFile (const std::string& skeletonDataFile, const std::string& atlasFile, float scale = 1);
virtual void initialize ();
protected:
void setSkeletonData (SkeletonData* skeletonData, bool ownsSkeletonData);
bool _ownsSkeletonData = false;
bool _ownsSkeleton = false;
bool _ownsAtlas = false;
Atlas* _atlas = nullptr;
AttachmentLoader* _attachmentLoader = nullptr;
Skeleton* _skeleton = nullptr;
VertexEffectDelegate* _effectDelegate = nullptr;
float _timeScale = 1;
bool _paused = false;
bool _batch = false;
bool _debugMesh = false;
bool _debugSlots = false;
bool _debugBones = false;
cocos2d::Color4F _nodeColor = cocos2d::Color4F::WHITE;
bool _premultipliedAlpha = false;
SkeletonClipping* _clipper = nullptr;
bool _useTint = false;
std::string _uuid = "";
int _startSlotIndex = -1;
int _endSlotIndex = -1;
cocos2d::middleware::IOTypedArray* _debugBuffer = nullptr;
cocos2d::renderer::NodeProxy* _nodeProxy = nullptr;
cocos2d::renderer::Effect* _effect = nullptr;
};
}
@@ -32,6 +32,7 @@
#include "spine/spine.h"
#include "spine-creator-support/SkeletonRenderer.h"
#include "spine-creator-support/SkeletonAnimation.h"
#include "spine-creator-support/SkeletonDataMgr.h"
#include "middleware-adapter.h"
namespace spine {
@@ -1,118 +0,0 @@
/******************************************************************************
* Spine Runtimes Software License v2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#ifndef Spine_Extension_h
#define Spine_Extension_h
#include <stdlib.h>
#include <spine/dll.h>
#define SP_UNUSED(x) (void)(x)
namespace spine {
class String;
class SP_API SpineExtension {
public:
template<typename T>
static T *alloc(size_t num, const char *file, int line) {
return (T *) getInstance()->_alloc(sizeof(T) * num, file, line);
}
template<typename T>
static T *calloc(size_t num, const char *file, int line) {
return (T *) getInstance()->_calloc(sizeof(T) * num, file, line);
}
template<typename T>
static T *realloc(T *ptr, size_t num, const char *file, int line) {
return (T *) getInstance()->_realloc(ptr, sizeof(T) * num, file, line);
}
template<typename T>
static void free(T *ptr, const char *file, int line) {
getInstance()->_free((void *) ptr, file, line);
}
static char *readFile(const String &path, int *length) {
return getInstance()->_readFile(path, length);
}
static void setInstance(SpineExtension *inSpineExtension);
static SpineExtension *getInstance();
virtual ~SpineExtension();
/// Implement this function to use your own memory allocator
virtual void *_alloc(size_t size, const char *file, int line) = 0;
virtual void *_calloc(size_t size, const char *file, int line) = 0;
virtual void *_realloc(void *ptr, size_t size, const char *file, int line) = 0;
/// If you provide a spineAllocFunc, you should also provide a spineFreeFunc
virtual void _free(void *mem, const char *file, int line) = 0;
virtual char *_readFile(const String &path, int *length) = 0;
protected:
SpineExtension();
private:
static SpineExtension *_instance;
};
class SP_API DefaultSpineExtension : public SpineExtension {
public:
DefaultSpineExtension();
virtual ~DefaultSpineExtension();
protected:
virtual void *_alloc(size_t size, const char *file, int line);
virtual void *_calloc(size_t size, const char *file, int line);
virtual void *_realloc(void *ptr, size_t size, const char *file, int line);
virtual void _free(void *mem, const char *file, int line);
virtual char *_readFile(const String &path, int *length);
};
// This function is to be implemented by engine specific runtimes to provide
// the default extension for that engine. It is called the first time
// SpineExtension::getInstance() is called, when no instance has been set
// yet.
extern SpineExtension *getDefaultExtension();
}
#endif /* Spine_Extension_h */
+1
View File
@@ -31,5 +31,6 @@
#include "math/Vec4.h"
#include "math/Mat4.h"
#include "math/Quaternion.h"
#include "math/Mat3.hpp"
#endif
+375
View File
@@ -0,0 +1,375 @@
/****************************************************************************
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "math/Mat3.hpp"
#include <cmath>
#include "math/Quaternion.h"
#include "math/MathUtil.h"
#include "base/ccMacros.h"
NS_CC_MATH_BEGIN
Mat3::Mat3()
{
*this = IDENTITY;
}
Mat3::Mat3(float m11, float m12, float m13, float m21, float m22, float m23,
float m31, float m32, float m33)
{
set(m11, m12, m13, m21, m22, m23, m31, m32, m33);
}
Mat3::Mat3(const float* mat)
{
set(mat);
}
Mat3::Mat3(const Mat3& copy)
{
memcpy(m, copy.m, MATRIX3_SIZE);
}
Mat3::~Mat3()
{
}
void Mat3::set(float m11, float m12, float m13, float m21, float m22, float m23, float m31, float m32, float m33)
{
m[0] = m11;
m[1] = m21;
m[2] = m31;
m[3] = m12;
m[4] = m22;
m[5] = m32;
m[6] = m13;
m[7] = m23;
m[8] = m33;
}
void Mat3::set(const float* mat)
{
GP_ASSERT(mat);
memcpy(this->m, mat, MATRIX3_SIZE);
}
void Mat3::set(const Mat3& mat)
{
memcpy(this->m, mat.m, MATRIX3_SIZE);
}
void Mat3::identity(Mat3& mat)
{
mat.m[0] = 1;
mat.m[1] = 0;
mat.m[2] = 0;
mat.m[3] = 0;
mat.m[4] = 1;
mat.m[5] = 0;
mat.m[6] = 0;
mat.m[7] = 0;
mat.m[8] = 1;
}
void Mat3::transpose()
{
float a01 = m[1], a02 = m[2], a12 = m[5];
m[1] = m[3];
m[2] = m[6];
m[3] = a01;
m[5] = m[7];
m[6] = a02;
m[7] = a12;
}
void Mat3::transpose(Mat3 &out, const Mat3 &mat)
{
out.m[0] = mat.m[0];
out.m[1] = mat.m[3];
out.m[2] = mat.m[6];
out.m[3] = mat.m[1];
out.m[4] = mat.m[4];
out.m[5] = mat.m[7];
out.m[6] = mat.m[2];
out.m[7] = mat.m[5];
out.m[8] = mat.m[8];
}
void Mat3::inverse()
{
float a00 = m[0], a01 = m[1], a02 = m[2];
float a10 = m[3], a11 = m[4], a12 = m[5];
float a20 = m[6], a21 = m[7], a22 = m[8];
float b01 = a22 * a11 - a12 * a21;
float b11 = -a22 * a10 + a12 * a20;
float b21 = a21 * a10 - a11 * a20;
// Calculate the determinant
float det = a00 * b01 + a01 * b11 + a02 * b21;
det = 1.0 / det;
m[0] = b01 * det;
m[1] = (-a22 * a01 + a02 * a21) * det;
m[2] = (a12 * a01 - a02 * a11) * det;
m[3] = b11 * det;
m[4] = (a22 * a00 - a02 * a20) * det;
m[5] = (-a12 * a00 + a02 * a10) * det;
m[6] = b21 * det;
m[7] = (-a21 * a00 + a01 * a20) * det;
m[8] = (a11 * a00 - a01 * a10) * det;
}
void Mat3::adjoint(Mat3 &out, const Mat3 &mat)
{
float a00 = mat.m[0], a01 = mat.m[1], a02 = mat.m[2];
float a10 = mat.m[3], a11 = mat.m[4], a12 = mat.m[5];
float a20 = mat.m[6], a21 = mat.m[7], a22 = mat.m[8];
out.m[0] = (a11 * a22 - a12 * a21);
out.m[1] = (a02 * a21 - a01 * a22);
out.m[2] = (a01 * a12 - a02 * a11);
out.m[3] = (a12 * a20 - a10 * a22);
out.m[4] = (a00 * a22 - a02 * a20);
out.m[5] = (a02 * a10 - a00 * a12);
out.m[6] = (a10 * a21 - a11 * a20);
out.m[7] = (a01 * a20 - a00 * a21);
out.m[8] = (a00 * a11 - a01 * a10);
}
float Mat3::determinant()
{
return m[0] * (m[8] * m[4] - m[5] * m[7]) + m[1] * (-m[8] * m[3] + m[5] * m[6]) + m[2] * (m[7] * m[3] - m[4] * m[6]);
}
void Mat3::multiply(Mat3 &out, const Mat3 &a, const Mat3 &b)
{
float a00 = a.m[0], a01 = a.m[1], a02 = a.m[2];
float a10 = a.m[3], a11 = a.m[4], a12 = a.m[5];
float a20 = a.m[6], a21 = a.m[7], a22 = a.m[8];
float b00 = b.m[0], b01 = b.m[1], b02 = b.m[2];
float b10 = b.m[3], b11 = b.m[4], b12 = b.m[5];
float b20 = b.m[6], b21 = b.m[7], b22 = b.m[8];
out.m[0] = b00 * a00 + b01 * a10 + b02 * a20;
out.m[1] = b00 * a01 + b01 * a11 + b02 * a21;
out.m[2] = b00 * a02 + b01 * a12 + b02 * a22;
out.m[3] = b10 * a00 + b11 * a10 + b12 * a20;
out.m[4] = b10 * a01 + b11 * a11 + b12 * a21;
out.m[5] = b10 * a02 + b11 * a12 + b12 * a22;
out.m[6] = b20 * a00 + b21 * a10 + b22 * a20;
out.m[7] = b20 * a01 + b21 * a11 + b22 * a21;
out.m[8] = b20 * a02 + b21 * a12 + b22 * a22;
}
void Mat3::translate(Mat3 &out, const Mat3 &mat, const Vec2 &vec)
{
float a00 = mat.m[0], a01 = mat.m[1], a02 = mat.m[2];
float a10 = mat.m[3], a11 = mat.m[4], a12 = mat.m[5];
float a20 = mat.m[6], a21 = mat.m[7], a22 = mat.m[8];
float x = vec.x, y = vec.y;
out.m[0] = a00;
out.m[1] = a01;
out.m[2] = a02;
out.m[3] = a10;
out.m[4] = a11;
out.m[5] = a12;
out.m[6] = x * a00 + y * a10 + a20;
out.m[7] = x * a01 + y * a11 + a21;
out.m[8] = x * a02 + y * a12 + a22;
}
void Mat3::rotate(Mat3 &out, const Mat3 &mat, float rad)
{
float a00 = mat.m[0], a01 = mat.m[1], a02 = mat.m[2];
float a10 = mat.m[3], a11 = mat.m[4], a12 = mat.m[5];
float a20 = mat.m[6], a21 = mat.m[7], a22 = mat.m[8];
float s = sin(rad);
float c = cos(rad);
out.m[0] = c * a00 + s * a10;
out.m[1] = c * a01 + s * a11;
out.m[2] = c * a02 + s * a12;
out.m[3] = c * a10 - s * a00;
out.m[4] = c * a11 - s * a01;
out.m[5] = c * a12 - s * a02;
out.m[6] = a20;
out.m[7] = a21;
out.m[8] = a22;
}
void Mat3::scale(Mat3 &out, const Mat3 &mat, const Vec2 &vec)
{
float x = vec.x, y = vec.y;
out.m[0] = x * mat.m[0];
out.m[1] = x * mat.m[1];
out.m[2] = x * mat.m[2];
out.m[3] = y * mat.m[3];
out.m[4] = y * mat.m[4];
out.m[5] = y * mat.m[5];
out.m[6] = mat.m[6];
out.m[7] = mat.m[7];
out.m[8] = mat.m[8];
}
void Mat3::fromMat4(Mat3 &out, const Mat4 &mat)
{
out.m[0] = mat.m[0];
out.m[1] = mat.m[1];
out.m[2] = mat.m[2];
out.m[3] = mat.m[4];
out.m[4] = mat.m[5];
out.m[5] = mat.m[6];
out.m[6] = mat.m[8];
out.m[7] = mat.m[9];
out.m[8] = mat.m[10];
}
void Mat3::fromTranslation(Mat3 &out, const Vec2 &vec)
{
out.m[0] = 1;
out.m[1] = 0;
out.m[2] = 0;
out.m[3] = 0;
out.m[4] = 1;
out.m[5] = 0;
out.m[6] = vec.x;
out.m[7] = vec.y;
out.m[8] = 1;
}
void Mat3::fromRotation(Mat3 &out, float rad)
{
float s = sin(rad);
float c = cos(rad);
out.m[0] = c;
out.m[1] = s;
out.m[2] = 0;
out.m[3] = -s;
out.m[4] = c;
out.m[5] = 0;
out.m[6] = 0;
out.m[7] = 0;
out.m[8] = 1;
}
void Mat3::fromScaling(Mat3 &out, const Vec2 &vec)
{
out.m[0] = vec.x;
out.m[1] = 0;
out.m[2] = 0;
out.m[3] = 0;
out.m[4] = vec.y;
out.m[5] = 0;
out.m[6] = 0;
out.m[7] = 0;
out.m[8] = 1;
}
void Mat3::fromQuat(Mat3 &out, const Quaternion &quat)
{
float x = quat.x, y = quat.y, z = quat.z, w = quat.w;
float x2 = x + x;
float y2 = y + y;
float z2 = z + z;
float xx = x * x2;
float yx = y * x2;
float yy = y * y2;
float zx = z * x2;
float zy = z * y2;
float zz = z * z2;
float wx = w * x2;
float wy = w * y2;
float wz = w * z2;
out.m[0] = 1 - yy - zz;
out.m[3] = yx - wz;
out.m[6] = zx + wy;
out.m[1] = yx + wz;
out.m[4] = 1 - xx - zz;
out.m[7] = zy - wx;
out.m[2] = zx - wy;
out.m[5] = zy + wx;
out.m[8] = 1 - xx - yy;
}
void Mat3::add(Mat3 &out, const Mat3 &a, const Mat3 &b)
{
out.m[0] = a.m[0] + b.m[0];
out.m[1] = a.m[1] + b.m[1];
out.m[2] = a.m[2] + b.m[2];
out.m[3] = a.m[3] + b.m[3];
out.m[4] = a.m[4] + b.m[4];
out.m[5] = a.m[5] + b.m[5];
out.m[6] = a.m[6] + b.m[6];
out.m[7] = a.m[7] + b.m[7];
out.m[8] = a.m[8] + b.m[8];
}
void Mat3::subtract(Mat3 &out, const Mat3 &a, const Mat3 &b)
{
out.m[0] = a.m[0] - b.m[0];
out.m[1] = a.m[1] - b.m[1];
out.m[2] = a.m[2] - b.m[2];
out.m[3] = a.m[3] - b.m[3];
out.m[4] = a.m[4] - b.m[4];
out.m[5] = a.m[5] - b.m[5];
out.m[6] = a.m[6] - b.m[6];
out.m[7] = a.m[7] - b.m[7];
out.m[8] = a.m[8] - b.m[8];
}
const Mat3 Mat3::IDENTITY = Mat3(
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f);
const Mat3 Mat3::ZERO = Mat3(
0, 0, 0,
0, 0, 0,
0, 0, 0);
NS_CC_MATH_END
+232
View File
@@ -0,0 +1,232 @@
/****************************************************************************
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef MATH_MAT3_H
#define MATH_MAT3_H
#define MATRIX3_SIZE ( sizeof(float) * 9)
#include "base/ccMacros.h"
#include "math/Vec2.h"
#include "math/Vec3.h"
#include "math/Vec4.h"
#include "math/Mat4.h"
/**
* @addtogroup base
* @{
*/
NS_CC_MATH_BEGIN
class CC_DLL Mat3
{
public:
/**
* Stores the columns of this 3x3 matrix.
* */
float m[9];
/**
* Default constructor.
* Constructs a matrix initialized to the identity matrix:
*
* 1 0 0
* 0 1 0
* 0 0 1
*/
Mat3();
/**
* Constructs a matrix initialized to the specified value.
*
* @param m11 The first element of the first row.
* @param m12 The second element of the first row.
* @param m13 The third element of the first row.
* @param m21 The first element of the second row.
* @param m22 The second element of the second row.
* @param m23 The third element of the second row.
* @param m31 The first element of the third row.
* @param m32 The second element of the third row.
* @param m33 The third element of the third row.
*/
Mat3(float m11, float m12, float m13, float m21, float m22, float m23, float m31, float m32, float m33);
/**
* Creates a matrix initialized to the specified column-major array.
*
* The passed-in array is in column-major order, so the memory layout of the array is as follows:
*
* 0 3 6
* 1 4 7
* 2 5 8
*
* @param mat An array containing 16 elements in column-major order.
*/
Mat3(const float* mat);
/**
* Constructs a new matrix by copying the values from the specified matrix.
*
* @param copy The matrix to copy.
*/
Mat3(const Mat3& copy);
/**
* Destructor.
*/
~Mat3();
/**
* Sets the values of this matrix.
*
* @param m11 The first element of the first row.
* @param m12 The second element of the first row.
* @param m13 The third element of the first row.
* @param m21 The first element of the second row.
* @param m22 The second element of the second row.
* @param m23 The third element of the second row.
* @param m31 The first element of the third row.
* @param m32 The second element of the third row.
* @param m33 The third element of the third row.
*/
void set(float m11, float m12, float m13, float m21, float m22, float m23,
float m31, float m32, float m33);
/**
* Sets the values of this matrix to those in the specified column-major array.
*
* @param mat An array containing 9 elements in column-major format.
*/
void set(const float* mat);
/**
* Sets the values of this matrix to those of the specified matrix.
*
* @param mat The source matrix.
*/
void set(const Mat3& mat);
/**
* return an identity matrix.
*/
static void identity(Mat3& mat);
/**
* Transposes matrix.
*/
void transpose();
/**
* Transposes a matrix.
*/
static void transpose(Mat3& out, const Mat3& mat);
/**
* Inverts a matrix.
*/
void inverse();
/**
* Calculates the adjugate of a matrix.
*/
static void adjoint(Mat3& out, const Mat3& mat);
/**
* Calculates the determinant of a matrix.
*/
float determinant();
/**
* Multiply two matrices explicitly.
*/
static void multiply(Mat3& out, const Mat3& a, const Mat3& b);
/**
* Multiply a matrix with a translation matrix given by a translation offset.
*/
static void translate(Mat3& out, const Mat3& mat, const Vec2& vec);
/**
* Rotates a matrix by the given angle.
*/
static void rotate(Mat3& out, const Mat3& mat, float rad);
/**
* Multiply a matrix with a scale matrix given by a scale vector.
*/
static void scale(Mat3& out, const Mat3& mat, const Vec2& vec);
/**
* Copies the upper-left 3x3 values of a 4x4 matrix into a 3x3 matrix.
*/
static void fromMat4(Mat3& out, const Mat4& mat);
/**
* Creates a matrix from a translation offset.
*/
static void fromTranslation(Mat3& out, const Vec2& vec);
/**
* Creates a matrix from a given angle.
*/
static void fromRotation(Mat3& out, float rad);
/**
* Creates a matrix from a scale vector.
*/
static void fromScaling(Mat3& out, const Vec2& vec);
/**
* Calculates a 3x3 matrix from the given quaternion.
*/
static void fromQuat(Mat3& out, const Quaternion& quat);
/**
* Adds two matrices.
*/
static void add(Mat3& out, const Mat3& a, const Mat3& b);
/**
* Subtracts matrix b from matrix a.
*/
static void subtract(Mat3& out, const Mat3& a, const Mat3& b);
/** equals to a matrix full of zeros */
static const Mat3 ZERO;
/** equals to the identity matrix */
static const Mat3 IDENTITY;
};
NS_CC_MATH_END
/**
end of base group
@}
*/
#endif
+40
View File
@@ -21,8 +21,10 @@
*/
#include "math/Vec3.h"
#include "math/Mat3.hpp"
#include "math/MathUtil.h"
#include "base/ccMacros.h"
#include "math/Quaternion.h"
NS_CC_MATH_BEGIN
@@ -153,6 +155,44 @@ void Vec3::cross(const Vec3& v1, const Vec3& v2, Vec3* dst)
MathUtil::crossVec3(&v1.x, &v2.x, &dst->x);
}
void Vec3::multiply(const Vec3& v)
{
x *= v.x;
y *= v.y;
z *= v.z;
}
void Vec3::multiply(const Vec3& v1, const Vec3& v2, Vec3* dst)
{
dst->x = v1.x * v2.x;
dst->y = v1.y * v2.y;
dst->z = v1.z * v2.z;
}
void Vec3::transformMat3(const Vec3& v, const Mat3 &m)
{
float ix = v.x, iy = v.y, iz = v.z;
x = ix * m.m[0] + iy * m.m[3] + iz * m.m[6];
y = ix * m.m[1] + iy * m.m[4] + iz * m.m[7];
z = ix * m.m[2] + iy * m.m[5] + iz * m.m[8];
}
void Vec3::transformQuat(const Quaternion& q)
{
float qx = q.x, qy = q.y, qz = q.z, qw = q.w;
// calculate quat * vec
float ix = qw * x + qy * z - qz * y;
float iy = qw * y + qz * x - qx * z;
float iz = qw * z + qx * y - qy * x;
float iw = -qx * x - qy * y - qz * z;
// calculate result * inverse quat
x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
}
float Vec3::distance(const Vec3& v) const
{
float dx = v.x - x;
+31
View File
@@ -35,6 +35,7 @@ NS_CC_MATH_BEGIN
class Mat4;
class Quaternion;
class Mat3;
/**
* Defines a 3-element floating point vector.
@@ -199,6 +200,36 @@ public:
* @param dst A vector to store the result in.
*/
static void cross(const Vec3& v1, const Vec3& v2, Vec3* dst);
/**
* Multiply the elements of the specified vector to this one.
*
* @param v The vector to multiply.
*/
void multiply(const Vec3& v);
/**
* Multiply the specified vectors and stores the result in dst.
*
* @param v1 The first vector.
* @param v2 The second vector.
* @param dst A vector to store the result in.
*/
static void multiply(const Vec3& v1, const Vec3& v2, Vec3* dst);
/**
* Transforms this vector by the specified Mat3 and stores the result in this vector.
*
* @param v The Vec3 to transform.
* @param m The matrix.
*/
void transformMat3(const Vec3& v, const Mat3& m);
/**
* Transforms this vector by the specified quaternion and stores the result in this vector.
*
* @param q The quaternion to multiply.
*/
void transformQuat(const Quaternion& q);
/**
* Returns the distance between this vector and v.
+16 -17
View File
@@ -284,14 +284,14 @@ void DeviceGraphics::setBlendColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
void DeviceGraphics::setBlendFunc(BlendFactor src, BlendFactor dst)
{
_nextState.blendSepartion = false;
_nextState.blendSeparation = false;
_nextState.blendSrc = src;
_nextState.blendDst = dst;
}
void DeviceGraphics::setBlendFuncSeparate(BlendFactor srcRGB, BlendFactor dstRGB, BlendFactor srcAlpha, BlendFactor dstAlpha)
{
_nextState.blendSepartion = true;
_nextState.blendSeparation = true;
_nextState.blendSrc = srcRGB;
_nextState.blendDst = dstRGB;
_nextState.blendSrcAlpha = srcAlpha;
@@ -300,13 +300,13 @@ void DeviceGraphics::setBlendFuncSeparate(BlendFactor srcRGB, BlendFactor dstRGB
void DeviceGraphics::setBlendEquation(BlendOp mode)
{
_nextState.blendSepartion = false;
_nextState.blendSeparation = false;
_nextState.blendEq = mode;
}
void DeviceGraphics::setBlendEquationSeparate(BlendOp modeRGB, BlendOp modeAlpha)
{
_nextState.blendSepartion = true;
_nextState.blendSeparation = true;
_nextState.blendEq = modeRGB;
_nextState.blendAlphaEq = modeAlpha;
}
@@ -431,6 +431,7 @@ void DeviceGraphics::draw(size_t base, GLsizei count)
GL_CHECK(glDrawArrays(ENUM_CLASS_TO_GLENUM(_nextState.primitiveType), (GLint)base, count));
}
_drawCalls++;
_currentState = std::move(_nextState);
}
@@ -680,7 +681,7 @@ void DeviceGraphics::commitBlendStates()
}
if (_nextState.blendSepartion)
if (_nextState.blendSeparation)
{
GL_CHECK(glBlendFuncSeparate(ENUM_CLASS_TO_GLENUM(_nextState.blendSrc),
ENUM_CLASS_TO_GLENUM(_nextState.blendDst),
@@ -708,9 +709,9 @@ void DeviceGraphics::commitBlendStates()
(_nextState.blendColor >> 8 & 0xff) / 255.f,
(_nextState.blendColor & 0xff) / 255.f);
if (_currentState.blendSepartion != _nextState.blendSepartion)
if (_currentState.blendSeparation != _nextState.blendSeparation)
{
if (_nextState.blendSepartion)
if (_nextState.blendSeparation)
{
GL_CHECK(glBlendFuncSeparate(ENUM_CLASS_TO_GLENUM(_nextState.blendSrc),
ENUM_CLASS_TO_GLENUM(_nextState.blendDst),
@@ -729,7 +730,7 @@ void DeviceGraphics::commitBlendStates()
return;
}
if (_nextState.blendSepartion)
if (_nextState.blendSeparation)
{
if (_currentState.blendSrc != _nextState.blendSrc ||
_currentState.blendDst != _nextState.blendDst ||
@@ -1031,8 +1032,8 @@ void DeviceGraphics::commitVertexBuffer()
for (int j = 0; j < usedAttriLen; ++j)
{
const auto& attr = attributes[j];
const auto& el = vb->getFormat().getElement(attr.name);
if (!el.isValid())
const auto* el = vb->getFormat().getElement(attr.name);
if (!el || !el->isValid())
{
RENDERER_LOGW("Can not find vertex attribute: %s", attr.name.c_str());
continue;
@@ -1047,11 +1048,11 @@ void DeviceGraphics::commitVertexBuffer()
// glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
GL_CHECK(ccVertexAttribPointer(attr.location,
el.num,
ENUM_CLASS_TO_GLENUM(el.type),
el.normalize,
el.stride,
(GLvoid*)(el.offset + vboffset * el.stride)));
el->num,
ENUM_CLASS_TO_GLENUM(el->type),
el->normalize,
el->stride,
(GLvoid*)(el->offset + vboffset * el->stride)));
}
}
@@ -1093,13 +1094,11 @@ void DeviceGraphics::commitTextures()
//
DeviceGraphics::Uniform::Uniform()
: dirty(true)
, value(nullptr)
, elementType(UniformElementType::FLOAT)
{}
DeviceGraphics::Uniform::Uniform(const void* v, size_t bytes, UniformElementType elementType_)
: dirty(true)
, value(nullptr)
, elementType(elementType_)
{
setValue(v, bytes);
+241 -71
View File
@@ -38,7 +38,6 @@
#include "../Types.h"
#include "State.h"
RENDERER_BEGIN
class FrameBuffer;
@@ -47,6 +46,15 @@ class IndexBuffer;
class Program;
class Texture;
/**
* @addtogroup gfx
* @{
*/
/**
* DeviceGraphics is a direct abstraction for OpenGL APIs.
* This fundamental class takes responsibility for all GL states management and GL call invocations.
*/
class DeviceGraphics final : public Ref
{
public:
@@ -60,84 +68,18 @@ public:
int maxColorAttatchments;
};
static DeviceGraphics* getInstance();
inline const Capacity& getCapacity() const { return _caps; }
bool supportGLExtension(const std::string& extension) const;
void setFrameBuffer(const FrameBuffer* fb);
void setViewport(int x, int y, int w, int h);
void setScissor(int x, int y, int w, int h);
void clear(uint8_t flags, Color4F *color, double depth, int32_t stencil);
void enableBlend();
void enableDepthTest();
void enableDepthWrite();
void enableStencilTest();
void setStencilFunc(StencilFunc func, int ref, unsigned int mask);
void setStencilFuncFront(StencilFunc func, int ref, unsigned int mask);
void setStencilFuncBack(StencilFunc func, int ref, unsigned int mask);
void setStencilOp(StencilOp failOp, StencilOp zFailOp, StencilOp zPassOp, unsigned int writeMask);
void setStencilOpFront(StencilOp failOp, StencilOp zFailOp, StencilOp zPassOp, unsigned int writeMask);
void setStencilOpBack(StencilOp failOp, StencilOp zFailOp, StencilOp zPassOp, unsigned int writeMask);
void setDepthFunc(DepthFunc func);
void setBlendColor(uint32_t rgba);
void setBlendColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a);
void setBlendFunc(BlendFactor src, BlendFactor dst);
void setBlendFuncSeparate(BlendFactor srcRGB, BlendFactor dstRGB, BlendFactor srcAlpha, BlendFactor dstAlpha);
void setBlendEquation(BlendOp mode);
void setBlendEquationSeparate(BlendOp modeRGB, BlendOp modeAlpha);
void setCullMode(CullMode mode);
void setVertexBuffer(int stream, VertexBuffer* buffer, int start = 0);
void setIndexBuffer(IndexBuffer *buffer);
void setProgram(Program *program);
void setTexture(const std::string& name, Texture* texture, int slot);
void setTextureArray(const std::string& name, const std::vector<Texture*>& textures, const std::vector<int>& slots);
void setUniformi(const std::string& name, int i1);
void setUniformi(const std::string& name, int i1, int i2);
void setUniformi(const std::string& name, int i1, int i2, int i3);
void setUniformi(const std::string& name, int i1, int i2, int i3, int i4);
void setUniformiv(const std::string& name, size_t count, const int* value);
void setUniformf(const std::string& name, float f1);
void setUniformf(const std::string& name, float f1, float f2);
void setUniformf(const std::string& name, float f1, float f2, float f3);
void setUniformf(const std::string& name, float f1, float f2, float f3, float f4);
void setUniformfv(const std::string& name, size_t count, const float* value);
void setUniformVec2(const std::string& name, const cocos2d::Vec2& value);
void setUniformVec3(const std::string& name, const cocos2d::Vec3& value);
void setUniformVec4(const std::string& name, const cocos2d::Vec4& value);
void setUniformMat2(const std::string& name, float* value);
void setUniformMat3(const std::string& name, float* value);
void setUniformMat4(const std::string& name, float* value);
void setUniformMat4(const std::string& name, const cocos2d::Mat4& value);
void setUniform(const std::string& name, const void* v, size_t bytes, UniformElementType elementType);
void setPrimitiveType(PrimitiveType type);
void draw(size_t base, GLsizei count);
private:
struct Uniform
{
Uniform(const void* v, size_t bytes, UniformElementType elementType_);
Uniform(Uniform&& h);
Uniform();
~Uniform();
Uniform& operator=(Uniform&& h);
void setValue(const void* v, size_t bytes);
void* value;
void* value = nullptr;
bool dirty;
UniformElementType elementType;
private:
@@ -145,6 +87,229 @@ private:
Uniform& operator=(const Uniform& o);
};
/**
* Returns a shared instance of the director.
*/
static DeviceGraphics* getInstance();
/**
* Checks whether a gl extension is supported
*/
bool supportGLExtension(const std::string& extension) const;
/**
* Sets the target FrameBuffer
*/
void setFrameBuffer(const FrameBuffer* fb);
/**
* Sets viewport with x, y, width and height
*/
void setViewport(int x, int y, int w, int h);
/**
* Sets scissor clipping area
*/
void setScissor(int x, int y, int w, int h);
/**
* Clear with flags, including color, depth and stencil,
* you should also specify the color, depth and stencil value to use.
*/
void clear(uint8_t flags, Color4F *color, double depth, int32_t stencil);
/**
* Enables blend in GL state
*/
void enableBlend();
/**
* Enables depth test in GL state
*/
void enableDepthTest();
/**
* Enables depth write in GL state
*/
void enableDepthWrite();
/**
* Enables stencil test in GL state
*/
void enableStencilTest();
/**
* Sets both the front and back function and reference value for stencil testing
*/
void setStencilFunc(StencilFunc func, int ref, unsigned int mask);
/**
* Sets the front function and reference value for stencil testing
*/
void setStencilFuncFront(StencilFunc func, int ref, unsigned int mask);
/**
* Sets the back function and reference value for stencil testing
*/
void setStencilFuncBack(StencilFunc func, int ref, unsigned int mask);
/**
* Sets both the front and back-facing stencil test actions
*/
void setStencilOp(StencilOp failOp, StencilOp zFailOp, StencilOp zPassOp, unsigned int writeMask);
/**
* Sets the front stencil test actions
*/
void setStencilOpFront(StencilOp failOp, StencilOp zFailOp, StencilOp zPassOp, unsigned int writeMask);
/**
* Sets the back stencil test actions
*/
void setStencilOpBack(StencilOp failOp, StencilOp zFailOp, StencilOp zPassOp, unsigned int writeMask);
/**
* Specifies the depth comparison function, which sets the conditions under which the pixel will be drawn.
*/
void setDepthFunc(DepthFunc func);
/**
* Sets the source and destination blending factors with all channel packed into a 32bit unsigned int
*/
void setBlendColor(uint32_t rgba);
/**
* Sets the source and destination blending factors with separate color channel values
*/
void setBlendColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a);
/**
* Sets which function is used for blending pixel arithmetic
*/
void setBlendFunc(BlendFactor src, BlendFactor dst);
/**
* Sets which function is used for blending pixel arithmetic for RGB and alpha components separately
*/
void setBlendFuncSeparate(BlendFactor srcRGB, BlendFactor dstRGB, BlendFactor srcAlpha, BlendFactor dstAlpha);
/**
* Sets both the RGB blend equation and alpha blend equation to a single equation.
*/
void setBlendEquation(BlendOp mode);
/**
* Sets the RGB blend equation and alpha blend equation separately.
*/
void setBlendEquationSeparate(BlendOp modeRGB, BlendOp modeAlpha);
/**
* Specifies whether or not front and/or back-facing polygons can be culled.
*/
void setCullMode(CullMode mode);
/**
* Sets the vertex buffer
*/
void setVertexBuffer(int stream, VertexBuffer* buffer, int start = 0);
/**
* Sets the index buffer
*/
void setIndexBuffer(IndexBuffer *buffer);
/**
* Sets a linked program
*/
void setProgram(Program *program);
/**
* Sets a texture into a GL texture slot then set to the specified uniform
*/
void setTexture(const std::string& name, Texture* texture, int slot);
/**
* Sets textures array into GL texture slots then set to the specified uniform
*/
void setTextureArray(const std::string& name, const std::vector<Texture*>& textures, const std::vector<int>& slots);
/**
* Sets a integer to the specified uniform
*/
void setUniformi(const std::string& name, int i1);
/**
* Sets two integers to the specified uniform
*/
void setUniformi(const std::string& name, int i1, int i2);
/**
* Sets three integers to the specified uniform
*/
void setUniformi(const std::string& name, int i1, int i2, int i3);
/**
* Sets four integers to the specified uniform
*/
void setUniformi(const std::string& name, int i1, int i2, int i3, int i4);
/**
* Sets a vector of integers to the specified uniform
*/
void setUniformiv(const std::string& name, size_t count, const int* value);
/**
* Sets a float to the specified uniform
*/
void setUniformf(const std::string& name, float f1);
/**
* Sets two floats to the specified uniform
*/
void setUniformf(const std::string& name, float f1, float f2);
/**
* Sets three floats to the specified uniform
*/
void setUniformf(const std::string& name, float f1, float f2, float f3);
/**
* Sets four floats to the specified uniform
*/
void setUniformf(const std::string& name, float f1, float f2, float f3, float f4);
/**
* Sets a vector of floats to the specified uniform
*/
void setUniformfv(const std::string& name, size_t count, const float* value);
/**
* Sets a Vec2 to the specified uniform
*/
void setUniformVec2(const std::string& name, const cocos2d::Vec2& value);
/**
* Sets a Vec3 to the specified uniform
*/
void setUniformVec3(const std::string& name, const cocos2d::Vec3& value);
/**
* Sets a Vec4 to the specified uniform
*/
void setUniformVec4(const std::string& name, const cocos2d::Vec4& value);
/**
* Sets a 2x2 matrix to the specified uniform
*/
void setUniformMat2(const std::string& name, float* value);
/**
* Sets a 3x3 matrix to the specified uniform
*/
void setUniformMat3(const std::string& name, float* value);
/**
* Sets a 4x4 matrix specified by float pointer to the given uniform
*/
void setUniformMat4(const std::string& name, float* value);
/**
* Sets a Mat4 object to the given uniform
*/
void setUniformMat4(const std::string& name, const cocos2d::Mat4& value);
/**
* Sets data specified by data pointer, type and bytes to the given uniform
*/
void setUniform(const std::string& name, const void* v, size_t bytes, UniformElementType elementType);
/**
* Sets the primitive type for draw calls
*/
void setPrimitiveType(PrimitiveType type);
/**
* Draw elements using the current gl states
*/
void draw(size_t base, GLsizei count);
/**
* Resets the draw call counter to 0
*/
void resetDrawCalls() { _drawCalls = 0; };
/**
* Gets current draw call counts
*/
uint32_t getDrawCalls() const { return _drawCalls; };
inline const Capacity& getCapacity() const { return _caps; }
private:
DeviceGraphics();
~DeviceGraphics();
CC_DISALLOW_COPY_ASSIGN_AND_MOVE(DeviceGraphics);
@@ -170,6 +335,8 @@ private:
int _sy;
int _sw;
int _sh;
uint32_t _drawCalls = 0;
int _defaultFbo;
@@ -188,4 +355,7 @@ private:
friend class Texture2D;
};
// end of gfx group
/// @}
RENDERER_END
+59 -2
View File
@@ -22,10 +22,8 @@
THE SOFTWARE.
****************************************************************************/
#pragma once
#include <vector>
#include "../Macro.h"
#include "../Types.h"
@@ -36,24 +34,80 @@ RENDERER_BEGIN
class DeviceGraphics;
class RenderTarget;
/**
* @addtogroup gfx
* @{
*/
/**
* The FrameBuffer class can store the render results of DeviceGraphics.
* It contains color buffers, depth buffers and stencil buffers,
* they are destinations for drawing, clearing and writing operations during the render process.
*/
class FrameBuffer final : public GraphicsHandle
{
public:
/**
* Create a FrameBuffer object with device and size
*/
RENDERER_DEFINE_CREATE_METHOD_3(FrameBuffer, init, DeviceGraphics*, uint16_t, uint16_t)
FrameBuffer();
/**
* Inits the frame buffer with device and size
*/
bool init(DeviceGraphics* device, uint16_t width, uint16_t height);
/**
* Destroys the GL buffers created by this frame buffer object
*/
void destroy();
/**
* Sets the color buffers as drawing and clearing destinations
*/
void setColorBuffers(const std::vector<RenderTarget*>& renderTargets);
/**
* Sets a color buffer at specific index
*/
void setColorBuffer(RenderTarget* rt, int index);
/**
* Sets the depth buffer as depth writing destination
*/
void setDepthBuffer(RenderTarget* rt);
/**
* Sets the stencil buffer as stencil writing destination
*/
void setStencilBuffer(RenderTarget* rt);
/**
* Sets the depth and stencil buffer at the same time.
* If you want to set both with the same RenderTarget, you should use this instead of setting them separatly.
*/
void setDepthStencilBuffer(RenderTarget* rt);
/**
* Sets the width of frame buffer
*/
inline int getWidth() const { return _width; }
/**
* Sets the width of frame buffer
*/
inline int getHeight() const { return _height; }
/**
* Gets the color buffers
*/
const std::vector<RenderTarget*>& getColorBuffers() const;
/**
* Gets the depth buffer
*/
const RenderTarget* getDepthBuffer() const;
/**
* Gets the stencil buffer
*/
const RenderTarget* getStencilBuffer() const;
/**
* Gets the depth and stencil buffer if they share the same one.
*/
const RenderTarget* getDepthStencilBuffer() const;
private:
@@ -68,4 +122,7 @@ private:
uint16_t _height;
};
// end of gfx group
/// @}
RENDERER_END
+3 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+3 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+3 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+3 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+3 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+18 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -31,15 +31,30 @@
RENDERER_BEGIN
/**
* @addtogroup gfx
* @{
*/
/**
* Abstract class for GL graphic classes that uses a GL handle id.
* Such as Texture, FrameBuffer, IndexBuffer, VertexBuffer, Program.
*/
class GraphicsHandle : public Ref
{
public:
GraphicsHandle();
virtual ~GraphicsHandle();
/**
* Gets the GL handle
*/
inline GLuint getHandle() const { return _glID; }
protected:
GLuint _glID;
};
// end of gfx group
/// @}
RENDERER_END
+3 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+74 -4
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -21,6 +21,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include <functional>
@@ -30,32 +31,95 @@
RENDERER_BEGIN
/**
* @addtogroup gfx
* @{
*/
class DeviceGraphics;
/**
* IndexBuffer manages the GL buffer for element indices.
* It creates, updates and destoies the GL buffer.
*/
class IndexBuffer final : public GraphicsHandle
{
public:
/**
* Creates an IndexBuffer object
* @param[in] device DeviceGraphics pointer.
* @param[in] format Index element format.
* @param[in] usage The usage pattern of the index buffer.
* @param[in] data Data pointer, could be nullptr, then nothing is updated to the buffer.
* @param[in] dataByteLength Data's byte length.
* @param[in] numIndices Count of indices.
*/
RENDERER_DEFINE_CREATE_METHOD_6(IndexBuffer, init, DeviceGraphics*, IndexFormat, Usage, const void*, size_t, uint32_t)
IndexBuffer();
virtual ~IndexBuffer();
/**
* Initializes the index buffer with necessary options.
* @param[in] device DeviceGraphics pointer.
* @param[in] format Index element format.
* @param[in] usage The usage pattern of the index buffer.
* @param[in] data Data pointer, could be nullptr, then nothing is updated to the buffer.
* @param[in] dataByteLength Data's byte length.
* @param[in] numIndices Count of indices.
*/
bool init(DeviceGraphics* device, IndexFormat format, Usage usage, const void* data, size_t dataByteLength, uint32_t numIndices);
/**
* Update data to the GL index buffer
* @param[in] offset Destination offset for filling buffer data.
* @param[in] data Data to be updated.
* @param[in] dataByteLength Data byte length to be updated.
*/
void update(uint32_t offset, const void* data, size_t dataByteLength);
/**
* Gets the count of indices.
*/
inline uint32_t getCount() const { return _numIndices; }
/**
* Sets the count of indices.
*/
inline void setCount(uint32_t numIndices) { _numIndices = numIndices; }
/**
* Gets the format of indices.
*/
inline IndexFormat getFormat() const { return _format; }
/**
* Sets the format of indices.
*/
inline void setFormat(IndexFormat format) { _format = format; }
/**
* Gets bytes occupied by each index.
*/
inline uint32_t getBytesPerIndex() const { return _bytesPerIndex; }
/**
* Sets bytes occupied by each index.
*/
inline void setBytesPerIndex(uint32_t bytesPerIndex) {_bytesPerIndex = bytesPerIndex; }
/**
* Gets usage pattern of the index buffer
*/
inline Usage getUsage() const { return _usage; }
/**
* Sets usage pattern of the index buffer
*/
inline void setUsage(Usage usage) { _usage = usage; }
/**
* Gets byte size of the index buffer
*/
inline uint32_t getBytes() const { return _bytes; }
/**
* Sets byte size of the index buffer
*/
inline void setBytes(uint32_t bytes) { _bytes = bytes; }
using FetchDataCallback = std::function<uint8_t*(size_t*)>;
@@ -68,7 +132,10 @@ public:
}
return _fetchDataCallback(bytes);
}
/**
* Destroies the index buffer
*/
void destroy();
private:
@@ -84,4 +151,7 @@ private:
CC_DISALLOW_COPY_ASSIGN_AND_MOVE(IndexBuffer)
};
// end of gfx group
/// @}
RENDERER_END
+3 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+76 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -34,41 +34,111 @@
RENDERER_BEGIN
/**
* @addtogroup gfx
* @{
*/
class DeviceGraphics;
/**
* Program class manages the internal GL shader program.
*/
class Program final: public GraphicsHandle
{
public:
/**
* Describes vertex attribute informations used in the program
* @struct Attribute
*/
struct Attribute
{
/**
* Attribute name
*/
std::string name;
/**
* Number of components per attribute
*/
GLsizei size;
/**
* Attribute location
*/
GLuint location;
/**
* Attribute type
*/
GLenum type;
};
/**
* Describes uniform informations used in the program
* @struct Uniform
*/
struct Uniform
{
/**
* Uniform name
*/
std::string name;
/**
* The length of the array for uniforms declared as arrays, default value is 1
*/
GLsizei size;
/**
* Uniform location
*/
GLint location;
/**
* Uniform type
*/
GLenum type;
/**
* Sets the uniform value
*/
void setUniform(const void* value, UniformElementType elementType) const;
/**
* Sets the callback which will be called when uniform updated
*/
using SetUniformCallback = void (*)(GLint, GLsizei, const void*, UniformElementType); // location, count, value, elementType
private:
SetUniformCallback _callback;
friend class Program;
};
/**
* Creates a Program with device and shader sources
*/
RENDERER_DEFINE_CREATE_METHOD_3(Program, init, DeviceGraphics*, const char*, const char*)
Program();
virtual ~Program();
/**
* Initializes a Program with device and program sources
* @param[in] device DeviceGraphics pointer
* @param[in] vertSource Vertex shader program
* @param[in] fragSource Fragment shader program
*/
bool init(DeviceGraphics* device, const char* vertSource, const char* fragSource);
/**
* Gets the id of program
*/
inline uint32_t getID() const { return _id; }
/**
* Gets the attibutes used in the program
*/
inline const std::vector<Attribute>& getAttributes() const { return _attributes; }
/**
* Gets the uniforms used in the program
*/
inline const std::vector<Uniform>& getUniforms() const { return _uniforms; }
/**
* Indicates whether the program is successfully linked
*/
inline bool isLinked() const { return _linked; }
/**
* Link the program with its shader sources
*/
void link();
private:
DeviceGraphics* _device;
@@ -80,4 +150,7 @@ private:
bool _linked;
};
// end of gfx group
/// @}
RENDERER_END
+3 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+24 -4
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -31,12 +31,23 @@
RENDERER_BEGIN
/**
* @addtogroup gfx
* @{
*/
class DeviceGraphics;
/**
* RenderBuffer manages the GL render buffer.
* A render buffer stores data such as an image, or can be source or target of a rendering operation.
*/
class RenderBuffer final : public RenderTarget
{
public:
// render-buffer format
/**
* RenderBuffer's pixel format
*/
enum class Format : uint32_t
{
RGBA4 = GL_RGBA4,
@@ -46,11 +57,17 @@ public:
// D24S8 = GL_DEPTH_STENCIL
};
/**
* Creates a RenderBuffer with device, pixel format and size
*/
RENDERER_DEFINE_CREATE_METHOD_4(RenderBuffer, init, DeviceGraphics*, Format, uint16_t, uint16_t)
RenderBuffer();
virtual ~RenderBuffer();
/**
* Initializes a RenderBuffer with device, pixel format and size
*/
bool init(DeviceGraphics* device, Format format, uint16_t width, uint16_t height);
private:
@@ -60,4 +77,7 @@ private:
uint16_t _height;
};
// end of gfx group
/// @}
RENDERER_END
+3 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+14 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -33,10 +33,21 @@
RENDERER_BEGIN
/**
* @addtogroup gfx
* @{
*/
/**
* Abstract class for all classes that could act as a render target
*/
class RenderTarget : public GraphicsHandle
{
public:
virtual ~RenderTarget() {}
};
// end of gfx group
/// @}
RENDERER_END
+4 -4
View File
@@ -38,7 +38,7 @@ namespace {
State::State()
// blend
: blend(false)
, blendSepartion(false)
, blendSeparation(false)
, blendColor(0xFFFFFFFF)
, blendEq(BlendOp::ADD)
, blendAlphaEq(BlendOp::ADD)
@@ -115,7 +115,7 @@ State& State::operator=(const State& o)
{
// blend
blend = o.blend;
blendSepartion = o.blendSepartion;
blendSeparation = o.blendSeparation;
blendColor = o.blendColor;
blendEq = o.blendEq;
blendAlphaEq = o.blendAlphaEq;
@@ -218,7 +218,7 @@ State& State::operator=(State&& o)
{
// blend
blend = o.blend;
blendSepartion = o.blendSepartion;
blendSeparation = o.blendSeparation;
blendColor = o.blendColor;
blendEq = o.blendEq;
blendAlphaEq = o.blendAlphaEq;
@@ -280,7 +280,7 @@ State& State::operator=(State&& o)
// reset o
o.blend = false;
o.blendSepartion = false;
o.blendSeparation = false;
o.blendColor = 0xFFFFFFFF;
o.blendEq = BlendOp::ADD;
o.blendAlphaEq = BlendOp::ADD;
+174 -8
View File
@@ -36,8 +36,22 @@ class IndexBuffer;
class Program;
class Texture;
/**
* @addtogroup gfx
* @{
*/
/**
* State class save the GL states used in one draw call.
* It will be used to compare between the previous states and the current states, so that we know which GL states should be updated.
* User shouldn't be using this Class directly. Instead, they should set the states in Pass of material system.
* @see `Pass`
*/
struct State final
{
{
/**
* Constructor
*/
State();
State(const State&);
State(State &&);
@@ -46,65 +60,214 @@ struct State final
State& operator =(const State& rhs);
State& operator =(State&& rhs);
/**
* Reset all states to default values
*/
void reset();
// blend
/**
@name Blend
@{
*/
/**
* Indicates blending enabled or not
*/
bool blend;
bool blendSepartion;
/**
* Indicates the RGB blend equation and alpha blend equation settings are separate or not
*/
bool blendSeparation;
/**
* The blending color
*/
uint32_t blendColor;
/**
* The blending equation
*/
BlendOp blendEq;
/**
* The blending equation for alpha channel
*/
BlendOp blendAlphaEq;
/**
* The blending source factor
*/
BlendFactor blendSrc;
/**
* The blending destination factor
*/
BlendFactor blendDst;
/**
* The blending source factor for alpha
*/
BlendFactor blendSrcAlpha;
/**
* The blending destination factor for alpha
*/
BlendFactor blendDstAlpha;
/**
end of Blend
@}
*/
// depth
/**
@name Depth
@{
*/
/**
* Indicates depth test enabled or not
*/
bool depthTest;
/**
* Indicates depth writing enabled or not
*/
bool depthWrite;
/**
* The depth comparison function
*/
DepthFunc depthFunc;
/**
end of Depth
@}
*/
// stencil
/**
@name Stencil
@{
*/
/**
* Indicates stencil test enabled or not
*/
bool stencilTest;
/**
* Indicates stencil test function for front and back is set separatly or not
*/
bool stencilSeparation;
/**
* The front face function for stencil test
*/
StencilFunc stencilFuncFront;
/**
* The front reference value for stencil test
*/
int32_t stencilRefFront;
/**
* The front mask value to AND with the reference value and store the result into stencil buffer when test is done
*/
uint32_t stencilMaskFront;
/**
* The function to use when the stencil test fails for front face
*/
StencilOp stencilFailOpFront;
/**
* The function to use when the stencil test passes but the depth test fails for front face
*/
StencilOp stencilZFailOpFront;
/**
* The function to use when both the stencil and the depth test pass for front face.
* Or when the stencil test passes and there is no depth buffer or depth testing is disabled.
*/
StencilOp stencilZPassOpFront;
/**
* The bit mask to enable or disable writing of individual bits in the front stencil planes
*/
uint32_t stencilWriteMaskFront;
/**
* The back face function for stencil test
*/
StencilFunc stencilFuncBack;
/**
* The back reference value for stencil test
*/
int32_t stencilRefBack;
/**
* The back mask value to AND with the reference value and store the result into stencil buffer when test is done
*/
uint32_t stencilMaskBack;
/**
* The function to use when the stencil test fails for back face
*/
StencilOp stencilFailOpBack;
/**
* The function to use when the stencil test passes but the depth test fails for back face
*/
StencilOp stencilZFailOpBack;
/**
* The function to use when both the stencil and the depth test pass for back face.
* Or when the stencil test passes and there is no depth buffer or depth testing is disabled.
*/
StencilOp stencilZPassOpBack;
/**
* The bit mask to enable or disable writing of individual bits in the back stencil planes
*/
uint32_t stencilWriteMaskBack;
/**
end of Stencil
@}
*/
/**
* Specifies whether front-facing or back-facing polygons are candidates for culling.
*/
CullMode cullMode;
/**
* Specifies the primitive type for rendering
*/
PrimitiveType primitiveType;
int32_t maxStream;
/**
* Specifies the vertex buffer
*/
void setVertexBuffer(size_t index, VertexBuffer* vertBuf);
/**
* Gets the vertex buffer
*/
VertexBuffer* getVertexBuffer(size_t index) const;
/**
* Specifies the vertex buffer offset
*/
void setVertexBufferOffset(size_t index, int32_t offset);
/**
* Gets the vertex buffer offset
*/
int32_t getVertexBufferOffset(size_t index) const;
/**
* Specifies the index buffer
*/
void setIndexBuffer(IndexBuffer* indexBuf);
/**
* Gets the index buffer
*/
IndexBuffer* getIndexBuffer() const;
/**
* Sets the texture for specific texture unit
*/
void setTexture(size_t index, Texture* texture);
/**
* Gets the specific texture unit
*/
Texture* getTexture(size_t index) const;
void setProgram(Program* program);
Program* getProgram() const;
/**
* Gets all texture units
*/
const std::vector<Texture*>& getTextureUnits() const { return _textureUnits; }
/**
* Sets the program used for rendering
*/
void setProgram(Program* program);
/**
* Gets the program used for rendering
*/
Program* getProgram() const;
private:
std::vector<VertexBuffer*> _vertexBuffers;
std::vector<int32_t> _vertexBufferOffsets;
@@ -113,4 +276,7 @@ private:
Program *_program;
};
// end of gfx group
/// @}
RENDERER_END
+7 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -76,6 +76,10 @@ Texture::~Texture()
bool Texture::init(DeviceGraphics* device)
{
if (device == nullptr)
{
return false;
}
_device = device;
_width = 4;
_height = 4;
+102 -9
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -37,10 +37,21 @@ RENDERER_BEGIN
class DeviceGraphics;
/**
* @addtogroup gfx
* @{
*/
/**
* The base texture class
*/
class Texture : public RenderTarget
{
public:
// texture filter
/**
* @enum Filter
* Texture filter modes
*/
enum class Filter : int8_t
{
NONE = -1,
@@ -48,7 +59,10 @@ public:
LINEAR = 1
};
// texture wrap mode
/**
* @enum Filter
* Texture wrap modes
*/
enum class WrapMode : uint16_t
{
REPEAT = GL_REPEAT,
@@ -56,7 +70,10 @@ public:
MIRROR = GL_MIRRORED_REPEAT
};
// texture format
/**
* @enum Format
* Texture formats
*/
enum class Format : uint8_t
{
BEGIN = 0,
@@ -95,35 +112,95 @@ public:
//
};
/**
* @struct Image
* Raw image data
*/
struct Image
{
uint8_t* data = nullptr;
size_t length = 0;
};
/**
* @struct Options
* Texture setting options including format, width, height, wrap mode, filter etc.
*/
struct Options
{
/**
* Image mipmaps
*/
std::vector<Image> images;
/**
* The maximum anisotropy for the texture
*/
int32_t anisotropy = 1;
/**
* The internal format specifying the color components in the texture
*/
GLenum glInternalFormat = GL_RGBA;
/**
* The pixel format of the texel data
*/
GLenum glFormat = GL_RGB;
/**
* The data type of the texel data
*/
GLenum glType = GL_UNSIGNED_BYTE;
/**
* The width of the texture
*/
uint16_t width = 4;
/**
* The height of the texture
*/
uint16_t height = 4;
uint8_t bpp = 0;
WrapMode wrapS = WrapMode::REPEAT;
WrapMode wrapT = WrapMode::REPEAT;
/**
* The wrapping function for texture coordinate s
*/
WrapMode wrapS = WrapMode::CLAMP;
/**
* The wrapping function for texture coordinate t
*/
WrapMode wrapT = WrapMode::CLAMP;
/**
* The texture minification filter
*/
Filter minFilter = Filter::LINEAR;
/**
* The texture magnification filter
*/
Filter magFilter = Filter::LINEAR;
/**
* The texture filter for mipmaps
*/
Filter mipFilter = Filter::LINEAR;
/**
* Specifies whether the texture have mipmaps
*/
bool hasMipmap = false;
bool flipY = true;
/**
* Specifies whether the texture if flipped vertically
*/
bool flipY = false;
/**
* Specifies whether the texture have alpha premultiplied
*/
bool premultiplyAlpha = false;
/**
* Specifies whether the texture is compressed
*/
bool compressed = false;
};
/**
* @struct ImageOption
* The informations of Image which indicates the mipmap level, width, height, filpY and premultiplyAlpha
*/
struct ImageOption
{
Image image;
@@ -135,6 +212,10 @@ public:
bool premultiplyAlpha = false;
};
/**
* @struct SubImageOption
* The informations of sub image which indicates the area to update, mipmap level, filpY and premultiplyAlpha
*/
struct SubImageOption
{
SubImageOption(uint16_t x, uint16_t y, uint16_t width, uint16_t height, uint8_t level, bool flipY, bool premultiplyAlpha)
@@ -160,8 +241,17 @@ public:
bool premultiplyAlpha = false;
};
/**
* Gets the target gl location
*/
inline GLuint getTarget() const { return _target; }
/**
* Gets the width of texture
*/
inline uint16_t getWidth() const { return _width; }
/**
* Gets the height of texture
*/
inline uint16_t getHeight() const { return _height; }
protected:
@@ -198,4 +288,7 @@ protected:
bool _compressed;
};
// end of gfx group
/// @}
RENDERER_END
+17 -6
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -149,7 +149,7 @@ void Texture2D::setSubImage(const SubImageOption& option)
GL_CHECK(ccPixelStorei(GL_UNPACK_FLIP_Y_WEBGL, flipY));
GL_CHECK(ccPixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha));
ccFlipYOrPremultiptyAlphaIfNeeded(_glFormat, option.width, option.height, (uint32_t)option.imageDataLength, option.imageData);
if (_compressed)
@@ -202,8 +202,19 @@ void Texture2D::setImage(const ImageOption& option)
GL_CHECK(ccPixelStorei(GL_UNPACK_ALIGNMENT, aligment));
GL_CHECK(ccPixelStorei(GL_UNPACK_FLIP_Y_WEBGL, flipY));
GL_CHECK(ccPixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha));
ccFlipYOrPremultiptyAlphaIfNeeded(_glFormat, option.width, option.height, (uint32_t)img.length, img.data);
uint32_t pixelBytes = (uint32_t)img.length;
switch(_glType)
{
case GL_FLOAT:
{
pixelBytes /= sizeof(float);
break;
}
}
ccFlipYOrPremultiptyAlphaIfNeeded(_glFormat, option.width, option.height, pixelBytes, img.data);
if (_compressed)
{
+42 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -31,15 +31,51 @@
RENDERER_BEGIN
/**
* @addtogroup gfx
* @{
*/
/**
* The 2d texture class\n
* JS API: gfx.Texture2D
@code
let texture = new gfx.Texture2D(cc.renderer.device, {
images: [],
width: 128,
height: 128,
wrapS: renderEngine.gfx.WRAP_REPEAT,
wrapT: renderEngine.gfx.WRAP_REPEAT,
format: renderEngine.gfx.TEXTURE_FMT_RGB8,
mipmap: false,
});
@endcode
*/
class Texture2D : public Texture
{
public:
Texture2D();
~Texture2D();
/*
* Init the texture with device and options
* @see Texture::Options
*/
bool init(DeviceGraphics* device, Options& options);
/**
* Update the texture with new options
* @see Texture::Options
*/
void update(const Options& options);
/**
* Update a sub area of the texture with sub image option
* @see Texture::SubImageOption
*/
void updateSubImage(const SubImageOption& option);
/**
* Update the image of a given level mipmap specified in image option
* @see Texture::ImageOption
*/
void updateImage(const ImageOption& option);
private:
@@ -50,4 +86,7 @@ private:
};
// end of gfx group
/// @}
RENDERER_END
+3 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+67 -4
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -32,30 +32,87 @@
RENDERER_BEGIN
/**
* @addtogroup gfx
* @{
*/
class DeviceGraphics;
/**
* VertexBuffer manages the GL vertex attributes buffer.
* It creates, updates and destoies the GL vertex buffer.
*/
class VertexBuffer final : public GraphicsHandle
{
public:
/**
* Creates a vertex buffer object
* @param[in] device DeviceGraphics pointer
* @param[in] format Specifies the vertex attributes layout
* @param[in] usage The usage pattern
* @param[in] data Data pointer, could be nullptr, then nothing is updated to the buffer.
* @param[in] dataByteLength Data's byte length.
* @param[in] numVertices Count of vertices.
*/
RENDERER_DEFINE_CREATE_METHOD_6(VertexBuffer, init, DeviceGraphics*, VertexFormat*, Usage, const void*, size_t, uint32_t)
VertexBuffer();
virtual ~VertexBuffer();
/**
* Initializes a vertex buffer object
* @param[in] device DeviceGraphics pointer
* @param[in] format Specifies the vertex attributes layout
* @param[in] usage The usage pattern
* @param[in] data Data pointer, could be nullptr, then nothing is updated to the buffer.
* @param[in] dataByteLength Data's byte length.
* @param[in] numVertices Count of vertices.
*/
bool init(DeviceGraphics* device, VertexFormat* format, Usage usage, const void* data, size_t dataByteLength, uint32_t numVertices);
/**
* Update data to the GL vertex buffer
* @param[in] offset Destination offset for filling buffer data.
* @param[in] data Data to be updated.
* @param[in] dataByteLength Data byte length to be updated.
*/
void update(uint32_t offset, const void* data, size_t dataByteLength);
/**
* Gets the count of vertices
*/
inline uint32_t getCount() const { return _numVertices; }
/**
* Sets the count of vertices
*/
inline void setCount(uint32_t numVertices) { _numVertices = numVertices; }
/**
* Gets the attributes layout and format of vertices.
*/
inline const VertexFormat& getFormat() const { return *_format; }
// inline void setFormat(VertexFormat&& format) { _format = std::move(format); }
/**
* Sets the attributes layout and format of vertices.
*/
void setFormat(VertexFormat* format);
/**
* Gets usage pattern of the vertex buffer
*/
inline Usage getUsage() const { return _usage; }
/**
* Sets usage pattern of the vertex buffer
*/
inline void setUsage(Usage usage) { _usage = usage; }
/**
* Gets byte size of the vertex buffer
*/
inline uint32_t getBytes() const { return _bytes; }
/**
* Sets byte size of the vertex buffer
*/
inline void setBytes(uint32_t bytes) { _bytes = bytes; }
using FetchDataCallback = std::function<uint8_t*(size_t*)>;
@@ -68,7 +125,10 @@ public:
}
return _fetchDataCallback(bytes);
}
/**
* Destroies the vertex buffer
*/
void destroy();
private:
@@ -83,4 +143,7 @@ private:
CC_DISALLOW_COPY_ASSIGN_AND_MOVE(VertexBuffer)
};
// end of gfx group
/// @}
RENDERER_END
+27 -6
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -48,6 +48,24 @@ static uint32_t attrTypeBytes(AttribType attrType)
return 0;
}
VertexFormat* VertexFormat::XY_UV_Two_Color = new VertexFormat(std::vector<Info>({
Info(ATTRIB_NAME_POSITION, AttribType::FLOAT32, 2),
Info(ATTRIB_NAME_UV0, AttribType::FLOAT32, 2),
Info(ATTRIB_NAME_COLOR, AttribType::UINT8, 4, true),
Info(ATTRIB_NAME_COLOR0, AttribType::UINT8, 4, true)
}));
VertexFormat* VertexFormat::XY_UV_Color = new VertexFormat(std::vector<Info>({
Info(ATTRIB_NAME_POSITION, AttribType::FLOAT32, 2),
Info(ATTRIB_NAME_UV0, AttribType::FLOAT32, 2),
Info(ATTRIB_NAME_COLOR, AttribType::UINT8, 4, true)
}));
VertexFormat* VertexFormat::XY_Color = new VertexFormat(std::vector<Info>({
Info(ATTRIB_NAME_POSITION, AttribType::FLOAT32, 2),
Info(ATTRIB_NAME_COLOR, AttribType::UINT8, 4, true)
}));
VertexFormat::VertexFormat()
{
}
@@ -76,6 +94,7 @@ VertexFormat::VertexFormat(const std::vector<Info>& infos)
el.normalize = info._normalize;
el.bytes = info._num * attrTypeBytes(info._type);
_names.push_back(el.name);
_attr2el[el.name] = el;
elements.push_back(&_attr2el[el.name]);
@@ -106,6 +125,7 @@ VertexFormat& VertexFormat::operator=(const VertexFormat& o)
{
if (this != &o)
{
_names = o._names;
_attr2el = o._attr2el;
#if GFX_DEBUG > 0
_elements = o._elements;
@@ -119,6 +139,7 @@ VertexFormat& VertexFormat::operator=(VertexFormat&& o)
{
if (this != &o)
{
_names = std::move(o._names);
_attr2el = std::move(o._attr2el);
#if GFX_DEBUG > 0
_elements = std::move(o._elements);
@@ -129,13 +150,13 @@ VertexFormat& VertexFormat::operator=(VertexFormat&& o)
return *this;
}
const VertexFormat::Element& VertexFormat::getElement(const std::string& attrName) const
const VertexFormat::Element* VertexFormat::getElement(const std::string& attrName) const
{
static const Element INVALID_ELEMENT_VALUE;
static const Element* INVALID_ELEMENT_VALUE = nullptr;
const auto& iter = _attr2el.find(attrName);
if (iter != _attr2el.end())
{
return iter->second;
return &iter->second;
}
return INVALID_ELEMENT_VALUE;
}
+98 -4
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -33,11 +33,38 @@
RENDERER_BEGIN
/**
* @addtogroup gfx
* @{
*/
/**
* The vertex format defines the attributes and their data layout in the VertexBuffer\n
* JS API: gfx.VertexFormat
@code
let vertexFmt = new gfx.VertexFormat([
{ name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 },
{ name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 },
{ name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_FLOAT32, num: 4, normalize: true },
]);
@endcode
*/
class VertexFormat : public Ref
{
public:
/*
* Informations used to define an attribute in vertex data layout.
* @struct Info
*/
struct Info
{
/*
* Constructor
* @param[in] name Attribute name
* @param[in] type Data type of each component
* @param[in] num Number of components per attribute
* @param[in] normalized Whether integer data values should be normalized into a certain range when being casted to a float
*/
Info(const std::string& name, AttribType type, uint32_t num, bool normalize = false)
: _name(name)
, _num(num)
@@ -53,6 +80,10 @@ public:
static Info INFO_END;
/*
* Element describes informations of an attribute
* @struct Info
*/
struct Element
{
Element()
@@ -70,27 +101,87 @@ public:
return type != AttribType::INVALID;
}
/*
* Name of the attribute
*/
std::string name;
/*
* Byte offset in each vertex data
*/
size_t offset;
/*
* Specifies the offset in bytes between the beginning of consecutive vertex attributes
*/
uint32_t stride;
int32_t stream;
/*
* Number of components per attribute unit
*/
uint32_t num;
/*
* Total bytes per attribute unit
*/
uint32_t bytes;
/*
* Data type of each component
*/
AttribType type;
/*
* Specifies whether integer data values should be normalized into a certain range when being casted to a float
*/
bool normalize;
};
/*
* Default constructor
*/
VertexFormat();
/**
* Constructor with specific attribute informations
* @param[in] infos Array of all elements informations
*/
VertexFormat(const std::vector<Info>& infos);
/*
* Copy constructor
*/
VertexFormat(const VertexFormat& o);
/*
* Move constructor
*/
VertexFormat(VertexFormat&& o);
VertexFormat& operator=(const VertexFormat& o);
VertexFormat& operator=(VertexFormat&& o);
const Element& getElement(const std::string& attrName) const;
/**
* Gets all attribute names
*/
const std::vector<std::string>& getAttributeNames() const { return _names; };
/**
* Getes an attribute element by name
*/
const Element* getElement(const std::string& attrName) const;
/**
* Gets total byte size of a vertex
*/
uint32_t getBytes() const { return _bytes; };
/*
* Builtin VertexFormat with 2d position, uv, color, color0 attributes
*/
static VertexFormat* XY_UV_Two_Color;
/*
* Builtin VertexFormat with 2d position, uv, color attributes
*/
static VertexFormat* XY_UV_Color;
/*
* Builtin VertexFormat with 2d position, color attributes
*/
static VertexFormat* XY_Color;
private:
std::vector<std::string> _names;
std::unordered_map<std::string, Element> _attr2el;
#if GFX_DEBUG > 0
std::vector<Element> _elements;
@@ -100,4 +191,7 @@ private:
friend class VertexBuffer;
};
// end of gfx group
/// @}
RENDERER_END
+128
View File
@@ -0,0 +1,128 @@
/****************************************************************************
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef RecyclePool_hpp
#define RecyclePool_hpp
#include <stdio.h>
#include "../Macro.h"
#include "../base/CCVector.h"
RENDERER_BEGIN
template<typename T>
class RecyclePool
{
public:
typedef std::function<T*()> RecycleFunc;
RecyclePool(RecycleFunc func, int size)
: _data()
{
_count = 0;
_func = func;
_data.resize(size);
for (int i = 0; i < size; i++)
{
_data[i] = func();
}
}
~RecyclePool()
{
for (size_t i = 0, len = _data.size(); i < len; i++)
{
delete _data[i];
}
_data.clear();
}
const T* getData(size_t index) const
{
if (index >= _count)
{
RENDERER_LOGW("Failed to get data %d, index not found.", index);
return nullptr;
}
return _data[index];
}
const size_t getLength() const
{
return _count;
}
void reset()
{
_count = 0;
}
T* add()
{
int size = (int)_data.size();
if (_count >= size)
{
resize(size * 2);
}
return _data[_count++];
}
void resize(int size)
{
if (size > _data.size())
{
for (int i = (int)_data.size(); i < size; i++)
{
T* data = _func();
_data.push_back(data);
}
}
}
void remove(int index)
{
if (index >= _count)
{
return;
}
int last = _count - 1;
T tmp = _data[index];
_data[index] = _data[last];
_data[last] = tmp;
_count -= 1;
}
private:
size_t _count = 0;
RecycleFunc _func;
std::vector<T*> _data;
};
RENDERER_END
#endif /* RecyclePool_hpp */
+198 -177
View File
@@ -30,18 +30,21 @@
#include "View.h"
#include "Scene.h"
#include "Effect.h"
#include "Light.h"
#include "InputAssembler.h"
#include "Pass.h"
#include "Camera.h"
#include "INode.h"
#include "Model.h"
RENDERER_BEGIN
BaseRenderer::BaseRenderer()
{
_drawItems.reserve(100);
_stageInfos.reserve(10);
_drawItems = new RecyclePool<DrawItem>([]()mutable->DrawItem*{return new DrawItem();},100);
_stageInfos = new RecyclePool<StageInfo>([]()mutable->StageInfo*{return new StageInfo();}, 10);
_views = new RecyclePool<View>([]()mutable->View*{return new View();}, 8);
_tmpMat3 = new cocos2d::Mat3();
}
BaseRenderer::~BaseRenderer()
@@ -54,6 +57,17 @@ BaseRenderer::~BaseRenderer()
RENDERER_SAFE_RELEASE(_defaultTexture);
_defaultTexture = nullptr;
delete _drawItems;
_drawItems = nullptr;
delete _stageInfos;
_stageInfos = nullptr;
delete _views;
_views = nullptr;
_tmpMat3 = nullptr;
}
bool BaseRenderer::init(DeviceGraphics* device, std::vector<ProgramLib::Template>& programTemplates)
@@ -99,69 +113,148 @@ void BaseRenderer::render(const View& view, const Scene* scene)
_device->clear(view.clearFlags, &clearColor, view.depth, view.stencil);
// get all draw items
_drawItems.clear();
int modelViewId = -1;
uint32_t drawItemCount = 0;
DrawItem drawItem;
_drawItems->reset();
int modelMask = -1;
for (const auto& model : scene->getModels())
{
modelViewId = model->getViewId();
modelMask = model->getCullingMask();
if (view.cullingByID)
{
if (modelViewId != view.id)
if ((modelMask & view.cullingMask) == 0)
continue;
}
else
{
if (-1 != modelViewId)
if (-1 != modelMask)
continue;
}
drawItemCount = model->getDrawItemCount();
for (uint32_t i = 0; i < drawItemCount; ++i)
{
model->extractDrawItem(drawItem, i);
_drawItems.push_back(drawItem);
}
DrawItem* drawItem = _drawItems->add();
model->extractDrawItem(*drawItem);
}
// dispatch draw items to different stage
_stageInfos.clear();
_stageInfos->reset();
StageItem stageItem;
StageInfo stageInfo;
std::vector<StageItem> stageItems;
for (const auto& stage : view.stages)
{
for (const auto& item : _drawItems)
for (size_t i = 0, len = _drawItems->getLength(); i < len; i++)
{
auto tech = item.effect->getTechnique(stage);
const DrawItem* item = _drawItems->getData(i);
auto tech = item->effect->getTechnique(stage);
if (tech)
{
stageItem.model = item.model;
stageItem.ia = item.ia;
stageItem.effect = item.effect;
stageItem.defines = item.defines;
stageItem.model = item->model;
stageItem.ia = item->ia;
stageItem.effect = item->effect;
stageItem.defines = item->defines;
stageItem.technique = tech;
stageItem.sortKey = -1;
stageItem.uniforms = item->uniforms;
stageItems.push_back(stageItem);
}
}
stageInfo.stage = stage;
stageInfo.items = &stageItems;
_stageInfos.push_back(std::move(stageInfo));
StageInfo* stageInfo = _stageInfos->add();
stageInfo->stage = stage;
stageInfo->items = &stageItems;
}
// render stages
std::unordered_map<std::string, StageCallback>::iterator foundIter;
for (const auto& stageInfo : _stageInfos)
for (size_t i = 0, len = _stageInfos->getLength(); i < len; i++)
{
foundIter = _stage2fn.find(stageInfo.stage);
const StageInfo* stageInfo = _stageInfos->getData(i);
foundIter = _stage2fn.find(stageInfo->stage);
if (_stage2fn.end() != foundIter)
{
auto& fn = foundIter->second;
fn(view, *stageInfo.items);
fn(view, *stageInfo->items);
}
}
}
void BaseRenderer::setProperty (Effect::Property& prop)
{
Technique::Parameter::Type propType = prop.getType();
auto& propName = prop.getName();
if (Effect::Property::Type::UNKNOWN == propType)
{
RENDERER_LOGW("Failed to set technique property, type unknown");
return;
}
if (nullptr == prop.getValue())
{
prop = Effect::Property(propName, propType);
if (Effect::Property::Type::TEXTURE_2D == propType)
{
prop.setTexture(_defaultTexture);
}
}
if (nullptr == prop.getValue())
{
RENDERER_LOGW("Failed to set technique property %s, value not found", propName.c_str());
return;
}
if (Effect::Property::Type::TEXTURE_2D == propType ||
Effect::Property::Type::TEXTURE_CUBE == propType)
{
if (1 == prop.getCount())
{
_device->setTexture(propName,
(renderer::Texture *)(prop.getValue()),
allocTextureUnit());
}
else if (0 < prop.getCount())
{
std::vector<int> slots;
slots.reserve(10);
for (int i = 0; i < prop.getCount(); ++i)
{
slots.push_back(allocTextureUnit());
}
_device->setTextureArray(propName,
prop.getTextureArray(),
slots);
}
}
else
{
if (0 != prop.getCount())
{
// if (Technique::Parameter::Type::COLOR3 == propType ||
// Technique::Parameter::Type::INT3 == propType ||
// Technique::Parameter::Type::FLOAT3 == propType ||
// Technique::Parameter::Type::MAT3 == propType)
// {
// RENDERER_LOGW("Uinform array of color3/int3/float3/mat3 can not be supported!");
// return;
// }
uint8_t size = Technique::Parameter::getElements(propType);
if (size * prop.getCount() > 64)
{
RENDERER_LOGW("Uniform array is too long!");
return;
}
}
uint16_t bytes = prop.getBytes();
if (Effect::Property::Type::INT == propType ||
Effect::Property::Type::INT2 == propType ||
Effect::Property::Type::INT4 == propType)
{
_device->setUniformiv(propName, bytes / sizeof(int), (const int*)prop.getValue());
}
else
{
_device->setUniformfv(propName, bytes / sizeof(float), (const float*)prop.getValue());
}
}
}
@@ -169,163 +262,90 @@ void BaseRenderer::render(const View& view, const Scene* scene)
void BaseRenderer::draw(const StageItem& item)
{
Mat4 worldMatrix = item.model->getWorldMatrix();
_device->setUniformMat4("model", worldMatrix.m);
_device->setUniformMat4("cc_matWorld", worldMatrix.m);
//REFINE: add Mat3
worldMatrix.inverse();
worldMatrix.transpose();
_device->setUniformMat4("normalMatrix", worldMatrix.m);
cocos2d::Mat3::fromMat4(*_tmpMat3, worldMatrix);
_tmpMat3->inverse();
_tmpMat3->transpose();
_device->setUniformMat4("cc_mat3WorldIT", _tmpMat3->m);
// set technique uniforms
auto ia = item.ia;
Technique::Parameter::Type propType = Technique::Parameter::Type::UNKNOWN;
for (const auto& param : item.technique->getParameters())
for (int i = 0, len = (int)item.uniforms->size(); i < len; i++)
{
Effect::Property* prop = const_cast<Effect::Property*>(&item.effect->getProperty(param.getName()));
std::unordered_map<std::string, Effect::Property>* properties = (*item.uniforms)[i];
for (auto& prop : *properties) {
setProperty(prop.second);
}
}
auto ia = item.ia;
// for each pass
for (const auto& pass : item.technique->getPasses())
{
// set vertex buffer
_device->setVertexBuffer(0, ia->getVertexBuffer());
if (Effect::Property::Type::UNKNOWN == prop->getType())
*prop = param;
// set index buffer
if (ia->_indexBuffer)
_device->setIndexBuffer(ia->_indexBuffer);
if (nullptr == prop->getValue())
// set primitive type
_device->setPrimitiveType(ia->_primitiveType);
_program = _programLib->getProgram(pass->_programName, *(item.defines));
_device->setProgram(_program);
// cull mode
_device->setCullMode(pass->_cullMode);
// blend
if (pass->_blend)
{
*prop = Effect::Property(param.getName(), param.getType());
if (Effect::Property::Type::TEXTURE_2D == param.getType())
prop->setTexture(_defaultTexture);
_device->enableBlend();
_device->setBlendFuncSeparate(pass->_blendSrc,
pass->_blendDst,
pass->_blendSrcAlpha,
pass->_blendDstAlpha);
_device->setBlendEquationSeparate(pass->_blendEq, pass->_blendAlphaEq);
_device->setBlendColor(pass->_blendColor);
}
if (nullptr == prop->getValue())
// depth test & write
if (pass->_depthTest)
{
RENDERER_LOGW("Failed to set technique property %s, value not found", param.getName().c_str());
continue;
_device->enableDepthTest();
_device->setDepthFunc(pass->_depthFunc);
}
if (pass->_depthWrite)
_device->enableDepthWrite();
// setencil
if (pass->_stencilTest)
{
_device->enableStencilTest();
// front
_device->setStencilFuncFront(pass->_stencilFuncFront,
pass->_stencilRefFront,
pass->_stencilMaskFront);
_device->setStencilOpFront(pass->_stencilFailOpFront,
pass->_stencilZFailOpFront,
pass->_stencilZPassOpFront,
pass->_stencilWriteMaskFront);
// back
_device->setStencilFuncBack(pass->_stencilFuncBack,
pass->_stencilRefBack,
pass->_stencilMaskBack);
_device->setStencilOpBack(pass->_stencilFailOpBack,
pass->_stencilZFailOpBack,
pass->_stencilZPassOpBack,
pass->_stencilWriteMaskBack);
}
propType = prop->getType();
if (Effect::Property::Type::TEXTURE_2D == propType ||
Effect::Property::Type::TEXTURE_CUBE == propType)
{
if (0 != param.getCount())
{
if (param.getCount() != prop->getCount())
{
RENDERER_LOGW("The length of texture array %d is not correct(expect %d)", prop->getCount(), param.getCount());
continue;
}
std::vector<int> slots;
slots.reserve(10);
for (int i = 0; i < param.getCount(); ++i)
slots.push_back(allocTextureUnit());
_device->setTextureArray(param.getName(),
std::move(prop->getTextureArray()),
slots);
}
else
_device->setTexture(param.getName(),
(renderer::Texture *)(prop->getValue()),
allocTextureUnit());
}
else
{
if (0 != prop->getCount())
{
if (Technique::Parameter::Type::COLOR3 == propType ||
Technique::Parameter::Type::INT3 == propType ||
Technique::Parameter::Type::FLOAT3 == propType ||
Technique::Parameter::Type::MAT3 == propType)
{
RENDERER_LOGW("Uinform array of color3/int3/float3/mat3 can not be supported!");
continue;
}
uint8_t size = Technique::Parameter::getElements(propType);
if (size * prop->getCount() > 64)
{
RENDERER_LOGW("Uniform array is too long!");
continue;
}
}
uint16_t bytes = prop->getBytes();
if (Effect::Property::Type::INT == propType ||
Effect::Property::Type::INT2 == propType ||
Effect::Property::Type::INT4 == propType)
_device->setUniformiv(param.getName(), bytes / sizeof(int), (const int*)prop->getValue());
else
_device->setUniformfv(param.getName(), bytes / sizeof(float), (const float*)prop->getValue());
}
// draw pass
_device->draw(ia->_start, ia->getPrimitiveCount());
// for each pass
for (const auto& pass : item.technique->getPasses())
{
// set vertex buffer
_device->setVertexBuffer(0, ia->getVertexBuffer());
// set index buffer
if (ia->_indexBuffer)
_device->setIndexBuffer(ia->_indexBuffer);
// set primitive type
_device->setPrimitiveType(ia->_primitiveType);
// set program
auto program = _programLib->getProgram(pass->_programName, *(item.defines));
_device->setProgram(program);
// cull mode
_device->setCullMode(pass->_cullMode);
// blend
if (pass->_blend)
{
_device->enableBlend();
_device->setBlendFuncSeparate(pass->_blendSrc,
pass->_blendDst,
pass->_blendSrcAlpha,
pass->_blendDstAlpha);
_device->setBlendEquationSeparate(pass->_blendEq, pass->_blendAlphaEq);
_device->setBlendColor(pass->_blendColor);
}
// depth test & write
if (pass->_depthTest)
{
_device->enableDepthTest();
_device->setDepthFunc(pass->_depthFunc);
}
if (pass->_depthWrite)
_device->enableDepthWrite();
// setencil
if (pass->_stencilTest)
{
_device->enableStencilTest();
// front
_device->setStencilFuncFront(pass->_stencilFuncFront,
pass->_stencilRefFront,
pass->_stencilMaskFront);
_device->setStencilOpFront(pass->_stencilFailOpFront,
pass->_stencilZFailOpFront,
pass->_stencilZPassOpFront,
pass->_stencilWriteMaskFront);
// back
_device->setStencilFuncBack(pass->_stencilFuncBack,
pass->_stencilRefBack,
pass->_stencilMaskBack);
_device->setStencilOpBack(pass->_stencilFailOpBack,
pass->_stencilZFailOpBack,
pass->_stencilZPassOpBack,
pass->_stencilWriteMaskBack);
}
// draw pass
_device->draw(ia->_start, ia->getPrimitiveCount());
resetTextureUint();
}
resetTextureUint();
}
}
@@ -347,12 +367,13 @@ int BaseRenderer::allocTextureUnit()
void BaseRenderer::reset()
{
_views->reset();
_stageInfos->reset();
}
View* BaseRenderer::requestView()
{
return new (std::nothrow) View();
return _views->add();
}
RENDERER_END
+50 -7
View File
@@ -31,6 +31,8 @@
#include "../Macro.h"
#include "ProgramLib.h"
#include "Model.h"
#include "Effect.h"
#include "../memop/RecyclePool.hpp"
RENDERER_BEGIN
@@ -44,33 +46,66 @@ class Effect;
class Technique;
class Texture2D;
/**
* @addtogroup renderer
* @{
*/
/**
* @brief Base renderer implements the basic render process.
*/
class BaseRenderer : public Ref
{
public:
struct StageItem
{
Model* model = nullptr;
INode* node = nullptr;
InputAssembler *ia = nullptr;
Effect* effect = nullptr;
ValueMap* defines = nullptr;
Technique* technique = nullptr;
std::vector<ValueMap*>* defines = nullptr;
std::vector<std::unordered_map<std::string, Effect::Property>*>* uniforms = nullptr;
int sortKey = -1;
};
typedef std::function<void(const View&, const std::vector<StageItem>&)> StageCallback;
/**
* @brief The default constructor.
*/
BaseRenderer();
/**
* @brief Initializes the base renderer.
* @param[in] device DeviceGraphics pointer.
* @param[in] programTemplates All linked programs.
*/
bool init(DeviceGraphics* device, std::vector<ProgramLib::Template>& programTemplates);
/**
* @brief Initializes the base renderer.
* @param[in] device DeviceGraphics pointer.
* @param[in] programTemplates All programs.
* @param[in] defaultTexture Default texture pointer.
*/
bool init(DeviceGraphics* device, std::vector<ProgramLib::Template>& programTemplates, Texture2D* defaultTexture);
/**
* @brief The default destructor.
*/
virtual ~BaseRenderer();
/**
* @brief Register a new render stage.
* @param[in] name Stage name.
* @param[in] call Stage handle callback.
*/
void registerStage(const std::string& name, const StageCallback& callback);
ProgramLib* getProgramLib() const { return _programLib; }
/**
* @brief Gets the program library pointer.
* @return Program library pointer.
*/
ProgramLib* getProgramLib() const { return _programLib; };
protected:
void render(const View&, const Scene* scene);
void draw(const StageItem& item);
void setProperty (Effect::Property& prop);
struct StageInfo
{
@@ -84,14 +119,22 @@ protected:
View* requestView();
int _usedTextureUnits = 0;
std::string _programName;
int32_t _definesKey = 0;
DeviceGraphics* _device = nullptr;
ProgramLib* _programLib = nullptr;
Program* _program = nullptr;
Texture2D* _defaultTexture = nullptr;
std::unordered_map<std::string, StageCallback> _stage2fn;
std::vector<DrawItem> _drawItems;
std::vector<StageInfo> _stageInfos;
RecyclePool<DrawItem>* _drawItems = nullptr;
RecyclePool<StageInfo>* _stageInfos = nullptr;
RecyclePool<View>* _views = nullptr;
cocos2d::Mat3* _tmpMat3 = nullptr;
CC_DISALLOW_COPY_ASSIGN_AND_MOVE(BaseRenderer);
};
// end of renderer group
/// @}
RENDERER_END
+40 -38
View File
@@ -24,21 +24,18 @@
#include "Camera.h"
#include "gfx/FrameBuffer.h"
#include "INode.h"
#include "math/MathUtil.h"
RENDERER_BEGIN
Camera::Camera()
{
_cachedView.color = _color;
_cachedView.depth = _depth;
_cachedView.clearFlags = _clearFlags;
_cachedView.stencil = _stencil;
}
Camera::~Camera()
{
RENDERER_SAFE_RELEASE(_framebuffer);
RENDERER_SAFE_RELEASE(_node);
}
void Camera::setFrameBuffer(FrameBuffer* framebuffer)
@@ -46,8 +43,6 @@ void Camera::setFrameBuffer(FrameBuffer* framebuffer)
RENDERER_SAFE_RELEASE(_framebuffer);
_framebuffer = framebuffer;
RENDERER_SAFE_RETAIN(_framebuffer);
_cachedView.frameBuffer = _framebuffer;
}
void Camera::setWorldMatrix(const Mat4& worldMatrix)
@@ -63,25 +58,21 @@ void Camera::setWorldMatrix(const Mat4& worldMatrix)
void Camera::setColor(float r, float g, float b, float a)
{
_color.set(r, g, b, a);
_cachedView.color = _color;
}
void Camera::setDepth(float depth)
{
_depth = depth;
_cachedView.depth = _depth;
}
void Camera::setStencil(int stencil)
{
_stencil = stencil;
_cachedView.stencil = _stencil;
}
void Camera::setClearFlags(uint8_t flags )
{
_clearFlags = flags;
_cachedView.clearFlags = _clearFlags;
}
void Camera::setRect(float x, float y, float w, float h)
@@ -92,46 +83,63 @@ void Camera::setRect(float x, float y, float w, float h)
void Camera::setStages(const std::vector<std::string>& stages)
{
_stages = stages;
_cachedView.stages = _stages;
}
void Camera::setNode(INode* node)
void Camera::setNode(NodeProxy* node)
{
if (_node != nullptr)
{
_node->release();
}
_node = node;
if (_node != nullptr)
{
_node->retain();
}
}
const View& Camera::extractView( int width, int height)
void Camera::extractView(View& out, int width, int height)
{
// can optimize it if node's position is not changed
// rect
_cachedView.rect.set(_rect.x * width,
out.rect.set(_rect.x * width,
_rect.y * height,
_rect.w * width,
_rect.h * height);
// clear opts
out.color = _color;
out.depth = _depth;
out.stencil = _stencil;
out.clearFlags = _clearFlags;
// view matrix
//REFINE:
_worldRTInv.set(_node->getWorldRT());
_cachedView.matView.set(_worldRTInv.getInversed());
_node->getWorldRT(&_worldRTInv);
out.matView.set(_worldRTInv.getInversed());
// projecton matrix
float aspect = (float)width / height;
if (ProjectionType::PERSPECTIVE == _projection)
Mat4::createPerspective(_fov / 3.1415926 * 180, aspect, _near, _far, &_cachedView.matProj);
Mat4::createPerspective(_fov / 3.1415926 * 180, aspect, _near, _far, &out.matProj);
else
{
float x = _orthoHeight * aspect;
float y = _orthoHeight;
Mat4::createOrthographic(-x, x, -y, y, &_cachedView.matProj);
Mat4::createOrthographicOffCenter(-x, x, -y, y, _near, _far, &out.matProj);
}
// view projection
Mat4::multiply(_cachedView.matProj, _cachedView.matView, &_cachedView.matViewProj);
_cachedView.matInvViewPorj.set(_cachedView.matViewProj.getInversed());
Mat4::multiply(out.matProj, out.matView, &out.matViewProj);
out.matInvViewPorj.set(out.matViewProj.getInversed());
return _cachedView;
// stages & framebuffer
out.stages = _stages;
out.frameBuffer = _framebuffer;
// culling mask
out.cullingMask = _cullingMask;
out.cullingByID = true;
}
Vec3& Camera::screenToWorld(Vec3& out, const Vec3& screenPos, int width, int height) const
@@ -153,7 +161,7 @@ Vec3& Camera::screenToWorld(Vec3& out, const Vec3& screenPos, int width, int hei
Mat4::createOrthographic(-x, x, -y, y, &matProj);
}
const_cast<Camera*>(this)->_worldRTInv = _node->getWorldRT();
_node->getWorldRT(&(const_cast<Camera*>(this)->_worldRTInv));
const_cast<Camera*>(this)->_worldRTInv.inverse();
// view projection
@@ -172,16 +180,15 @@ Vec3& Camera::screenToWorld(Vec3& out, const Vec3& screenPos, int width, int hei
// Transform to world position.
matInvViewProj.transformPoint(&out);
const_cast<Camera*>(this)->_worldPos.set(_node->getWorldPos());
_node->getWorldPosition(&(const_cast<Camera*>(this)->_worldPos));
Vec3 tmpVec3 = _worldPos;
out = tmpVec3.lerp(out, screenPos.z / _far);
out = tmpVec3.lerp(out, MathUtil::lerp(_near / _far, 1, screenPos.z));
}
else
{
float range = _far - _near;
out.set((screenPos.x - cx) * 2.0f / cw - 1.0f,
(screenPos.y - cy) * 2.0f / ch - 1.0f,
(_far - screenPos.z) / range * 2.0f - 1.0f);
screenPos.z * 2.0f - 1.0f);
// Transform to world position.
matInvViewProj.transformPoint(&out);
@@ -209,21 +216,16 @@ Vec3& Camera::worldToScreen(Vec3& out, const Vec3& worldPos, int width, int heig
Mat4::createOrthographic(-x, x, -y, y, &matProj);
}
const_cast<Camera*>(this)->_worldRTInv = _node->getWorldRT();
_node->getWorldRT(&(const_cast<Camera*>(this)->_worldRTInv));
const_cast<Camera*>(this)->_worldRTInv.inverse();
// view projection
Mat4 matViewProj;
Mat4::multiply(matProj, _worldRTInv, &matViewProj);
// caculate w
float w = worldPos.x * matViewProj.m[3] +
worldPos.y * matViewProj.m[7] +
worldPos.z * matViewProj.m[11] +
matViewProj.m[15];
matViewProj.transformPoint(worldPos, &out);
out.x = cx + (out.x / w + 1) * 0.5f * cw;
out.y = cy + (out.y / w + 1) * 0.5f * ch;
out.x = cx + (out.x + 1) * 0.5f * cw;
out.y = cy + (out.y + 1) * 0.5f * ch;
out.z = out.z * 0.5 + 0.5;
return out;
}
+132 -23
View File
@@ -32,6 +32,7 @@
#include "../Macro.h"
#include "../Types.h"
#include "View.h"
#include "../scene/NodeProxy.hpp"
#ifdef near
#undef near
@@ -44,67 +45,172 @@
RENDERER_BEGIN
class FrameBuffer;
class INode;
/**
* @addtogroup renderer
* @{
*/
/**
* @brief Manage scene camera.
*/
class Camera : public Ref
{
public:
/**
* @brief The default constructor.
*/
Camera();
/**
* @brief The default destructor.
*/
~Camera();
/**
* @brief Gets the camera type.
*/
ProjectionType getType() const { return _projection; }
/**
* @brief Sets the camera type.
*/
inline void setType(ProjectionType value) { _projection = value; }
/**
* @brief Gets the view height for orthographic camera.
*/
inline float getOrthoHeight() const { return _orthoHeight; }
/**
* @brief Sets the view height for orthographic camera.
*/
inline void setOrthoHeight(float value) { _orthoHeight = value; }
/**
* @brief Gets the field of view for the camera.
*/
inline float getFov() const { return _fov; }
/**
* @brief Sets the field of view for the camera.
*/
inline void setFov(float fov) { _fov = fov; }
/**
* @brief Gets the near clip plane.
*/
inline float getNear() const { return _near; }
/**
* @brief Sets the near clip plane.
*/
inline void setNear(float near) { _near = near; }
/**
* @brief Gets the far clip plane.
*/
inline float getFar() const { return _far; }
/**
* @brief Sets the far clip plane.
*/
inline void setFar(float far) { _far = far; }
/**
* @brief Gets the clear color.
*/
inline void getColor(Color4F& out) const { out = _color; }
/**
* @brief Sets the clear color.
*/
void setColor(float r, float g, float b, float a);
/**
* @brief Gets the depth of the camera, camera of smaller depth gets rendered earlier.
*/
inline float getDepth() const { return _depth; }
/**
* @brief Sets the depth of the camera, camera of smaller depth gets rendered earlier
*/
void setDepth(float depth);
/**
* @brief Gets the culling mask.
*/
inline int getCullingMask() const { return _cullingMask; }
/**
* @brief Sets the culling mask.
*/
inline void setCullingMask(int mask) { _cullingMask = mask; }
/**
* @brief Gets the stencil value to clear
*/
inline int getStencil() const { return _stencil; }
/**
* @brief Sets the stencil value to clear
*/
void setStencil(int stencil);
/**
* @brief Gets the clear flags including color, stencil and depth.
*/
inline uint8_t getClearFlags() const { return _clearFlags; }
/**
* @brief Sets the clear flags including color, stencil and depth.
*/
void setClearFlags(uint8_t flags );
/**
* @brief Gets rect.
*/
inline Rect* getRect(Rect& out) const { out = _rect; return &out; }
/**
* @brief Sets rect.
*/
void setRect(float x, float y, float w, float h);
/**
* @brief Gets stages.
*/
inline const std::vector<std::string>& getStages() const { return _stages; }
/**
* @brief Sets stages.
*/
void setStages(const std::vector<std::string>& stages);
/**
* @brief Gets the frame buffer as render target.
*/
inline FrameBuffer* getFrameBuffer() const { return _framebuffer; }
/**
* @brief Sets the frame buffer as render target.
*/
void setFrameBuffer(FrameBuffer* framebuffer);
/**
* @brief Sets the world matrix.
*/
void setWorldMatrix(const Mat4& worldMatrix);
const View& extractView(int width, int height);
/**
* @brief Extracts the camera info to view.
*/
void extractView(View& view, int width, int height);
/**
* @brief Transform a screen position to world in the current camera projection.
*/
Vec3& screenToWorld(Vec3& out, const Vec3& screenPos, int width, int height) const;
/**
* @brief Transform a world position to screen in the current camera projection.
*/
Vec3& worldToScreen(Vec3& out, const Vec3& worldPos, int width, int height) const;
void setNode(INode* node);
inline INode* getNode() const { return _node; }
/**
* @brief Sets the related node proxy which provids model matrix for camera.
*/
void setNode(NodeProxy* node);
/**
* @brief Gets the related node proxy which provids model matrix for camera.
*/
inline NodeProxy* getNode() const { return _node; }
/**
* @brief Sets the camera render priority.
*/
void setPriority(int priority) { _priority = priority; }
/**
* @brief Gets the camera render priority.
*/
int getPriority() const { return _priority; }
private:
INode* _node = nullptr;
NodeProxy* _node = nullptr;
ProjectionType _projection = ProjectionType::PERSPECTIVE;
// clear options
Color4F _color = {0.2f, 0.3f, 0.47f, 1.f};
float _depth = 1.f;
int _stencil = 1;
int _cullingMask = 1;
uint8_t _clearFlags = ClearFlag::COLOR | ClearFlag::DEPTH;
// stage & framebuffer
@@ -122,8 +228,11 @@ private:
Mat4 _worldRTInv;
Vec3 _worldPos;
View _cachedView;
int _priority = 0;
};
// end of renderer group
/// @}
RENDERER_END
+25
View File
@@ -31,11 +31,33 @@
RENDERER_BEGIN
/**
* @addtogroup renderer
* @{
*/
/**
* @brief Stage config which use to store stageID.
*/
class Config
{
public:
/**
* @brief Adds stage id by name.
* @param[in] name Stage name.
*/
static void addStage(const std::string& name);
/**
* @brief Gets stage id by name.
* @param[in] name Stage name.
* @return Stage id.
*/
static int getStageID(const std::string& name);
/**
* @brief Gets all stage id by a list of names and store in uint32 value by AND operation.
* @param[in] nameList Stage name list.
* @return A uint32 represents all stages.
*/
static unsigned int getStageIDs(const std::vector<std::string>& nameList);
private:
@@ -43,4 +65,7 @@ private:
static std::unordered_map<std::string, unsigned int> _name2stageID;
};
// end of renderer group
/// @}
RENDERER_END
@@ -0,0 +1,91 @@
/****************************************************************************
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CustomProperties.hpp"
RENDERER_BEGIN
CustomProperties::CustomProperties()
{
}
CustomProperties::~CustomProperties()
{
_properties.clear();
_defines.clear();
}
void CustomProperties::setProperty(const std::string name, const Property& property)
{
auto iter = _properties.find(name);
if (iter != _properties.end() && iter->second == property)
{
return;
}
_properties[name] = property;
_dirty = true;
}
const CustomProperties::Property& CustomProperties::getProperty(std::string name) const
{
static Property EMPTY_PROPERTY;
if (_properties.end() == _properties.find(name))
return EMPTY_PROPERTY;
else
return _properties.at(name);
}
void CustomProperties::define(const std::string& name, const Value& value)
{
if (_defines[name] == value)
{
return;
};
_dirty = true;
_defines[name] = value;
}
Value CustomProperties::getDefine(const std::string& name) const
{
auto iter = _defines.find(name);
if (iter != _defines.end())
{
return iter->second;
}
RENDERER_LOGW("Failed to get CustomProperties define %s, define not found.", name.c_str());
return Value::Null;
}
std::unordered_map<std::string, CustomProperties::Property>* CustomProperties::extractProperties()
{
return &_properties;
}
ValueMap* CustomProperties::extractDefines()
{
return &_defines;
}
RENDERER_END
@@ -0,0 +1,56 @@
/****************************************************************************
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include <stdio.h>
#include "../Macro.h"
#include "Technique.h"
#include "base/CCValue.h"
RENDERER_BEGIN
class CustomProperties
{
public:
using Property = Technique::Parameter;
CustomProperties();
~CustomProperties();
void setProperty(const std::string name, const Property& property);
const Property& getProperty(std::string name) const;
void define(const std::string& name, const Value& value);
Value getDefine(const std::string& name) const;
std::unordered_map<std::string, Property>* extractProperties();
ValueMap* extractDefines();
const double getHash() const {return _hash; };
private:
std::unordered_map<std::string, Property> _properties;
ValueMap _defines;
double _hash = 0;
bool _dirty = false;
};
RENDERER_END
+106 -7
View File
@@ -27,7 +27,12 @@
RENDERER_BEGIN
std::map<std::string,std::size_t> Effect::_defineBitOrder;
std::vector<std::string> Effect::_sharedDefineList;
Effect::Effect()
: _hash(0)
, _definesKey(0)
{}
void Effect::init(const Vector<Technique*>& techniques,
@@ -41,6 +46,7 @@ void Effect::init(const Vector<Technique*>& techniques,
for (const auto defineTemplate: _defineTemplates)
_cachedNameValues.emplace(defineTemplate.at("name").asString(),
defineTemplate.at("value"));
generateKey();
}
Effect::~Effect()
@@ -70,7 +76,7 @@ Technique* Effect::getTechnique(const std::string& stage) const
return nullptr;
}
Value Effect::getDefineValue(const std::string& name) const
Value Effect::getDefine(const std::string& name) const
{
for (const auto& def : _defineTemplates)
{
@@ -82,27 +88,33 @@ Value Effect::getDefineValue(const std::string& name) const
return Value::Null;
}
void Effect::setDefineValue(const std::string& name, const Value& value)
void Effect::define(const std::string& name, const Value& value)
{
for (auto& def : _defineTemplates)
{
if (name == def.at("name").asString())
{
def["value"] = value;
_cachedNameValues[name] = value;
if (_cachedNameValues[name] != value)
{
_cachedNameValues[name] = value;
generateKey();
}
return;
}
}
};
}
ValueMap* Effect::extractDefines()
{
// for (auto& def : _defineTemplates)
// out.emplace(def.at("name").asString(), def.at("value"));
return &_cachedNameValues;
}
std::unordered_map<std::string, Effect::Property>* Effect::extractProperties()
{
return &_properties;
}
const Effect::Property& Effect::getProperty(const std::string& name) const
{
static Property EMPTY_PROPERTY;
@@ -117,4 +129,91 @@ void Effect::setProperty(const std::string& name, const Property& property)
_properties[name] = property;
}
void Effect::_updateDefineBitOrder(const ValueMap& nameValues)
{
for (auto& tmplDefs : nameValues)
{
if (_defineBitOrder.find(tmplDefs.first) == _defineBitOrder.end())
{
_sharedDefineList.push_back(tmplDefs.first);
_defineBitOrder[tmplDefs.first] = _sharedDefineList.size();
}
}
}
void Effect::generateKey()
{
// Update global order when has new define.
_updateDefineBitOrder(_cachedNameValues);
_definesKey = 0;
for (auto& tmplDefs : _cachedNameValues) {
uint32_t value = tmplDefs.second.asUnsignedInt();
CCASSERT(value <= 1,"Define value can't greater than 1");
value <<= _defineBitOrder[tmplDefs.first];
_definesKey |= value;
}
// Reserve 8 bit for the OR operation with program id in ProgramLib.
_definesKey <<= 8;
}
void Effect::copy(const Effect* effect)
{
_hash = effect->_hash;
auto& otherTech = effect->_techniques;
for (auto it = otherTech.begin(); it != otherTech.end(); it ++)
{
auto tech = new Technique();
tech->autorelease();
tech->copy(**it);
_techniques.pushBack(tech);
}
_defineTemplates = effect->_defineTemplates;
_cachedNameValues = effect->_cachedNameValues;
_properties = effect->_properties;
_definesKey = effect->_definesKey;
}
void Effect::setCullMode(CullMode cullMode)
{
Technique* tech = _techniques.front();
const Vector<Pass*>& passes = tech->getPasses();
for (const auto& pass : passes)
{
pass->setCullMode(cullMode);
}
}
void Effect::setBlend(BlendOp blendEq, BlendFactor blendSrc, BlendFactor blendDst, BlendOp blendAlphaEq, BlendFactor blendSrcAlpha, BlendFactor blendDstAlpha, uint32_t blendColor)
{
Technique* tech = _techniques.front();
const Vector<Pass*>& passes = tech->getPasses();
for (const auto& pass : passes)
{
pass->setBlend(blendEq, blendSrc, blendDst, blendAlphaEq, blendSrcAlpha, blendDstAlpha, blendColor);
}
}
void Effect::setStencilTest(bool value)
{
Technique* tech = _techniques.front();
const Vector<Pass*>& passes = tech->getPasses();
for (const auto& pass : passes)
{
pass->setStencilTest(value);
}
}
void Effect::setStencil(StencilFunc stencilFunc, uint32_t stencilRef, uint8_t stencilMask, StencilOp stencilFailOp, StencilOp stencilZFailOp, StencilOp stencilZPassOp, uint8_t stencilWriteMask)
{
Technique* tech = _techniques.front();
const Vector<Pass*>& passes = tech->getPasses();
for (const auto& pass : passes)
{
pass->setStencilFront(stencilFunc, stencilRef, stencilMask, stencilFailOp, stencilZFailOp, stencilZPassOp, stencilWriteMask);
pass->setStencilBack(stencilFunc, stencilRef, stencilMask, stencilFailOp, stencilZFailOp, stencilZPassOp, stencilWriteMask);
}
}
RENDERER_END
+153 -5
View File
@@ -26,44 +26,192 @@
#include <vector>
#include <unordered_map>
#include <map>
#include "base/CCRef.h"
#include "base/CCValue.h"
#include "../Macro.h"
#include "Technique.h"
#include "Pass.h"
RENDERER_BEGIN
/**
* @addtogroup renderer
* @{
*/
/**
* @brief Fundamental class of material system, contains techniques, shader template define settings and uniform properties.\n
* JS API: renderer.Effect
* @code
* let pass = new renderer.Pass('sprite');
* pass.setDepth(false, false);
* pass.setCullMode(gfx.CULL_NONE);
* let mainTech = new renderer.Technique(
* ['transparent'],
* [
* { name: 'texture', type: renderer.PARAM_TEXTURE_2D },
* { name: 'color', type: renderer.PARAM_COLOR4 }
* ],
* [
* pass
* ]
* );
* let effect = new renderer.Effect(
* [
* mainTech
* ],
* {
* 'color': {r: 1, g: 1, b: 1, a: 1}
* },
* [
* { name: 'useTexture', value: true },
* { name: 'useModel', value: false },
* { name: 'alphaTest', value: false },
* { name: 'useColor', value: true }
* ]
* );
* @endcode
*/
class Effect : public Ref
{
public:
using Property = Technique::Parameter;
/*
* @brief The default constructor.
*/
Effect();
/*
* @brief The default destructor.
*/
~Effect();
/*
* @brief Initialize with techniques, properties and define settings.
* @param[in] techniques All techniques in an array
* @param[in] properties All properties in a map
* @param[in] defineTemplates All defines and their value in a map
*/
void init(const Vector<Technique*>& techniques,
const std::unordered_map<std::string, Property>& properties,
const std::vector<ValueMap>& defineTemplates);
/**
* @brief Clears techniques and define list.
*/
void clear();
/**
* @brief Gets technique by stage.
*/
Technique* getTechnique(const std::string& stage) const;
/*
* @brief Gets all techniques.
*/
const Vector<Technique*>& getTechniques() const { return _techniques; }
Value getDefineValue(const std::string& name) const;
/**
* @brief Gets define property value by name.
*/
Value getDefine(const std::string& name) const;
/**
* @brief Sets a define's value.
*/
void define(const std::string& name, const Value& value);
/*
* @brief Gets all define values.
*/
const std::vector<ValueMap>& getDefines() const { return _defineTemplates; }
void setDefineValue(const std::string& name, const Value& value);
/*
* @brief Extracts all defines.
*/
ValueMap* extractDefines();
/*
* @brief Extracts all propertyps.
*/
std::unordered_map<std::string, Property>* extractProperties();
/**
* @brief Gets uniform property value by name.
*/
const Property& getProperty(const std::string& name) const;
/**
* @brief Sets uniform property value by name.
*/
void setProperty(const std::string& name, const Property& property);
/*
* @brief Gets all uniform properties.
*/
const std::unordered_map<std::string, Property>& getProperties() const { return _properties; }
/**
* @brief Updates hash.
*/
void updateHash(double hash) { _hash = hash; };
/**
* @brief Gets hash.
*/
double getHash() const { return _hash; };
/**
* @brief Sets cull mode.
* @param[in] cullMode Cull front or back or both.
*/
void setCullMode(CullMode cullMode);
/**
* @brief Sets blend mode.
* @param[in] blendEq RGB blend equation.
* @param[in] blendSrc Src RGB blend factor.
* @param[in] blendDst Dst RGB blend factor.
* @param[in] blendAlphaEq Alpha blend equation.
* @param[in] blendSrcAlpha Src Alpha blend equation.
* @param[in] blendDstAlpha Dst Alpha blend equation.
* @param[in] blendColor Blend constant color value.
*/
void setBlend(BlendOp blendEq = BlendOp::ADD,
BlendFactor blendSrc = BlendFactor::ONE,
BlendFactor blendDst = BlendFactor::ZERO,
BlendOp blendAlphaEq = BlendOp::ADD,
BlendFactor blendSrcAlpha = BlendFactor::ONE,
BlendFactor blendDstAlpha = BlendFactor::ZERO,
uint32_t blendColor = 0xffffffff);
/**
* @brief Sets stencil front-facing function, reference, mask, fail operation, write mask.
*/
void setStencil(StencilFunc stencilFunc = StencilFunc::ALWAYS,
uint32_t stencilRef = 0,
uint8_t stencilMask = 0xff,
StencilOp stencilFailOp = StencilOp::KEEP,
StencilOp stencilZFailOp = StencilOp::KEEP,
StencilOp stencilZPassOp = StencilOp::KEEP,
uint8_t stencilWriteMask = 0xff);
/*
* @brief Sets stencil test enabled or not.
*/
void setStencilTest(bool value);
/*
* @brief Gets the define key for the current define settings.
*/
const int32_t& getDefinesKey() { return _definesKey; };
/**
* @brief Deep copy from other effect.
*/
void copy(const Effect* effect);
private:
double _hash;
int32_t _definesKey;
Vector<Technique*> _techniques;
std::vector<ValueMap> _defineTemplates;
ValueMap _cachedNameValues;
std::unordered_map<std::string, Property> _properties;
// Global define order.
static std::map<std::string,std::size_t> _defineBitOrder;
static std::vector<std::string> _sharedDefineList;
static void _updateDefineBitOrder(const ValueMap& nameValues);
void generateKey();
};
// end of renderer group
/// @}
RENDERER_END
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -28,6 +28,7 @@
#include "gfx/Texture2D.h"
#include "gfx/VertexBuffer.h"
#include "gfx/IndexBuffer.h"
#include "gfx/FrameBuffer.h"
#include "ProgramLib.h"
#include "View.h"
#include "Scene.h"
@@ -35,12 +36,28 @@
#include "InputAssembler.h"
#include "Pass.h"
#include "Camera.h"
#include "Light.h"
#include <algorithm>
RENDERER_BEGIN
ForwardRenderer::ForwardRenderer()
{
_arrayPool = new RecyclePool<float>([]()mutable->float*{return new float[16];}, 8);
}
ForwardRenderer::~ForwardRenderer()
{
_directionalLights.clear();
_pointLights.clear();
_spotLights.clear();
_shadowLights.clear();
_ambientLights.clear();
_defines.clear();
delete _arrayPool;
_arrayPool = nullptr;
}
bool ForwardRenderer::init(DeviceGraphics* device, std::vector<ProgramLib::Template>& programTemplates, Texture2D* defaultTexture, int width, int height)
@@ -48,32 +65,395 @@ bool ForwardRenderer::init(DeviceGraphics* device, std::vector<ProgramLib::Templ
BaseRenderer::init(device, programTemplates, defaultTexture);
_width = width;
_height = height;
registerStage("opaque", std::bind(&ForwardRenderer::opaqueStage, this, std::placeholders::_1, std::placeholders::_2));
registerStage("shadowcast", std::bind(&ForwardRenderer::shadowStage, this, std::placeholders::_1, std::placeholders::_2));
registerStage("transparent", std::bind(&ForwardRenderer::transparentStage, this, std::placeholders::_1, std::placeholders::_2));
return true;
}
void ForwardRenderer::resetData()
{
_arrayPool->reset();
reset();
}
void ForwardRenderer::render(Scene* scene)
{
// reset();
resetData();
updateLights(scene);
scene->sortCameras();
auto& cameras = scene->getCameras();
for (auto& camera : cameras)
{
View* view = requestView();
camera->extractView(*view, _width, _height);
}
const auto& cameras = scene->getCameras();
for (auto camera : cameras)
BaseRenderer::render(camera->extractView(_width, _height), scene);
for (size_t i = 0, len = _views->getLength(); i < len; ++i) {
const View* view = _views->getData(i);
BaseRenderer::render(*view, scene);
}
scene->removeModels();
}
void ForwardRenderer::renderCamera(Camera* camera, Scene* scene)
{
reset();
int width = _width;
int height = _height;
FrameBuffer* fb = camera->getFrameBuffer();
if (nullptr != fb) {
width = fb->getWidth();
height = fb->getHeight();
}
View* view = requestView();
camera->extractView(*view, width, height);
BaseRenderer::render(*view, scene);
scene->removeModels();
}
void ForwardRenderer::updateLights(Scene* scene)
{
_directionalLights.clear();
_pointLights.clear();
_spotLights.clear();
_shadowLights.clear();
_ambientLights.clear();
const Vector<Light*> lights = scene->getLights();
for (const auto& light : lights)
{
light->update(_device);
if (light->getShadowType() != Light::ShadowType::NONE)
{
_shadowLights.pushBack(light);
View* view = requestView();
std::vector<std::string> stages;
stages.push_back("shadowcast");
light->extractView(*view, stages);
}
switch(light->getType())
{
case Light::LightType::DIRECTIONAL:
{
_directionalLights.pushBack(light);
break;
}
case Light::LightType::POINT:
{
_pointLights.pushBack(light);
break;
}
case Light::LightType::SPOT:
{
_spotLights.pushBack(light);
break;
}
case Light::LightType::AMBIENT:
{
_ambientLights.pushBack(light);
break;
}
}
}
if (lights.size() > 0)
{
updateDefines();
}
_numLights = lights.size();
}
void ForwardRenderer::updateDefines()
{
_defines.emplace(std::make_pair("CC_NUM_DIR_LIGHTS", Value(std::min(4, (int)_directionalLights.size()))));
_defines.emplace(std::make_pair("CC_NUM_POINT_LIGHTS", Value(std::min(4, (int)_pointLights.size()))));
_defines.emplace(std::make_pair("CC_NUM_SPOT_LIGHTS", Value(std::min(4, (int)_spotLights.size()))));
_defines.emplace(std::make_pair("CC_NUM_AMBIENT_LIGHTS", Value(std::min(4, (int)_ambientLights.size()))));
_defines.emplace(std::make_pair("CC_NUM_SHADOW_LIGHTS", Value(std::min(4, (int)_shadowLights.size()))));
}
void ForwardRenderer::submitLightsUniforms()
{
if (_directionalLights.size() > 0)
{
size_t count = _directionalLights.size();
float* directions = _arrayPool->add();
float* colors = _arrayPool->add();
Vec3 lightVec3;
Vec3 colorVec3;
for (int i = 0; i < count; ++i)
{
int index = i * 4;
auto* light = _directionalLights.at(i);
lightVec3.set(light->getDirectionUniform());
*(directions + index) = lightVec3.x;
*(directions + index + 1) = lightVec3.y;
*(directions + index + 2) = lightVec3.z;
*(directions + index + 3) = 0;
colorVec3.set(light->getColorUniform());
*(colors + index) = colorVec3.x;
*(colors + index + 1) = colorVec3.y;
*(colors + index + 2) = colorVec3.z;
*(colors + index + 3) = 0;
}
_device->setUniformfv("cc_dirLightDirection", count * 4, directions);
_device->setUniformfv("cc_dirLightColor", count * 4, colors);
}
if (_pointLights.size() > 0)
{
size_t count = _pointLights.size();
float* positionAndRanges = _arrayPool->add();
float* colors = _arrayPool->add();
Vec3 posVec3;
Vec3 colorVec3;
for (int i = 0; i < count; ++i)
{
int index = i * 4;
auto* light = _pointLights.at(i);
posVec3.set(light->getPositionUniform());
*(positionAndRanges + index) = posVec3.x;
*(positionAndRanges + index + 1) = posVec3.y;
*(positionAndRanges + index + 2) = posVec3.z;
*(positionAndRanges + index + 3) = light->getRange();
colorVec3.set(light->getColorUniform());
*(colors + index) = colorVec3.x;
*(colors + index + 1) = colorVec3.y;
*(colors + index + 2) = colorVec3.z;
*(colors + index + 3) = 0;
}
_device->setUniformfv("cc_pointLightPositionAndRange", count * 4, positionAndRanges);
_device->setUniformfv("cc_pointLightColor", count * 4, colors);
}
if (_spotLights.size() > 0)
{
size_t count = _spotLights.size();
float* directions = _arrayPool->add();
float* positionAndRanges = _arrayPool->add();
float* colors = _arrayPool->add();
Vec3 lightVec3;
Vec3 posVec3;
Vec3 colorVec3;
for (int i = 0; i < count; ++i)
{
int index = i * 4;
auto* light = _spotLights.at(i);
lightVec3.set(light->getDirectionUniform());
*(directions + index) = lightVec3.x;
*(directions + index + 1) = lightVec3.y;
*(directions + index + 2) = lightVec3.z;
*(directions + index + 3) = 0;
posVec3.set(light->getPositionUniform());
*(positionAndRanges + index) = posVec3.x;
*(positionAndRanges + index + 1) = posVec3.y;
*(positionAndRanges + index + 2) = posVec3.z;
*(positionAndRanges + index + 3) = light->getRange();
colorVec3.set(light->getColorUniform());
*(colors + index) = colorVec3.x;
*(colors + index + 1) = colorVec3.y;
*(colors + index + 2) = colorVec3.z;
*(colors + index + 3) = 0;
}
_device->setUniformfv("cc_spotLightDirection", count * 4, directions);
_device->setUniformfv("cc_spotLightPositionAndRange", count * 4, positionAndRanges);
_device->setUniformfv("cc_spotLightColor", count * 4, colors);
}
if (_ambientLights.size() > 0) {
size_t count = _ambientLights.size();
float* colors = _arrayPool->add();
Vec3 colorVec3;
for (int i = 0; i < count; ++i)
{
int index = i * 4;
auto* light = _ambientLights.at(i);
colorVec3.set(light->getColorUniform());
*(colors + index) = colorVec3.x;
*(colors + index + 1) = colorVec3.y;
*(colors + index + 2) = colorVec3.z;
*(colors + index + 3) = 0;
}
_device->setUniformfv("cc_pointLightColor", count * 4, colors);
}
}
void ForwardRenderer::submitShadowStageUniforms(const View& view)
{
static float* shadowInfo = new float[4];
shadowInfo[0] = view.shadowLight->getShadowMinDepth();
shadowInfo[1] = view.shadowLight->getShadowMaxDepth();
shadowInfo[2] = view.shadowLight->getShadowDepthScale();
shadowInfo[3] = view.shadowLight->getShadowDarkness();
_device->setUniformMat4("cc_shadow_map_lightViewProjMatrix", view.matViewProj);
_device->setUniformfv("cc_shadow_map_info", 4, shadowInfo);
_device->setUniformf("cc_shadow_map_bias", view.shadowLight->getShadowBias());
}
void ForwardRenderer::submitOtherStagesUniforms()
{
size_t count = _shadowLights.size();
float* shadowLightInfo = _arrayPool->add();
static float* shadowLightProjs = new float[count * 16];
for (int i = 0; i < count; ++i)
{
int index = i * 4;
Light* light = _shadowLights.at(i);
const Mat4 view = light->getViewProjMatrix();
memcpy(shadowLightProjs + index, view.m, 16);
*(shadowLightInfo + index) = light->getShadowMinDepth();
*(shadowLightInfo + index + 1) = light->getShadowMaxDepth();
*(shadowLightInfo + index + 2) = light->getShadowDepthScale();
*(shadowLightInfo + index + 3) = light->getShadowDarkness();
}
_device->setUniformfv("cc_shadow_lightViewProjMatrix", count * 16, shadowLightProjs);
_device->setUniformfv("cc_shadow_info", count * 4, shadowLightInfo);
}
void ForwardRenderer::updateShaderDefines(const StageItem& item)
{
item.defines->push_back(&_defines);
}
bool ForwardRenderer::compareItems(const StageItem &a, const StageItem &b)
{
const Technique* techA = a.technique;
const Technique* techB = b.technique;
if (techA->getLayer() != techB->getLayer()) {
return techA->getLayer() > techB->getLayer();
}
size_t pa = techA->getPasses().size();
size_t pb = techB->getPasses().size();
if (pa != pb) {
return pa > pb;
}
return a.sortKey > b.sortKey;
}
void ForwardRenderer::sortItems(std::vector<StageItem>& items)
{
std::sort(items.begin(), items.end(), compareItems);
}
void ForwardRenderer::drawItems(const std::vector<StageItem>& items)
{
size_t count = _shadowLights.size();
if (count == 0 && _numLights == 0)
{
for (const auto& item : items)
{
draw(item);
}
}
else
{
std::vector<Texture*> shadowMaps;
shadowMaps.reserve(count);
std::vector<int> slots;
slots.reserve(count);
for (auto item : items)
{
shadowMaps.clear();
for(int i = 0; i < count; i++)
{
Light* light = _shadowLights.at(i);
shadowMaps.push_back(light->getShadowMap());
slots.push_back(allocTextureUnit());
}
_device->setTextureArray("cc_shadow_map", shadowMaps, slots);
updateShaderDefines(item);
draw(item);
}
}
}
void ForwardRenderer::opaqueStage(const View& view, const std::vector<StageItem>& items)
{
// update uniforms
_device->setUniformMat4("cc_matView", view.matView);
_device->setUniformMat4("cc_matpProj", view.matProj);
_device->setUniformMat4("cc_matViewProj", view.matViewProj);
static Vec3 cameraPos3;
static Vec4 cameraPos4;
view.getPosition(cameraPos3);
cameraPos4.set(cameraPos3.x, cameraPos3.y, cameraPos3.z, 0);
_device->setUniformVec4("cc_cameraPos", cameraPos4);
submitLightsUniforms();
submitOtherStagesUniforms();
drawItems(items);
}
void ForwardRenderer::shadowStage(const View& view, const std::vector<StageItem>& items)
{
// update rendering
submitShadowStageUniforms(view);
for (auto& item : items)
{
if (_programLib->getValueFromDefineList("CC_SHADOW_CASTING", *item.defines) != Value::Null) {
updateShaderDefines(item);
draw(item);
}
}
}
void ForwardRenderer::transparentStage(const View& view, const std::vector<StageItem>& items)
{
// update uniforms
_device->setUniformMat4("view", view.matView);
_device->setUniformMat4("proj", view.matProj);
_device->setUniformMat4("viewProj", view.matViewProj);
// RENDERER_LOGD("StageItem count: %d", (int)items.size());
// draw it
for (const auto& item : items)
draw(item);
_device->setUniformMat4("cc_matView", view.matView);
_device->setUniformMat4("cc_matpProj", view.matProj);
_device->setUniformMat4("cc_matViewProj", view.matViewProj);
static Vec3 cameraPos3;
static Vec4 cameraPos4;
view.getPosition(cameraPos3);
cameraPos4.set(cameraPos3.x, cameraPos3.y, cameraPos3.z, 0);
_device->setUniformVec4("cc_cameraPos", cameraPos4);
static Vec3 camFwd;
static Vec3 tmpVec3;
view.getForward(camFwd);
submitLightsUniforms();
submitOtherStagesUniforms();
NodeProxy* node;
// calculate zdist
for (auto& item : const_cast<std::vector<StageItem>&>(items))
{
// TODO: we should use mesh center instead!
node = const_cast<NodeProxy*>(item.model->getNode());
if (node != nullptr)
{
node->getWorldPosition(&tmpVec3);
}
else
{
tmpVec3.set(0, 0, 0);
}
Vec3::subtract(tmpVec3, tmpVec3, &cameraPos3);
item.sortKey = -Vec3::dot(tmpVec3, camFwd);
}
sortItems(const_cast<std::vector<StageItem>&>(items));
drawItems(items);
}
RENDERER_END
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -25,22 +25,74 @@
#pragma once
#include "BaseRenderer.h"
#include "Camera.h"
#include "../memop/RecyclePool.hpp"
RENDERER_BEGIN
/**
* @addtogroup renderer
* @{
*/
/**
* @brief A builtin forward renderer implementation
*/
class ForwardRenderer final : public BaseRenderer
{
public:
/**
* @brief The default constructor.
*/
ForwardRenderer();
~ForwardRenderer();
/**
* @brief Initializes the forward renderer.
* @param[in] device DeviceGraphics pointer.
* @param[in] programTemplates All linked programs.
* @param[in] defaultTexture Default texture pointer.
* @param[in] width.
* @param[in] height.
*/
bool init(DeviceGraphics* device, std::vector<ProgramLib::Template>& programTemplates, Texture2D* defaultTexture, int width, int height);
/**
* @brief Renders the given render scene.
*/
void render(Scene* scene);
/**
* @brief Renders the given render scene with a given camera setting.
*/
void renderCamera(Camera* camera, Scene* scene);
private:
void updateLights(Scene* scene);
void updateDefines();
void submitLightsUniforms();
void submitShadowStageUniforms(const View& view);
void submitOtherStagesUniforms();
void updateShaderDefines(const StageItem& item);
void sortItems(std::vector<StageItem>& items);
void drawItems(const std::vector<StageItem>& items);
void opaqueStage(const View& view, const std::vector<StageItem>& items);
void shadowStage(const View& view, const std::vector<StageItem>& items);
void transparentStage(const View& view, const std::vector<StageItem>& items);
void resetData();
static bool compareItems(const StageItem& a, const StageItem& b);
Vector<Light*> _directionalLights;
Vector<Light*> _pointLights;
Vector<Light*> _spotLights;
Vector<Light*> _shadowLights;
Vector<Light*> _ambientLights;
RecyclePool<float>* _arrayPool = nullptr;
ValueMap _defines;
int _width = 0;
int _height = 0;
std::size_t _numLights = 0;
};
// end of renderer group
/// @}
RENDERER_END
@@ -48,6 +48,18 @@ InputAssembler::~InputAssembler()
RENDERER_SAFE_RELEASE(_indexBuffer);
}
void InputAssembler::clear()
{
CC_SAFE_RELEASE(_vertexBuffer);
CC_SAFE_RELEASE(_indexBuffer);
_vertexBuffer = nullptr;
_indexBuffer = nullptr;
_primitiveType = PrimitiveType::TRIANGLES;
_start = 0;
_count = -1;
}
InputAssembler& InputAssembler::operator=(const InputAssembler& o)
{
CC_SAFE_RELEASE(_vertexBuffer);
@@ -78,6 +90,8 @@ InputAssembler& InputAssembler::operator=(InputAssembler&& o)
o._indexBuffer = nullptr;
o._vertexBuffer = nullptr;
o._start = 0;
o._count = -1;
return *this;
}
@@ -118,4 +132,13 @@ uint32_t InputAssembler::getPrimitiveCount() const
return _vertexBuffer->getCount();
}
bool InputAssembler::isMergeable(const InputAssembler& ia) const
{
if (_indexBuffer != ia._indexBuffer || _vertexBuffer != ia._vertexBuffer)
{
return false;
}
return (_start + _count) == ia._start;
}
RENDERER_END
@@ -32,6 +32,14 @@ RENDERER_BEGIN
class VertexBuffer;
class IndexBuffer;
/**
* @addtogroup renderer
* @{
*/
/**
* @brief InputAssembler is an fundamental data structure to store vertex buffer and index buffer.
*/
class InputAssembler
{
public:
@@ -43,24 +51,66 @@ public:
InputAssembler& operator=(const InputAssembler& o);
InputAssembler& operator=(InputAssembler&& o);
/**
* @brief Initializes with vertex buffer, index buffer and primitive type.
*/
bool init(VertexBuffer* vb,
IndexBuffer* ib,
PrimitiveType pt = PrimitiveType::TRIANGLES);
/**
* @brief Gets the primitive count.
*/
uint32_t getPrimitiveCount() const;
/**
* @brief Sets the vertex buffer.
*/
void setVertexBuffer(VertexBuffer* vb);
/**
* @brief Gets the vertex buffer.
*/
inline VertexBuffer* getVertexBuffer() const { return _vertexBuffer; }
/**
* @brief Sets the index buffer.
*/
void setIndexBuffer(IndexBuffer* ib);
/**
* @brief Gets the index buffer.
*/
inline IndexBuffer* getIndexBuffer() const { return _indexBuffer; }
/**
* @brief Sets the index offset in buffer.
*/
inline void setStart(int start) { _start = start; }
/**
* @brief Gets the index offset in buffer.
*/
inline int getStart() const { return _start; }
/**
* @brief Sets the count of indices.
*/
inline void setCount(int count) { _count = count; }
/**
* @brief Gets the count of indices.
*/
inline int getCount() const { return _count; }
/**
* @brief Gets the primitive type.
*/
inline PrimitiveType getPrimitiveType() const { return _primitiveType; }
/**
* @brief Sets the primitive type.
*/
inline void setPrimitiveType(PrimitiveType type) { _primitiveType = type; }
/**
* @brief Clears all field.
*/
void clear();
/**
* @brief Can be merge.
*/
bool isMergeable(const InputAssembler& ia) const;
private:
friend class BaseRenderer;
@@ -71,4 +121,6 @@ private:
int _count = -1;
};
// end of renderer group
/// @}
RENDERER_END
+2 -2
View File
@@ -164,7 +164,7 @@ void Light::update(DeviceGraphics* device)
void Light::updateLightPositionAndDirection()
{
_worldMatrix.transformVector(Vec3(0, 0, -1.f), &_directionUniform);
_worldMatrix.transformVector(_forward, &_directionUniform);
_positionUniform.set(_worldMatrix.m[12], _worldMatrix.m[13], _worldMatrix.m[14]);
}
@@ -197,7 +197,7 @@ void Light::generateShadowMap(DeviceGraphics* device)
Texture2D::Options options;
options.width = _shadowResolution;
options.height = _shadowResolution;
// options.format = Texture2D::Format::RGBA8;
options.glFormat = GL_RGBA;
options.wrapS = Texture2D::WrapMode::CLAMP;
options.wrapT = Texture2D::WrapMode::CLAMP;
_shadowMap->init(device, options);
+171 -21
View File
@@ -39,78 +39,223 @@ class Texture2D;
class RenderBuffer;
class DeviceGraphics;
/**
* @addtogroup renderer
* @{
*/
/**
* @brief Manage scene light.
*/
class Light : public Ref
{
public:
/**
* @brief Light type.
*/
enum class LightType
{
/**
* Directional light
*/
DIRECTIONAL,
/**
* Point light
*/
POINT,
SPOT
/**
* Spot light
*/
SPOT,
/**
* Ambient light
*/
AMBIENT
};
/**
* @brief Shadow type.
*/
enum class ShadowType
{
/**
* No shadow
*/
NONE,
/**
* Hard shadow
*/
HARD,
/**
* Soft shadow
*/
SOFT
};
/**
* @brief The default constructor.
*/
Light();
/**
* @brief Sets the light color.
*/
void setColor(float r, float g, float b);
/**
* @brief Gets the light color.
*/
inline Color3F getColor() const { return _color; }
/**
* @brief Sets the light intensity.
*/
void setIntensity(float val);
/**
* @brief Gets the light intensity.
*/
inline float getIntensity() const { return _intensity; }
/**
* @brief Sets the light type.
*/
inline void setType(LightType type) { _type = type; }
/**
* @brief Gets the light type.
*/
inline LightType getType() const { return _type; }
/**
* @brief Sets the spot light angle.
*/
void setSpotAngle(float val);
/**
* @brief Gets the spot light angle.
*/
inline float getSpotAngle() const { return _spotAngle; }
/**
* @brief Sets the light attenuation exponent.
*/
void setSpotExp(float val);
/**
* @brief Gets the light attenuation exponent.
*/
inline float getSpotExp() const { return _spotExp; }
/**
* @brief Sets spot or point light range.
*/
inline void setRange(float val) { _range = val; }
/**
* @brief Gets spot or point light range.
*/
inline float getRange() const { return _range; }
/**
* @brief Gets the shadow type.
*/
void setShadowType(ShadowType val);
/**
* @brief Gets the shadow type.
*/
inline ShadowType getShadowType() const { return _shadowType; }
/**
* @brief Gets the shadow map texture.
*/
inline Texture2D* getShadowMap() const { return _shadowMap; }
/**
* @brief Gets the view projection matrix.
*/
inline Mat4 getViewPorjMatrix() const { return _viewProjMatrix; }
/**
* @brief Gets the view projection matrix.
*/
inline const Mat4& getViewProjMatrix() const { return _viewProjMatrix; }
/**
* @brief Gets the direction uniform.
*/
inline const Vec3& getDirectionUniform() const { return _directionUniform; }
/**
* @brief Gets the color uniform.
*/
inline const Vec3& getColorUniform() const { return _colorUniform; }
/**
* @brief Gets the position uniform.
*/
inline const Vec3& getPositionUniform() const { return _positionUniform; }
/**
* @brief Sets the resolution of shadow
*/
void setShadowResolution(uint32_t val);
/**
* @brief Gets the resolution of shadow
*/
inline uint32_t getShadowResolution() const { return _shadowResolution; }
/**
* @brief Sets the shadow bias setting.
*/
inline void setShadowBias(float val) { _shadowBias = val; }
/**
* @brief Gets the shadow bias setting.
*/
inline float getShadowBias() const { return _shadowBias; }
/**
* @brief Sets the shadow darkness setting.
*/
inline void setShadowDarkness(float val) { _shadowDarkness = val; }
/**
* @brief Gets the shadow darkness setting.
*/
inline float getShadowDarkness() const { return _shadowDarkness; }
inline void setShadowDarkness(uint32_t val) { _shadowDarkness = val; }
inline uint32_t getShadowDarkness() const { return _shadowDarkness; }
/**
* @brief Sets the min depth of shadow.
*/
inline void setShadowMinDepth(float val) { _shadowMinDepth = val; }
/**
* @brief Gets the min depth of shadow.
*/
float getShadowMinDepth() const;
/**
* @brief Sets the max depth of shadow.
*/
inline void setShadowMaxDepth(float val) { _shadowMaxDepth = val; }
/**
* @brief Gets the max depth of shadow.
*/
float getShadowMaxDepth() const;
inline void setShadowScale(float val) { _shadowScale = val; }
inline float getShadowScale() const { return _shadowScale; }
/**
* @brief Sets the shadow scale.
*/
inline void setShadowDepthScale(float val) { _shadowScale = val; }
/**
* @brief Gets the shadow scale.
*/
inline float getShadowDepthScale() const { return _shadowScale; }
/**
* @brief Sets the frustum edge fall off.
*/
inline void setFrustumEdgeFalloff(uint32_t val) { _frustumEdgeFalloff = val; }
/**
* @brief Gets the frustum edge fall off.
*/
inline uint32_t getFrustumEdgeFalloff() const { return _frustumEdgeFalloff; }
/**
* @brief Sets the world matrix.
*/
void setWorldMatrix(const Mat4& worldMatrix);
/**
* @brief Gets the world matrix.
*/
inline const Mat4& getWorldMatrix() const { return _worldMatrix; }
/**
* @brief Extract light informations to view.
*/
void extractView(View& out, const std::vector<std::string>& stages);
/**
* @brief Update light and generate new shadow map.
*/
void update(DeviceGraphics* device);
/**
* @brief Sets the shadow frustum size.
*/
inline void setShadowFrustumSize(float val) {_shadowFustumSize = val;};
private:
void updateLightPositionAndDirection();
@@ -150,10 +295,15 @@ private:
uint32_t _frustumEdgeFalloff = 0; // used by directional and spot light.
Mat4 _viewProjMatrix;
float _spotAngleScale = 1; // used for spot light.
uint32_t _shadowFustumSize = 80; // used for directional light.
float _shadowFustumSize = 50; // used for directional light.
Mat4 _worldMatrix;
Mat4 _worldRT;
Vec3 _forward = Vec3(0, 0, -1.f);
};
// end of renderer group
/// @}
RENDERER_END
+48 -46
View File
@@ -25,6 +25,8 @@
#include "Model.h"
#include "Effect.h"
#include "InputAssembler.h"
#include "../scene/NodeProxy.hpp"
#include "../gfx/VertexBuffer.h"
RENDERER_BEGIN
@@ -61,78 +63,78 @@ void ModelPool::returnModel(Model *model)
Model::Model()
{
// RENDERER_LOGD("Model construction %p", this);
_inputAssemblers.reserve(500);
}
Model::~Model()
{
RENDERER_LOGD("Model destruction %p", this);
reset();
}
void Model::setInputAssembler(const InputAssembler& ia)
{
_inputAssembler = ia;
}
void Model::setEffect(Effect* effect, CustomProperties* customProperties)
{
if (_effect != effect)
{
CC_SAFE_RELEASE(_effect);
_effect = effect;
CC_SAFE_RETAIN(_effect);
}
ccCArrayFree(_effects);
}
void Model::addInputAssembler(const InputAssembler& ia)
{
_inputAssemblers.push_back(std::move(ia));
}
void Model::clearInputAssemblers()
{
_inputAssemblers.clear();
}
void Model::addEffect(Effect* effect)
{
if (ccCArrayContainsValue(_effects, effect))
return;
_uniforms.clear();
ccCArrayAppendValue(_effects, effect);
if (effect != nullptr)
{
_definesList.push_back(effect->extractDefines());
_uniforms.push_back(effect->extractProperties());
}
_defines.push_back(effect->extractDefines());
if (customProperties != nullptr)
{
_definesList.push_back(customProperties->extractDefines());
_uniforms.push_back(customProperties->extractProperties());
}
}
void Model::clearEffects()
void Model::setNode(NodeProxy* node)
{
ccCArrayRemoveAllValues(_effects);
_defines.clear();
if (_node != node)
{
CC_SAFE_RELEASE(_node);
_node = node;
CC_SAFE_RETAIN(_node);
}
}
void Model::extractDrawItem(DrawItem& out, uint32_t index) const
void Model::extractDrawItem(DrawItem& out) const
{
if (_dynamicIA)
{
out.model = const_cast<Model*>(this);
out.ia = nullptr;
out.effect = static_cast<Effect*>(_effects->arr[0]);
out.defines = out.effect->extractDefines();
out.effect = _effect;
out.defines = const_cast<std::vector<ValueMap*>*>(&_definesList);
return;
}
if (index >= _inputAssemblers.size())
return;
out.model = const_cast<Model*>(this);
out.ia = const_cast<InputAssembler*>(&(_inputAssemblers[index]));
auto effectsSize = _effects->num;
if (index >= effectsSize)
index = (uint32_t)(effectsSize - 1);
out.effect = static_cast<Effect*>(_effects->arr[index]);
out.defines = out.effect->extractDefines();
out.ia = const_cast<InputAssembler*>(&_inputAssembler);
out.effect = _effect;
out.defines = const_cast<std::vector<ValueMap*>*>(&_definesList);
out.uniforms = const_cast<std::vector<std::unordered_map<std::string, Effect::Property>*>*>(&_uniforms);
}
void Model::reset()
{
ccCArrayRemoveAllValues(_effects);
_inputAssemblers.clear();
_defines.clear();
CC_SAFE_RELEASE_NULL(_effect);
CC_SAFE_RELEASE_NULL(_node);
_inputAssembler.clear();
_uniforms.clear();
_definesList.clear();
}
RENDERER_END
+73 -25
View File
@@ -31,20 +31,29 @@
#include "base/ccCArray.h"
#include "math/Mat4.h"
#include "../Macro.h"
#include "InputAssembler.h"
#include "../gfx/DeviceGraphics.h"
#include "CustomProperties.hpp"
#include "../scene/NodeProxy.hpp"
RENDERER_BEGIN
class Effect;
class InputAssembler;
class Model;
class INode;
/**
* @addtogroup renderer
* @{
*/
struct DrawItem
{
Model* model = nullptr;
InputAssembler* ia = nullptr;
Effect* effect = nullptr;
ValueMap* defines = nullptr;
std::vector<ValueMap*>* defines = nullptr;
std::vector<std::unordered_map<std::string, Effect::Property>*>* uniforms = nullptr;
};
class Model;
@@ -59,41 +68,80 @@ private:
static ccCArray* _pool;;
};
/**
* @brief Model contains InputAssembler, effect, culling mask and model matrix.
*/
class Model
{
public:
/**
* @brief The default constructor.
*/
Model();
/**
* @brief The default destructor.
*/
~Model();
inline uint32_t getInputAssemblerCount() const { return (uint32_t)_inputAssemblers.size(); }
inline bool isDynamicIA() const { return _dynamicIA; }
inline void setDynamicIA(bool value) { _dynamicIA = value; }
inline uint32_t getDrawItemCount() const { return _dynamicIA ? 1 : (uint32_t)_inputAssemblers.size(); }
inline void setWorldMatix(const Mat4& matrix) { _worldMatrix = std::move(matrix); }
/**
* @brief Sets model matrix.
*/
inline void setWorldMatix(const Mat4& matrix) { _worldMatrix = matrix; }
/**
* @brief Gets mode matrix.
*/
inline const Mat4& getWorldMatrix() const { return _worldMatrix; }
inline void setViewId(int val) { _viewID = val; }
inline int getViewId() const { return _viewID; }
void addInputAssembler(const InputAssembler& ia);
void clearInputAssemblers();
void addEffect(Effect* effect);
void clearEffects();
void extractDrawItem(DrawItem& out, uint32_t index) const;
/**
* @brief Sets culling mask.
*/
inline void setCullingMask(int val) { _cullingMask = val; }
/**
* @brief Gets culling mask.
*/
inline int getCullingMask() const { return _cullingMask; }
/**
* @brief Adds a input assembler.
*/
void setInputAssembler(const InputAssembler& ia);
/**
* @brief Adds an effect.
*/
void setEffect(Effect* effect, CustomProperties* customProperties);
/**
* @brief Set user key.
*/
inline void setUserKey(int key) { _userKey = key; };
/**
* @brief Set node.
*/
void setNode(NodeProxy* node);
/**
* @brief Get node.
*/
inline const NodeProxy* getNode() const { return _node; };
/**
* @brief Extract draw item for the given index during rendering process.
*/
void extractDrawItem(DrawItem& out) const;
/**
* @brief Resets models.
*/
void reset();
private:
friend class ModelPool;
void reset();
NodeProxy* _node = nullptr;
Mat4 _worldMatrix;
ccCArray* _effects = ccCArrayNew(2);
Effect* _effect = nullptr;
std::vector<InputAssembler> _inputAssemblers;
std::vector<ValueMap*> _defines;
InputAssembler _inputAssembler;
std::vector<ValueMap*> _definesList;
std::vector<std::unordered_map<std::string, Effect::Property>*> _uniforms;
bool _dynamicIA = false;
int _viewID = -1;
int _cullingMask = -1;
int _userKey = -1;
};
// end of renderer group
/// @}
RENDERER_END
+43
View File
@@ -103,4 +103,47 @@ void Pass::setStencilBack(StencilFunc stencilFunc,
_stencilWriteMaskBack = stencilWriteMask;
}
void Pass::copy(const Pass& pass)
{
// blending
_blend = pass._blend;
_blendEq = pass._blendEq;
_blendAlphaEq = pass._blendAlphaEq;
_blendSrc = pass._blendSrc;
_blendDst = pass._blendDst;
_blendSrcAlpha = pass._blendSrcAlpha;
_blendDstAlpha = pass._blendDstAlpha;
_blendColor = pass._blendColor;
// depth
_depthTest = pass._depthTest;
_depthWrite = pass._depthWrite;
_depthFunc = pass._depthFunc;
// stencil
_stencilTest = pass._stencilTest;
// front
_stencilRefFront = pass._stencilRefFront;
_stencilFuncFront = pass._stencilFuncFront;
_stencilFailOpFront = pass._stencilFailOpFront;
_stencilZFailOpFront = pass._stencilZFailOpFront;
_stencilZPassOpFront = pass._stencilZPassOpFront;
_stencilWriteMaskFront = pass._stencilWriteMaskFront;
_stencilMaskFront = pass._stencilMaskFront;
// back
_stencilRefBack = pass._stencilRefBack;
_stencilFuncBack = pass._stencilFuncBack;
_stencilFailOpBack = pass._stencilFailOpBack;
_stencilZFailOpBack = pass._stencilZFailOpBack;
_stencilZPassOpBack = pass._stencilZPassOpBack;
_stencilWriteMaskBack = pass._stencilWriteMaskBack;
_stencilMaskBack = pass._stencilMaskBack;
// cull mode
_cullMode = pass._cullMode;
_programName = pass._programName;
}
RENDERER_END
+77 -6
View File
@@ -31,14 +31,52 @@
RENDERER_BEGIN
/**
* @addtogroup renderer
* @{
*/
/**
* @brief Pass describes base render pass configurations, including program, cull face, blending, depth testing and stencil testing configs.\n
* JS API: renderer.Pass
* @code
* let pass = new renderer.Pass('sprite');
* pass.setDepth(false, false);
* pass.setCullMode(gfx.CULL_NONE);
* pass.setBlend(
* gfx.BLEND_FUNC_ADD,
* gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA,
* gfx.BLEND_FUNC_ADD,
* gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA
* );
* @endcode
*/
class Pass : public Ref
{
public:
/**
* @brief Constructor with linked program name.
* @param[in] programName Shader program name
*/
Pass(const std::string& programName);
Pass() {}
Pass() {};
~Pass();
/**
* @brief Sets cull mode.
* @param[in] cullMode Cull front or back or both.
*/
void setCullMode(CullMode cullMode);
/**
* @brief Sets blend mode.
* @param[in] blendEq RGB blend equation.
* @param[in] blendSrc Src RGB blend factor.
* @param[in] blendDst Dst RGB blend factor.
* @param[in] blendAlphaEq Alpha blend equation.
* @param[in] blendSrcAlpha Src Alpha blend equation.
* @param[in] blendDstAlpha Dst Alpha blend equation.
* @param[in] blendColor Blend constant color value.
*/
void setBlend(BlendOp blendEq = BlendOp::ADD,
BlendFactor blendSrc = BlendFactor::ONE,
BlendFactor blendDst = BlendFactor::ZERO,
@@ -46,9 +84,18 @@ public:
BlendFactor blendSrcAlpha = BlendFactor::ONE,
BlendFactor blendDstAlpha = BlendFactor::ZERO,
uint32_t blendColor = 0xffffffff);
/**
* @brief Switch depth test or write, and sets depth test function.
* @param[in] depthTest Enable depth test or not.
* @param[in] depthWrite Enable depth write or not.
* @param[in] depthFunc Depth test function.
*/
void setDepth(bool depthTest = false,
bool depthWrite = false,
DepthFunc depthFunc = DepthFunc::LESS);
/**
* @brief Sets stencil front-facing function, reference, mask, fail operation, write mask.
*/
void setStencilFront(StencilFunc stencilFunc = StencilFunc::ALWAYS,
uint32_t stencilRef = 0,
uint8_t stencilMask = 0xff,
@@ -56,6 +103,9 @@ public:
StencilOp stencilZFailOp = StencilOp::KEEP,
StencilOp stencilZPassOp = StencilOp::KEEP,
uint8_t stencilWriteMask = 0xff);
/**
* @brief Sets stencil back-facing function, reference, mask, fail operation, write mask.
*/
void setStencilBack(StencilFunc stencilFunc = StencilFunc::ALWAYS,
uint32_t stencilRef = 0,
uint8_t stencilMask = 0xff,
@@ -63,10 +113,30 @@ public:
StencilOp stencilZFailOp = StencilOp::KEEP,
StencilOp stencilZPassOp = StencilOp::KEEP,
uint8_t stencilWriteMask = 0xff);
/*
* @brief Sets stencil test enabled or not.
*/
inline void setStencilTest(bool value) { _stencilTest = value; }
/**
* @brief Gets stencil test enabled or not.
*/
inline bool getStencilTest() const { return _stencilTest; }
/**
* @brief Sets linked program name.
*/
inline void setProgramName(const std::string& programName) { _programName = programName; }
/**
* @brief Gets linked program name.
*/
inline std::string getProgramName() const { return _programName; }
/**
* @brief Disable stencil test.
*/
inline void disableStencilTest() { _stencilTest = false; }
/**
* @brief deep copy from other pass.
*/
void copy(const Pass& pass);
private:
friend class BaseRenderer;
@@ -75,10 +145,10 @@ private:
bool _blend = false;
BlendOp _blendEq = BlendOp::ADD;
BlendOp _blendAlphaEq = BlendOp::ADD;
BlendFactor _blendSrc = BlendFactor::ONE;
BlendFactor _blendDst = BlendFactor::ZERO;
BlendFactor _blendSrcAlpha = BlendFactor::ONE;
BlendFactor _blendDstAlpha = BlendFactor::ZERO;
BlendFactor _blendSrc = BlendFactor::SRC_ALPHA;
BlendFactor _blendDst = BlendFactor::ONE_MINUS_SRC_ALPHA;
BlendFactor _blendSrcAlpha = BlendFactor::SRC_ALPHA;
BlendFactor _blendDstAlpha = BlendFactor::ONE_MINUS_SRC_ALPHA;
uint32_t _blendColor = 0xffffffff;
// depth
@@ -87,7 +157,6 @@ private:
DepthFunc _depthFunc = DepthFunc::LESS;
// stencil
bool _stencilTest = false;
// front
uint32_t _stencilRefFront = 0;
@@ -112,4 +181,6 @@ private:
std::string _programName = "";
};
// end of renderer group
/// @}
RENDERER_END
+161 -44
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -21,7 +21,6 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "ProgramLib.h"
#include "../gfx/Program.h"
#include "gfx/DeviceGraphics.h"
@@ -34,36 +33,67 @@
namespace {
uint32_t _shdID = 0;
std::string generateDefines(const cocos2d::ValueMap& defMap)
std::string generateDefines(const std::vector<cocos2d::ValueMap*>& definesList)
{
std::string ret;
for (const auto& def : defMap)
{
if (def.second.asBool())
{
ret += "#define " + def.first + "\n";
}
}
return ret;
}
std::string replaceMacroNums(const std::string str, const cocos2d::ValueMap& defMap)
{
std::string v;
cocos2d::ValueMap cache;
std::string tmp = str;
for (const auto& def : defMap)
for (int i = (int)definesList.size() - 1; i >= 0; i--)
{
if (def.second.getType() == cocos2d::Value::Type::INTEGER || def.second.getType() == cocos2d::Value::Type::UNSIGNED)
cocos2d::ValueMap* defMap = definesList[i];
for (const auto& def : *defMap)
{
if (cache.find(def.first) != cache.end())
{
continue;
}
if (def.second.getType() == cocos2d::Value::Type::BOOLEAN)
{
v = def.second.asBool() ? "1" : "0";
}
else
{
v = std::to_string(def.second.asUnsignedInt());
}
ret += "#define " + def.first + " " + v + "\n";
cache.emplace(def.first, def.second);
}
}
return ret;
}
std::string replaceMacroNums(const std::string str, const std::vector<cocos2d::ValueMap*>& definesList)
{
cocos2d::ValueMap cache;
std::string tmp = str;
for (int i = (int)definesList.size() - 1; i >= 0; i--)
{
cocos2d::ValueMap* defMap = definesList[i];
for (const auto& def : *defMap)
{
if (cache.find(def.first) != cache.end())
{
continue;
}
if (def.second.getType() == cocos2d::Value::Type::INTEGER || def.second.getType() == cocos2d::Value::Type::UNSIGNED)
{
cache.emplace(def.first, def.second);
}
}
}
for (const auto& def : cache)
{
std::regex pattern(def.first);
tmp = std::regex_replace(tmp, pattern, def.second.asString());
}
return tmp;
}
@@ -178,9 +208,57 @@ void ProgramLib::define(const std::string& name, const std::string& vert, const
oneDefMap["_offset"] = offset;
}
std::string newVert = _precision + vert;
std::string newFrag = _precision + frag;
std::string newVert = vert;
std::string newFrag = frag;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
std::string::size_type pos = 0;
pos = newVert.find(_precisionVert);
if (pos != std::string::npos)
{
newVert.replace(pos, strlen(_precisionVert), "");
}
pos = newFrag.find(_precisionFrag);
if (pos != std::string::npos)
{
newFrag.replace(pos, strlen(_precisionFrag), "");
}
while((pos = newVert.find(_mediump)) != std::string::npos)
{
newVert.replace(pos, strlen(_mediump), "");
}
while((pos = newFrag.find(_mediump)) != std::string::npos)
{
newFrag.replace(pos, strlen(_mediump), "");
}
while((pos = newVert.find(_lowp)) != std::string::npos)
{
newVert.replace(pos, strlen(_lowp), "");
}
while((pos = newFrag.find(_lowp)) != std::string::npos)
{
newFrag.replace(pos, strlen(_lowp), "");
}
#else
std::string::size_type pos = 0;
pos = newVert.find(_precisionVert);
if (pos == std::string::npos)
{
newVert = _precisionVertReplace + vert;
}
pos = newVert.find(_precisionFrag);
if (pos == std::string::npos)
{
newFrag = _precisionFragReplace + frag;
}
#endif
// store it
auto& templ = _templates[name];
templ.id = id;
@@ -190,32 +268,44 @@ void ProgramLib::define(const std::string& name, const std::string& vert, const
templ.defines = defines;
}
uint32_t ProgramLib::getKey(const std::string& name, const ValueMap& defines)
std::string ProgramLib::getKey(const std::string& name, const std::vector<ValueMap*>& definesList)
{
auto iter = _templates.find(name);
assert(iter != _templates.end());
auto& tmpl = iter->second;
int32_t key = 0;
for (auto& tmplDefs : tmpl.defines) {
auto& tmplDefMap = tmplDefs.asValueMap();
std::string tempName = tmplDefMap["name"].asString();
auto iter2 = defines.find(tempName);
if (iter2 == defines.end()) {
uint32_t key = 0;
uint32_t offset = 0;
for (const auto& tmpl : iter->second.defines)
{
auto& temp = tmpl.asValueMap();
const Value& value = getValueFromDefineList(temp.find("name")->second.asString(), definesList);
if (value == Value::Null)
{
continue;
}
// const auto& value = iter2->second;
// key |= tmplDefs._map(100); //IDEA:
uint32_t offset = tmplDefMap["_offset"].asUnsignedInt();
key |= 1 << offset;
uint32_t vkey = getValueKey(value);
key |= vkey << offset;
if (value.getType() != Value::Type::BOOLEAN)
{
offset += ceil(log2(vkey));
}
else
{
offset += 1;
}
}
return key << 8 | tmpl.id;
// return key << 8 | tmpl.id;
// key number maybe bigger than 32 bit, need use string to store value.
return std::to_string(iter->second.id) + ":" + std::to_string(key);
}
Program* ProgramLib::getProgram(const std::string& name, const ValueMap& defines)
Program* ProgramLib::getProgram(const std::string& name, const std::vector<ValueMap*>& definesList)
{
uint32_t key = getKey(name, defines);
std::string key = getKey(name, definesList);
auto iter = _cache.find(key);
if (iter != _cache.end()) {
iter->second->retain();
@@ -228,12 +318,12 @@ Program* ProgramLib::getProgram(const std::string& name, const ValueMap& defines
if (templIter != _templates.end())
{
const auto& tmpl = templIter->second;
std::string customDef = generateDefines(defines) + "\n";
std::string vert = replaceMacroNums(tmpl.vert, defines);
std::string customDef = generateDefines(definesList) + "\n";
std::string vert = replaceMacroNums(tmpl.vert, definesList);
vert = customDef + unrollLoops(vert);
std::string frag = replaceMacroNums(tmpl.frag, defines);
std::string frag = replaceMacroNums(tmpl.frag, definesList);
frag = customDef + unrollLoops(frag);
program = new Program();
program->init(_device, vert.c_str(), frag.c_str());
program->link();
@@ -243,4 +333,31 @@ Program* ProgramLib::getProgram(const std::string& name, const ValueMap& defines
return program;
}
Value ProgramLib::getValueFromDefineList(const std::string& name, const std::vector<ValueMap*>& definesList)
{
for (int i = (int)definesList.size() - 1; i >= 0; i--)
{
ValueMap* defines = definesList[i];
auto iter = defines->find(name);
if (iter != defines->end())
{
return iter->second;
}
}
return Value::Null;
}
uint32_t ProgramLib::getValueKey(const Value &v)
{
if (v.getType() == Value::Type::BOOLEAN)
{
return v.asBool() ? 1 : 0;
}
else
{
return v.asUnsignedInt();
}
}
RENDERER_END
+51 -9
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -36,9 +36,20 @@ RENDERER_BEGIN
class DeviceGraphics;
class Program;
/**
* @addtogroup renderer
* @{
*/
/**
* @brief This class manages shader template and linked programs, material can customize shader by setting different defines.
*/
class ProgramLib final
{
public:
/**
* @brief Program template
*/
struct Template
{
uint32_t id = 0;
@@ -48,20 +59,51 @@ public:
ValueVector defines;
};
/**
* @brief Constructor with device and all initial templates.
*/
ProgramLib(DeviceGraphics* device, std::vector<Template>& templates);
/**
* @brief The default destructor.
*/
~ProgramLib();
/**
* @brief Define a new program with name, vertex shader name, fragement shader name and template define settings.
*/
void define(const std::string& name, const std::string& vert, const std::string& frag, ValueVector& defines);
uint32_t getKey(const std::string& name, const ValueMap& defines);
/**
* @brief Gets unique key for the given program name and defines key.
*/
std::string getKey(const std::string& name, const std::vector<ValueMap*>& definesList);
//note: the return value needs to be released by its 'release' method.
Program* getProgram(const std::string& name, const ValueMap& defines);
/**
* @brief Gets program by template name, define settings and defines key.
* @note The return value needs to be released by its 'release' method.
*/
Program* getProgram(const std::string& name, const std::vector<ValueMap*>& definesList);
Value getValueFromDefineList(const std::string& name, const std::vector<ValueMap*>& definesList);
private:
uint32_t getValueKey(const Value& v);
private:
DeviceGraphics* _device = nullptr;
const char* _precision = "#ifdef GL_ES\nprecision highp float;\n#endif\n";
const char* _precisionVert = "precision highp float;";
const char* _precisionVertReplace = "#ifdef GL_ES\nprecision highp float;\n#endif\n";
const char* _precisionFrag = "precision highp float;";
const char* _precisionFragReplace = "#ifdef GL_ES\nprecision mediump float;\n#endif\n";
const char* _mediumpReplace = "half";
const char* _mediump = "mediump";
const char* _lowpReplace = "fixed";
const char* _lowp = "lowp";
std::unordered_map<std::string, Template> _templates;
std::unordered_map<uint32_t, Program*> _cache;
std::unordered_map<std::string, Program*> _cache;
};
// end of renderer group
/// @}
RENDERER_END
+3 -3
View File
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -2,17 +2,17 @@
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+8 -5
View File
@@ -40,7 +40,7 @@ Scene::Scene()
void Scene::reset()
{
for (auto& model : _models)
model->setViewId(-1);
model->setCullingMask(-1);
}
void Scene::setDebugCamera(Camera* debugCamera)
@@ -58,6 +58,13 @@ Camera* Scene::getCamera(uint32_t index) const
return _cameras.at(index);
}
void Scene::sortCameras()
{
std::sort(_cameras.begin(), _cameras.end(), [=](const Camera* a, const Camera* b){
return a->getPriority() < b->getPriority();
});
}
void Scene::addCamera(Camera* camera)
{
_cameras.pushBack(camera);
@@ -83,16 +90,12 @@ void Scene::removeModel(Model* model)
auto iter = std::find(_models.begin(), _models.end(), model);
if (_models.end() != iter)
{
ModelPool::returnModel(model);
_models.erase(iter);
}
}
void Scene::removeModels()
{
for (const auto& model : _models)
ModelPool::returnModel(model);
_models.clear();
}
+104 -9
View File
@@ -36,39 +36,131 @@ class Light;
class Model;
class View;
/**
* @addtogroup renderer
* @{
*/
/**
* @brief Render scene.
*/
class Scene
{
public:
/**
* @brief The default constructor.
*/
Scene();
/**
* @brief Resets all model culling mask.
*/
void reset();
/**
* @brief Sets debug camera.
* @param[in] debugCamera Debug camera pointer.
*/
void setDebugCamera(Camera* debugCamera);
// camera
/**
* @brief Gets cameras count.
* @return Cameras count.
*/
inline uint32_t getCameraCount() const { return (uint32_t)_cameras.size(); }
Camera* getCamera(uint32_t index) const;
void addCamera(Camera* camera);
void removeCamera(Camera* camera);
inline const Vector<Camera*>& getCameras() const { return _cameras; }
// model
/**
* @brief Gets camera by index.
* @return camera pointer.
*/
Camera* getCamera(uint32_t index) const;
/**
* @brief Adds camera.
* @param[in] camera Camera pointer.
*/
void addCamera(Camera* camera);
/**
* @brief Removes camera.
* @param[in] camera Camera pointer.
*/
void removeCamera(Camera* camera);
/**
* @brief Gets all cameras.
* @return All Cameras container.
*/
inline const Vector<Camera*>& getCameras() const { return _cameras; }
/**
* @brief Sorts all cameras.
*/
void sortCameras();
/**
* @brief Gets all models count.
* @return All models count.
*/
inline uint32_t getModelCount() const { return (uint32_t)_models.size(); }
/**
* @brief Gets model by index.
* @param[in] index Model index.
* @return Model pointer.
*/
Model* getModel(uint32_t index);
/**
* @brief Adds model.
* @param[in] model Model pointer.
*/
void addModel(Model* model);
/**
* @brief Removes model.
* @param[in] model Model pointer.
*/
void removeModel(Model* model);
/**
* @brief Removes all models.
*/
void removeModels();
/**
* @brief Gets all models.
* @return Models container.
*/
inline const std::vector<Model*>& getModels() const { return _models; }
// light
/**
* @brief Gets light count.
* @return Lights count.
*/
inline uint32_t getLightCount() const { return (uint32_t)_lights.size(); }
/**
* @brief Gets light by index.
* @param[in] index Light index.
* @return Light pointer.
*/
Light* getLight(uint32_t index);
/**
* @brief Adds light.
* @param[in] light Light pointer.
*/
void addLight(Light* light);
/**
* @brief Removes light.
* @param[in] light Light pointer.
*/
void removeLight(Light* light);
// view
/**
* @brief Adds view.
* @param[in] view View pointer.
*/
void addView(View* view);
/**
* @brief Removes view.
* @param[in] view View pointer.
*/
void removeView(View* view);
/**
* @brief Gets all lights.
* @return Lights container.
*/
inline const Vector<Light*> getLights() const { return _lights; };
private:
//REFINE: optimize speed.
Vector<Camera*> _cameras;
@@ -78,4 +170,7 @@ private:
Camera* _debugCamera = nullptr;
};
// end of renderer group
/// @}
RENDERER_END
+68 -26
View File
@@ -32,28 +32,39 @@ RENDERER_BEGIN
// implementation of Parameter
uint8_t Technique::Parameter::elementsOfType[] = {
1, // INT
2, // INT2
3, // INT3
4, // INT4
1, // FLOAT
2, // FLOAT2
3, // FLOAT3
4, // FLOAT4
3, // COLOR3
4, // COLOR4
4, // MAT2
9, // MAT3
16,// MAT4
1, // TEXTURE_2D
1, // TEXTURE_CUBE
0, // UNKNOWN
};
uint8_t Technique::Parameter::getElements(Type type)
{
return Parameter::elementsOfType[(int)type];
switch (type)
{
case Type::INT:
return 1;
case Type::INT2:
return 2;
case Type::INT3:
return 3;
case Type::INT4:
return 4;
case Type::FLOAT:
return 1;
case Type::FLOAT2:
return 2;
case Type::FLOAT3:
return 3;
case Type::FLOAT4:
return 4;
case Type::COLOR3:
return 3;
case Type::COLOR4:
return 4;
case Type::MAT2:
return 4;
case Type::MAT3:
return 9;
case Type::MAT4:
return 16;
default:
return 0;
}
}
Technique::Parameter::Parameter()
@@ -256,6 +267,19 @@ Technique::Parameter& Technique::Parameter::operator=(const Parameter& rh)
return *this;
}
bool Technique::Parameter::operator==(const Parameter& rh)
{
if (this == &rh)
return true;
if (_type == rh.getType() && _value == rh.getValue())
{
return true;
}
return false;
}
std::vector<Texture*> Technique::Parameter::getTextureArray() const
{
std::vector<Texture*> ret;
@@ -308,11 +332,10 @@ void Technique::Parameter::copyValue(const Parameter& rh)
_value = rh._value;
RENDERER_SAFE_RETAIN((Texture*)_value);
}
else
else if (_count > 0)
{
if (_count > 0)
_value = malloc(_count * sizeof(void*));
_value = malloc(_count * sizeof(void*));
memcpy(_value, rh._value, _count * sizeof(void*));
Texture** texture = (Texture**)_value;
for (uint8_t i = 0; i < _count; ++i)
{
@@ -364,18 +387,21 @@ void Technique::Parameter::freeValue()
uint32_t Technique::_genID = 0;
Technique::Technique(const std::vector<std::string>& stages,
const std::vector<Parameter>& parameters,
const Vector<Pass*>& passes,
int layer)
: _id(_genID++)
, _stageIDs(Config::getStageIDs(stages))
, _parameters(parameters)
, _passes(passes)
, _layer(layer)
{
// RENDERER_LOGD("Technique construction: %p", this);
}
Technique::Technique()
{
}
Technique::~Technique()
{
// RENDERER_LOGD("Technique destruction: %p", this);
@@ -391,4 +417,20 @@ void Technique::setPass(int index, Pass* pass)
_passes.insert(index, pass);
}
void Technique::copy(const Technique& tech)
{
_id = tech._id;
_stageIDs = tech._stageIDs;
_layer = tech._layer;
_passes.clear();
auto& otherPasses = tech._passes;
for (auto it = otherPasses.begin(); it != otherPasses.end(); it++)
{
auto newPass = new Pass();
newPass->autorelease();
newPass->copy(**it);
_passes.pushBack(newPass);
}
}
RENDERER_END

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