Kevin 3 vuotta sitten
commit
53a485cb4f
3753 muutettua tiedostoa jossa 212302 lisäystä ja 0 poistoa
  1. +398
    -0
      Editor/AlignTool.lua
  2. +137
    -0
      Editor/ApplyDict.lua
  3. +29
    -0
      Editor/CCBoxNode.lua
  4. +57
    -0
      Editor/CCRectNode.lua
  5. +808
    -0
      Editor/CSharpConstants.lua
  6. +145
    -0
      Editor/Camera2DControllerTool.lua
  7. +218
    -0
      Editor/Camera3DControllerTool.lua
  8. +111
    -0
      Editor/CombineEffectCommands.lua
  9. +378
    -0
      Editor/CombineEffectEditor.lua
  10. +471
    -0
      Editor/Commands.lua
  11. +113
    -0
      Editor/CompareVersion.lua
  12. +654
    -0
      Editor/CompileFile.lua
  13. +61
    -0
      Editor/Editor.lua
  14. +738
    -0
      Editor/EditorApp.lua
  15. +20
    -0
      Editor/EditorConfig.lua
  16. +27
    -0
      Editor/EditorGlobalFunction.lua
  17. +8
    -0
      Editor/EditorNodeZorder.lua
  18. +124
    -0
      Editor/EffectEditor.lua
  19. +22
    -0
      Editor/GenerateAnimationClips.lua
  20. +121
    -0
      Editor/GenerateDict.lua
  21. +22
    -0
      Editor/GenerateMaterials.lua
  22. +31
    -0
      Editor/GenerateTextureSize.lua
  23. +274
    -0
      Editor/GenerateVersion.lua
  24. +46
    -0
      Editor/LinkFile.lua
  25. +23
    -0
      Editor/MapEditor.lua
  26. +139
    -0
      Editor/Move2DTool.lua
  27. +171
    -0
      Editor/Move3DTool.lua
  28. +292
    -0
      Editor/MoveTool.lua
  29. +269
    -0
      Editor/NodeEditor.lua
  30. +101
    -0
      Editor/ObstacleTool.lua
  31. +453
    -0
      Editor/PostloadResource.lua
  32. +140
    -0
      Editor/SceneEditor.lua
  33. +147
    -0
      Editor/UIEditor.lua
  34. +172
    -0
      Editor/UIPreviewEditor.lua
  35. +114
    -0
      Editor/UndoRedoManager.lua
  36. +126
    -0
      Editor/VisibleRect.lua
  37. BIN
      Editor/hero1.png
  38. BIN
      Editor/hero2.png
  39. BIN
      Editor/iphone5.png
  40. +74
    -0
      Editor/main.lua
  41. BIN
      Editor/map.png
  42. +59
    -0
      Editor/preloadText.bmfc
  43. BIN
      Editor/preloadText.txt
  44. BIN
      EditorCS.exe
  45. BIN
      EditorEngine.dll
  46. +2
    -0
      README.md
  47. BIN
      TimeBeam.dll
  48. +8
    -0
      _fetch.bat
  49. +3
    -0
      _rebaseToOriginMaster.bat
  50. +3
    -0
      _rebaseToUpstreamMaster.bat
  51. +7
    -0
      _updateMaster.bat
  52. BIN
      _w3h.dll
  53. +1
    -0
      changeProjcet.bat
  54. +225
    -0
      changeProject.py
  55. +2
    -0
      co_mini_games.bat
  56. +42
    -0
      core/luaScript/Config/Configs.lua
  57. +49
    -0
      core/luaScript/Config/DefaultModuleConfig.lua
  58. +28
    -0
      core/luaScript/Config/MultiWechatConfig.lua
  59. +15
    -0
      core/luaScript/Config/Setting.lua
  60. +61
    -0
      core/luaScript/Extension/CCExt.lua
  61. +70
    -0
      core/luaScript/Extension/IoExt.lua
  62. +64
    -0
      core/luaScript/Extension/MathExt.lua
  63. +144
    -0
      core/luaScript/Extension/StringExt.lua
  64. +354
    -0
      core/luaScript/Extension/TableExt.lua
  65. +53
    -0
      core/luaScript/GameChatDefine.lua
  66. +1368
    -0
      core/luaScript/GameGlobalFunction.lua
  67. +214
    -0
      core/luaScript/GameGlobalSound.lua
  68. +421
    -0
      core/luaScript/GameTypeDef.lua
  69. +322
    -0
      core/luaScript/GlobalEvent.lua
  70. +577
    -0
      core/luaScript/GlobalPlugin.lua
  71. +4
    -0
      core/luaScript/GoToMainView.lua
  72. +85
    -0
      core/luaScript/Interface/IClub.lua
  73. +51
    -0
      core/luaScript/Interface/IGameCommon.lua
  74. +30
    -0
      core/luaScript/Interface/IGameOverAward.lua
  75. +245
    -0
      core/luaScript/Interface/IPlayGameAgain.lua
  76. +7
    -0
      core/luaScript/Interface/init.lua
  77. +92
    -0
      core/luaScript/MJFramework.lua
  78. +299
    -0
      core/luaScript/Map/Map.lua
  79. +133
    -0
      core/luaScript/Map/MapDrawer.lua
  80. +22
    -0
      core/luaScript/ModuleEapSdk/AdapterEapSdk.lua
  81. +58
    -0
      core/luaScript/ModuleEapSdk/BaseCommon/BaseCommon.lua
  82. +12
    -0
      core/luaScript/ModuleEapSdk/BaseCommon/BaseEvent.lua
  83. +84
    -0
      core/luaScript/ModuleEapSdk/BaseLayers/BaseLayer.lua
  84. +1053
    -0
      core/luaScript/ModuleEapSdk/EapFunc/EapJson.lua
  85. +28
    -0
      core/luaScript/ModuleEapSdk/EapFunc/config.lua
  86. +207
    -0
      core/luaScript/ModuleEapSdk/EapFunc/framework/audio.lua
  87. +158
    -0
      core/luaScript/ModuleEapSdk/EapFunc/framework/components/event.lua
  88. +108
    -0
      core/luaScript/ModuleEapSdk/EapFunc/framework/device.lua
  89. +547
    -0
      core/luaScript/ModuleEapSdk/EapFunc/framework/display.lua
  90. +81
    -0
      core/luaScript/ModuleEapSdk/EapFunc/framework/extends/LayerEx.lua
  91. +32
    -0
      core/luaScript/ModuleEapSdk/EapFunc/framework/extends/MenuEx.lua
  92. +229
    -0
      core/luaScript/ModuleEapSdk/EapFunc/framework/extends/NodeEx.lua
  93. +68
    -0
      core/luaScript/ModuleEapSdk/EapFunc/framework/extends/SpriteEx.lua
  94. +41
    -0
      core/luaScript/ModuleEapSdk/EapFunc/framework/extends/UICheckBox.lua
  95. +42
    -0
      core/luaScript/ModuleEapSdk/EapFunc/framework/extends/UIEditBox.lua
  96. +69
    -0
      core/luaScript/ModuleEapSdk/EapFunc/framework/extends/UIListView.lua
  97. +39
    -0
      core/luaScript/ModuleEapSdk/EapFunc/framework/extends/UIPageView.lua
  98. +57
    -0
      core/luaScript/ModuleEapSdk/EapFunc/framework/extends/UIScrollView.lua
  99. +39
    -0
      core/luaScript/ModuleEapSdk/EapFunc/framework/extends/UISlider.lua
  100. +45
    -0
      core/luaScript/ModuleEapSdk/EapFunc/framework/extends/UITextField.lua

+ 398
- 0
Editor/AlignTool.lua Näytä tiedosto

@@ -0,0 +1,398 @@
require("EditorGlobalFunction")

local AlignTool = class("AlignTool")
function AlignTool:ctor()
end

-- 计算最左边
local function calcLeft()
local minX = 65536;
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
minX = math.min(minX , node:getWorldPositionX() - node:getAnchorPoint().x * node:getContentSize().width * node:getScaleX());
end
return minX;
end

-- 计算最右边
local function calcRight()
local maxX = 0;
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
maxX = math.max(maxX , node:getWorldPositionX() + (1 - node:getAnchorPoint().x) * node:getContentSize().width * node:getScaleX());
end
return maxX;
end

-- 计算最上边
local function calcTop()
local maxY = 0;
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
maxY = math.max(maxY , node:getWorldPositionY() + (1 - node:getAnchorPoint().y) * node:getContentSize().height * node:getScaleY());
end
return maxY;
end

-- 计算最下边
local function calcBottom()
local minY = 65536;
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
minY = math.min(minY , node:getWorldPositionY() - node:getAnchorPoint().y * node:getContentSize().height * node:getScaleY());
end
return minY;
end

-- 获得所有选中元素的总宽高
local function calcAllSize()
local size = cc.size(0,0);
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
local s = node:getSize();
size.width = size.width + s.width;
size.height = size.height + s.height;
end
return size;
end

-- 获得最后一个选中的节点
local function getLastSelectedNode()
local node;
for i , v in pairs(app.editor.SelectedNodes) do
if node == nil or v.SelectedIndex > node.SelectedIndex then
node = v;
end
end
return node;
end

function AlignTool:AlignLeft()
local minX = calcLeft();
local commands = {};
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
local pos = node:getWorldPosition();
pos.x = minX + node:getAnchorPoint().x * node:getContentSize().width * node:getScaleX();
table.insert(commands, Commands:setWorldPosition(node, pos));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

function AlignTool:AlignCenter()
local minX = calcLeft();
local maxX = calcRight();
local width = maxX - minX;
local center = minX + width / 2;

local commands = {};
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
local offsetX = center - (node:getWorldPositionX() - node:getAnchorPoint().x * node:getContentSize().width * node:getScaleX() + node:getContentSize().width * node:getScaleX() / 2);
local pos = node:getWorldPosition();
pos.x = node:getWorldPositionX() + offsetX;
table.insert(commands, Commands:setWorldPosition(node, pos));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

function AlignTool:AlignRight()
local maxX = calcRight();
local commands = {};
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
local pos = node:getWorldPosition();
pos.x = maxX - node:getContentSize().width * node:getScaleX() + node:getAnchorPoint().x * node:getContentSize().width * node:getScaleX();
table.insert(commands, Commands:setWorldPosition(node, pos));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

function AlignTool:AlignTop()
local maxY = calcTop();
local commands = {};
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
local pos = node:getWorldPosition();
pos.y = maxY - node:getContentSize().height * node:getScaleY() + node:getAnchorPoint().y * node:getContentSize().height * node:getScaleY();
table.insert(commands, Commands:setWorldPosition(node, pos));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

function AlignTool:AlignMiddle()
local minY = calcBottom();
local maxY = calcTop();
local height = maxY - minY;
local middle = minY + height / 2;

local commands = {};
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
local offsetY = middle - (node:getWorldPositionY() - node:getAnchorPoint().y * node:getContentSize().height * node:getScaleY() + node:getContentSize().height * node:getScaleY() / 2);
local pos = node:getWorldPosition();
pos.y = node:getWorldPositionY() + offsetY;
table.insert(commands, Commands:setWorldPosition(node, pos));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

function AlignTool:AlignBottom()
local minY = calcBottom();
local commands = {};
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
local offsetY = minY - (node:getWorldPositionY() - node:getAnchorPoint().y * node:getContentSize().height * node:getScaleY());
local pos = node:getWorldPosition();
pos.y = node:getWorldPositionY() + offsetY;
table.insert(commands, Commands:setWorldPosition(node, pos));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

function AlignTool:SameWidth()
local lastNode = getLastSelectedNode();
if not lastNode then
return;
end
local width = lastNode:getSize().width;
local commands = {};
for i , v in pairs(app.editor.SelectedNodes) do
local size = v:getSize();
size.width = width;
table.insert(commands, Commands:sizeNode(v, size));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

function AlignTool:SameHeight()
local lastNode = getLastSelectedNode();
if not lastNode then
return;
end
local height = lastNode:getSize().height;
local commands = {};
for i , v in pairs(app.editor.SelectedNodes) do
local size = v:getSize();
size.height = height;
table.insert(commands, Commands:sizeNode(v, size));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

function AlignTool:SameSize()
local lastNode = getLastSelectedNode();
if not lastNode then
return;
end
local commands = {};
for i , v in pairs(app.editor.SelectedNodes) do
table.insert(commands, Commands:sizeNode(v, lastNode:getSize()));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

function AlignTool:SameHorzSpace()
local count = table.nums(app.editor.SelectedNodes);
if count < 3 then
return;
end
local allSize = calcAllSize();
local left = calcLeft();
local right = calcRight();
-- 计算间距
local space = 0;
if allSize.width > right - left then
space = 0;
else
space = ((right - left) - allSize.width) / (count - 1);
end
-- 计算顺序
local nodes = {};
for i , v in pairs(app.editor.SelectedNodes) do
table.insert(nodes, v);
end
-- 从左到右排序
table.sort(nodes , function(a,b)return a:getWorldPositionX() - a:getAnchorPoint().x * a:getContentSize().width * a:getScaleX() < b:getWorldPositionX() - b:getAnchorPoint().x * b:getContentSize().width * a:getScaleX();end);

local commands = {};
local posX = left;
for i , node in ipairs(nodes) do
local pos = node:getWorldPosition();
pos.x = posX + node:getAnchorPoint().x * node:getContentSize().width * node:getScaleX();

posX = posX + space + node:getSize().width;
table.insert(commands, Commands:setWorldPosition(node, pos));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

function AlignTool:AddHorzSpace()
end

function AlignTool:SubHorzSpace()
end

function AlignTool:NoHorzSpace()
end

function AlignTool:SameVertSpace()
local count = table.nums(app.editor.SelectedNodes);
if count < 3 then
return;
end
local allSize = calcAllSize();
local bottom = calcBottom();
local top = calcTop();
-- 计算间距
local space = 0;
if allSize.height > top - bottom then
space = 0;
else
space = ((top - bottom) - allSize.height) / (count - 1);
end
-- 计算顺序
local nodes = {};
for i , v in pairs(app.editor.SelectedNodes) do
table.insert(nodes, v);
end
-- 从左到右排序
table.sort(nodes , function(a,b)return a:getWorldPositionY() - a:getAnchorPoint().y * a:getContentSize().height * a:getScaleY() < b:getWorldPositionY() - b:getAnchorPoint().y * b:getContentSize().height * a:getScaleY();end);

local commands = {};
local posY = bottom;
for i , node in ipairs(nodes) do
local pos = node:getWorldPosition();
pos.y = posY + node:getAnchorPoint().y * node:getContentSize().height * node:getScaleY();

posY = posY + space + node:getSize().height;
table.insert(commands, Commands:setWorldPosition(node, pos));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

function AlignTool:AddVertSpace()
end

function AlignTool:SubVertSpace()
end

function AlignTool:NoVertSpace()
end

function AlignTool:HorzCenter()
local left = calcLeft();
local right = calcRight();
local size = app.setting.ResourceSize;
local minX = (size.width - (right - left)) / 2;
local commands = {};
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
local pos = node:getWorldPosition();
pos.x = minX + ((node:getWorldPositionX() - node:getAnchorPoint().x * node:getContentSize().width * node:getScaleX()) - left);
table.insert(commands, Commands:setWorldPosition(node, pos));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

function AlignTool:VertCenter()
local bottom = calcBottom();
local top = calcTop();
local size = app.setting.ResourceSize;
local minY = (size.height - (top - bottom)) / 2;
local commands = {};
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
local pos = node:getWorldPosition();
pos.y = minY + ((node:getWorldPositionY() - node:getAnchorPoint().y * node:getContentSize().height * node:getScaleY()) - bottom);
table.insert(commands, Commands:setWorldPosition(node, pos));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

function AlignTool:MoveUp()
local lastNode = getLastSelectedNode();
if not lastNode then
return;
end
local children = lastNode:getParent():getChildren();
local node;
for i , v in ipairs(children) do
if v == lastNode then
node = children[i - 1];
break;
end
end
if node and node ~= lastNode then
app.undoRedoManager:doCommand(Commands:swapNode(lastNode, node))
end
end

function AlignTool:MoveDown()
local lastNode = getLastSelectedNode();
if not lastNode then
return;
end
local children = lastNode:getParent():getChildren();
local node;
for i , v in ipairs(children) do
if v == lastNode then
node = children[i + 1];
break;
end
end
if node and node ~= lastNode then
app.undoRedoManager:doCommand(Commands:swapNode(lastNode, node))
end
end

function AlignTool:MoveTop()
local lastNode = getLastSelectedNode();
if not lastNode then
return;
end
local children = lastNode:getParent():getChildren();
local node = children[1];
if node and node ~= lastNode then
local commands = {};
local found = false;
for i = #children , 1 , -1 do
local child = children[i];
if found then
print("交换一个");
table.insert(commands, Commands:swapNode(child, lastNode));
end
if child == lastNode then
found = true;
end
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end
end

function AlignTool:MoveBottom()
local lastNode = getLastSelectedNode();
if not lastNode then
return;
end
local children = lastNode:getParent():getChildren();
local node = children[#children];
if node and node ~= lastNode then
local commands = {};
local found = false;
for i = 1 , #children do
local child = children[i];
if found then
table.insert(commands, Commands:swapNode(child, lastNode));
end
if child == lastNode then
found = true;
end
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end
end

return AlignTool;

+ 137
- 0
Editor/ApplyDict.lua Näytä tiedosto

@@ -0,0 +1,137 @@
require("Editor.CompileFile")
require("luaScript.Tools.Widgets.UIWidget")


-- 收集languageCN.lua里的语言
local function collectLanguages(transDict)
local Languages = require("languageCN");

local newLn = {};
for i , v in pairs(Languages) do
print("收集Lang文本" , v);
local translated = transDict[XmlTranslator:collect(v)];
if translated then
newLn[i] = XmlTranslator:translate(v , translated);
else
newLn[i] = v;
end
end

for i , v in pairs(newLn) do
Languages[i] = v;
end
table.saveFile(Languages , "luaScript/Config/Languages/languageEN.lua");
end

-- 收集一个语言片
local function collectConfig(transDict , record , fieldName , translator)
local v = record[fieldName];
if v then
local translated = transDict[translator:collect(v)];
if translated then
record[fieldName] = translator:translate(v , translated);
end
end
end

-- 收集一个配置
local function collectLanguageConfig(transDict , config)
local desc = config:getConfigDesc();
print("正在收集配置的语言:" , desc.XMLFile);
if desc.Translation then
for i , v in pairs(desc.Translation) do
print("正在收集字段:" , i);
for ii , vv in pairs(config) do
if desc.SecondKeyName then
for iii , vvv in pairs(vv) do
collectConfig(transDict , vvv , i , v);
end
else
collectConfig(transDict , vv , i , v);
end
end
end
saveLuaXMLConfig(config , desc, "dataconfig/" .. desc.XMLFile .. ".lua");
end
end

-- 收集一个ui
local function collectSingleUI(transDict , ui)
if ui.applyDict then
ui:applyDict(transDict);
end
end
-- 收集一个ui
local function collectUI(transDict , ui)
collectSingleUI(transDict , ui);
-- 递归所有子
for i , v in pairs(ui:getChildren()) do
collectUI(transDict , v);
end
end

-- 收集所有UI的语言
local function collectUILanguage(transDict)
local function saveui(fileName)
-- 返回pathName , baseName , ext
local pathName , baseName , ext = string.splitFilename(fileName);
print(pathName , baseName , ext);
if ext ~= "ui" then
return false;
end

print("\n\n");
print("正在加载UI:" , fileName);
local ui = cc.StreamObject:loadFromFile(fileName);
collectUI(transDict , ui);
ui:recalcAllPList();
ui:saveToFile(fileName);
end
visitPath("res/ui" , saveui);
end

-- 载入字典文件,返回字典表
local function loadDict(dictFile)
local dict = {};
local function onStartElement(name , atts)
if name == "item" then
dict[atts.source] = atts.target;
end
end

local result , err = tiny.load(dictFile , onStartElement);
if not result then
error(err);
end
return dict;
end

-- 生成所有语言
function applyDict(dictFile)

-- initialize director
local director = cc.Director:getInstance();
local glview = director:getOpenGLView();
if not glview then
glview = cc.GLView:createWithRect("applyDict", {x=0,y=0,width=100,height=100});
director:setOpenGLView(glview);
end

local transDict = loadDict(dictFile)
-- 加载xml
loadAllXML()

-- 生成所有配置的语言
for i , v in pairs(app.config) do
if i ~= "Setting" and i ~= "RomSetting" then
local desc = v:getConfigDesc();
local filename = desc.XMLFile;
collectLanguageConfig(transDict , v);
end
end

-- 收集languageCN.lua里的语言
collectLanguages(transDict);

collectUILanguage(transDict);
end

+ 29
- 0
Editor/CCBoxNode.lua Näytä tiedosto

@@ -0,0 +1,29 @@
-- 画鼠标框选的时候那个白框
cc.BoxNode = {

}

function cc.BoxNode:create()
local glNode = gl.glNodeCreate()
glNode:setAnchorPoint(cc.p(0.5, 0.5))

local function primitivesDraw(transform, transformUpdated)
-- 绑定相机、世界矩阵
cc.DrawPrimitives.setCamera(cc.Director:getInstance():getFixedCamera());
cc.DrawPrimitives.setWorldTransform(cc.Mat4:identity());

-- 画矩形
gl.lineWidth( 1 )
cc.DrawPrimitives.drawColor4B(255, 255, 255, 255)
cc.DrawPrimitives.drawRect(glNode.startPos, glNode.endPos)

-- 状态恢复
gl.lineWidth(1)
cc.DrawPrimitives.drawColor4B(255,255,255,255)
cc.DrawPrimitives.setPointSize(1)
end

glNode:registerScriptDrawHandler(primitivesDraw)

return glNode
end

+ 57
- 0
Editor/CCRectNode.lua Näytä tiedosto

@@ -0,0 +1,57 @@
-- 被选择节点显示高亮框
cc.RectNode = {

}

function cc.RectNode:create(node)
local glNode = gl.glNodeCreate()
glNode:setAnchorPoint(cc.p(0.5, 0.5))
function glNode:setNode(node)
local function onNodeEvent(node , eventType)
if eventType == cc.NodeEvent.OnExit then
if self.Node == node then
self.Node = nil;
end
end
end
if node then
node:addNodeEventListener(onNodeEvent)
end

self.Node = node;
end

glNode:setNode(node)
local material3d = cc.MaterialCache:getInstance():load("core/preload/shaders/ccDefault.material#ShaderPosition_uColor3D");
cc.Default2DMaterials:getInstance():bindValue(material3d:getParameter("CC_MVPMatrix") , "WORLD_VIEW_PROJECTION_MATRIX");

local function primitivesDraw(transform, transformUpdated)
local node = glNode.Node;
if not tolua.isnull(node) then
cc.DrawPrimitives.setMaterial(material3d);
-- 绑定相机、世界矩阵
cc.DrawPrimitives.setCamera(node:getActiveCamera());
cc.DrawPrimitives.setWorldTransform(cc.Mat4:identity());

-- 画矩形
gl.lineWidth( 1 )
cc.DrawPrimitives.drawColor4B(0, 255, 0, 255)
cc.DrawPrimitives.drawBoundingBox(node:getSelectBox())

-- 状态恢复
gl.lineWidth(1)
cc.DrawPrimitives.drawColor4B(255,255,255,255)
cc.DrawPrimitives.setPointSize(1)

-- 材质状态恢复
cc.DrawPrimitives.setCamera(nil);
cc.DrawPrimitives.setMaterial(nil);
end
end

glNode:registerScriptDrawHandler(primitivesDraw)

return glNode
end


+ 808
- 0
Editor/CSharpConstants.lua Näytä tiedosto

@@ -0,0 +1,808 @@

MouseButtons =
{
-- 摘要:
-- 未曾按下鼠标按钮。
None = 0,
--
-- 摘要:
-- 鼠标左按钮曾按下。
Left = 1048576,
--
-- 摘要:
-- 鼠标右按钮曾按下。
Right = 2097152,
--
-- 摘要:
-- 鼠标中按钮曾按下。
Middle = 4194304,
--
-- 摘要:
-- 第 1 个 XButton 曾按下。
XButton1 = 8388608,
--
-- 摘要:
-- 第 2 个 XButton 曾按下。
XButton2 = 16777216,
}

-- 摘要:
-- 指定键代码和修饰符。
Keys =
{
-- 摘要:
-- 从键值提取修饰符的位屏蔽。
Modifiers = -65536,
--
-- 摘要:
-- 没有按任何键。
None = 0,
--
-- 摘要:
-- 鼠标左按钮。
LButton = 1,
--
-- 摘要:
-- 鼠标右按钮。
RButton = 2,
--
-- 摘要:
-- Cancel 键。
Cancel = 3,
--
-- 摘要:
-- 鼠标中按钮(三个按钮的鼠标)。
MButton = 4,
--
-- 摘要:
-- 第一个 X 鼠标按钮(五个按钮的鼠标)。
XButton1 = 5,
--
-- 摘要:
-- 第二个 X 鼠标按钮(五个按钮的鼠标)。
XButton2 = 6,
--
-- 摘要:
-- Backspace 键。
Back = 8,
--
-- 摘要:
-- The TAB key.
Tab = 9,
--
-- 摘要:
-- LINEFEED 键。
LineFeed = 10,
--
-- 摘要:
-- Clear 键。
Clear = 12,
--
-- 摘要:
-- Enter 键。
Enter = 13,
--
-- 摘要:
-- Return 键。
Return = 13,
--
-- 摘要:
-- Shift 键。
ShiftKey = 16,
--
-- 摘要:
-- The CTRL key.
ControlKey = 17,
--
-- 摘要:
-- Alt 键。
Menu = 18,
--
-- 摘要:
-- Pause 键。
Pause = 19,
--
-- 摘要:
-- The CAPS LOCK key.
CapsLock = 20,
--
-- 摘要:
-- The CAPS LOCK key.
Capital = 20,
--
-- 摘要:
-- IME Kana 模式键。
KanaMode = 21,
--
-- 摘要:
-- IME Hanguel 模式键。(为了保持兼容性而设置;使用 HangulMode)
HanguelMode = 21,
--
-- 摘要:
-- IME Hangul 模式键。
HangulMode = 21,
--
-- 摘要:
-- IME Junja 模式键。
JunjaMode = 23,
--
-- 摘要:
-- IME 最终模式键。
FinalMode = 24,
--
-- 摘要:
-- IME Kanji 模式键。
KanjiMode = 25,
--
-- 摘要:
-- IME Hanja 模式键。
HanjaMode = 25,
--
-- 摘要:
-- The ESC key.
Escape = 27,
--
-- 摘要:
-- IME 转换键。
IMEConvert = 28,
--
-- 摘要:
-- IME 非转换键。
IMENonconvert = 29,
--
-- 摘要:
-- IME 接受键。已过时,请改用 System.Windows.Forms.Keys.IMEAccept。
IMEAceept = 30,
--
-- 摘要:
-- IME 接受键,替换 System.Windows.Forms.Keys.IMEAceept。
IMEAccept = 30,
--
-- 摘要:
-- IME 模式更改键。
IMEModeChange = 31,
--
-- 摘要:
-- 空格键。
Space = 32,
--
-- 摘要:
-- The PAGE UP key.
Prior = 33,
--
-- 摘要:
-- The PAGE UP key.
PageUp = 33,
--
-- 摘要:
-- The PAGE DOWN key.
Next = 34,
--
-- 摘要:
-- The PAGE DOWN key.
PageDown = 34,
--
-- 摘要:
-- The END key.
End = 35,
--
-- 摘要:
-- The HOME key.
Home = 36,
--
-- 摘要:
-- 向左键。
Left = 37,
--
-- 摘要:
-- 向上键。
Up = 38,
--
-- 摘要:
-- 向右键。
Right = 39,
--
-- 摘要:
-- 向下键。
Down = 40,
--
-- 摘要:
-- Select 键。
Select = 41,
--
-- 摘要:
-- Print 键。
Print = 42,
--
-- 摘要:
-- EXECUTE 键。
Execute = 43,
--
-- 摘要:
-- Print Screen 键。
PrintScreen = 44,
--
-- 摘要:
-- Print Screen 键。
Snapshot = 44,
--
-- 摘要:
-- The INS key.
Insert = 45,
--
-- 摘要:
-- The DEL key.
Delete = 46,
--
-- 摘要:
-- The HELP key.
Help = 47,
--
-- 摘要:
-- The 0 key.
D0 = 48,
--
-- 摘要:
-- The 1 key.
D1 = 49,
--
-- 摘要:
-- The 2 key.
D2 = 50,
--
-- 摘要:
-- The 3 key.
D3 = 51,
--
-- 摘要:
-- The 4 key.
D4 = 52,
--
-- 摘要:
-- The 5 key.
D5 = 53,
--
-- 摘要:
-- The 6 key.
D6 = 54,
--
-- 摘要:
-- The 7 key.
D7 = 55,
--
-- 摘要:
-- The 8 key.
D8 = 56,
--
-- 摘要:
-- The 9 key.
D9 = 57,
--
-- 摘要:
-- A 键。
A = 65,
--
-- 摘要:
-- B 键。
B = 66,
--
-- 摘要:
-- C 键。
C = 67,
--
-- 摘要:
-- D 键。
D = 68,
--
-- 摘要:
-- E 键。
E = 69,
--
-- 摘要:
-- F 键。
F = 70,
--
-- 摘要:
-- G 键。
G = 71,
--
-- 摘要:
-- H 键。
H = 72,
--
-- 摘要:
-- I 键。
I = 73,
--
-- 摘要:
-- J 键。
J = 74,
--
-- 摘要:
-- K 键。
K = 75,
--
-- 摘要:
-- L 键。
L = 76,
--
-- 摘要:
-- M 键。
M = 77,
--
-- 摘要:
-- N 键。
N = 78,
--
-- 摘要:
-- O 键。
O = 79,
--
-- 摘要:
-- P 键。
P = 80,
--
-- 摘要:
-- Q 键。
Q = 81,
--
-- 摘要:
-- R 键。
R = 82,
--
-- 摘要:
-- S 键。
S = 83,
--
-- 摘要:
-- T 键。
T = 84,
--
-- 摘要:
-- U 键。
U = 85,
--
-- 摘要:
-- V 键。
V = 86,
--
-- 摘要:
-- W 键。
W = 87,
--
-- 摘要:
-- X 键。
X = 88,
--
-- 摘要:
-- Y 键。
Y = 89,
--
-- 摘要:
-- Z 键。
Z = 90,
--
-- 摘要:
-- 左 Windows 徽标键(Microsoft Natural Keyboard,人体工程学键盘)。
LWin = 91,
--
-- 摘要:
-- 右 Windows 徽标键(Microsoft Natural Keyboard,人体工程学键盘)。
RWin = 92,
--
-- 摘要:
-- 应用程序键(Microsoft Natural Keyboard,人体工程学键盘)。
Apps = 93,
--
-- 摘要:
-- 计算机睡眠键。
Sleep = 95,
--
-- 摘要:
-- The 0 key on the numeric keypad.
NumPad0 = 96,
--
-- 摘要:
-- The 1 key on the numeric keypad.
NumPad1 = 97,
--
-- 摘要:
-- 数字键盘上的 2 键。
NumPad2 = 98,
--
-- 摘要:
-- 数字键盘上的 3 键。
NumPad3 = 99,
--
-- 摘要:
-- 数字键盘上的 4 键。
NumPad4 = 100,
--
-- 摘要:
-- 数字键盘上的 5 键。
NumPad5 = 101,
--
-- 摘要:
-- 数字键盘上的 6 键。
NumPad6 = 102,
--
-- 摘要:
-- 数字键盘上的 7 键。
NumPad7 = 103,
--
-- 摘要:
-- The 8 key on the numeric keypad.
NumPad8 = 104,
--
-- 摘要:
-- The 9 key on the numeric keypad.
NumPad9 = 105,
--
-- 摘要:
-- 乘号键。
Multiply = 106,
--
-- 摘要:
-- 加号键。
Add = 107,
--
-- 摘要:
-- 分隔符键。
Separator = 108,
--
-- 摘要:
-- 减号键。
Subtract = 109,
--
-- 摘要:
-- 句点键。
Decimal = 110,
--
-- 摘要:
-- 除号键。
Divide = 111,
--
-- 摘要:
-- The F1 key.
F1 = 112,
--
-- 摘要:
-- The F2 key.
F2 = 113,
--
-- 摘要:
-- The F3 key.
F3 = 114,
--
-- 摘要:
-- The F4 key.
F4 = 115,
--
-- 摘要:
-- The F5 key.
F5 = 116,
--
-- 摘要:
-- The F6 key.
F6 = 117,
--
-- 摘要:
-- The F7 key.
F7 = 118,
--
-- 摘要:
-- The F8 key.
F8 = 119,
--
-- 摘要:
-- The F9 key.
F9 = 120,
--
-- 摘要:
-- The F10 key.
F10 = 121,
--
-- 摘要:
-- The F11 key.
F11 = 122,
--
-- 摘要:
-- The F12 key.
F12 = 123,
--
-- 摘要:
-- The F13 key.
F13 = 124,
--
-- 摘要:
-- The F14 key.
F14 = 125,
--
-- 摘要:
-- The F15 key.
F15 = 126,
--
-- 摘要:
-- The F16 key.
F16 = 127,
--
-- 摘要:
-- The F17 key.
F17 = 128,
--
-- 摘要:
-- The F18 key.
F18 = 129,
--
-- 摘要:
-- The F19 key.
F19 = 130,
--
-- 摘要:
-- The F20 key.
F20 = 131,
--
-- 摘要:
-- The F21 key.
F21 = 132,
--
-- 摘要:
-- The F22 key.
F22 = 133,
--
-- 摘要:
-- The F23 key.
F23 = 134,
--
-- 摘要:
-- The F24 key.
F24 = 135,
--
-- 摘要:
-- The NUM LOCK key.
NumLock = 144,
--
-- 摘要:
-- Scroll Lock 键。
Scroll = 145,
--
-- 摘要:
-- 左 Shift 键。
LShiftKey = 160,
--
-- 摘要:
-- 右 Shift 键。
RShiftKey = 161,
--
-- 摘要:
-- 左 Ctrl 键。
LControlKey = 162,
--
-- 摘要:
-- 右 Ctrl 键。
RControlKey = 163,
--
-- 摘要:
-- 左 Alt 键。
LMenu = 164,
--
-- 摘要:
-- 右 Alt 键。
RMenu = 165,
--
-- 摘要:
-- 浏览器后退键(Windows 2000 或更高版本)。
BrowserBack = 166,
--
-- 摘要:
-- 浏览器前进键(Windows 2000 或更高版本)。
BrowserForward = 167,
--
-- 摘要:
-- 浏览器刷新键(Windows 2000 或更高版本)。
BrowserRefresh = 168,
--
-- 摘要:
-- 浏览器停止键(Windows 2000 或更高版本)。
BrowserStop = 169,
--
-- 摘要:
-- 浏览器搜索键(Windows 2000 或更高版本)。
BrowserSearch = 170,
--
-- 摘要:
-- 浏览器收藏夹键(Windows 2000 或更高版本)。
BrowserFavorites = 171,
--
-- 摘要:
-- 浏览器主页键(Windows 2000 或更高版本)。
BrowserHome = 172,
--
-- 摘要:
-- 静音键(Windows 2000 或更高版本)。
VolumeMute = 173,
--
-- 摘要:
-- 减小音量键(Windows 2000 或更高版本)。
VolumeDown = 174,
--
-- 摘要:
-- 增大音量键(Windows 2000 或更高版本)。
VolumeUp = 175,
--
-- 摘要:
-- 媒体下一曲目键(Windows 2000 或更高版本)。
MediaNextTrack = 176,
--
-- 摘要:
-- 媒体上一曲目键(Windows 2000 或更高版本)。
MediaPreviousTrack = 177,
--
-- 摘要:
-- 媒体停止键(Windows 2000 或更高版本)。
MediaStop = 178,
--
-- 摘要:
-- 媒体播放暂停键(Windows 2000 或更高版本)。
MediaPlayPause = 179,
--
-- 摘要:
-- 启动邮件键(Windows 2000 或更高版本)。
LaunchMail = 180,
--
-- 摘要:
-- 选择媒体键(Windows 2000 或更高版本)。
SelectMedia = 181,
--
-- 摘要:
-- 启动应用程序一键(Windows 2000 或更高版本)。
LaunchApplication1 = 182,
--
-- 摘要:
-- 启动应用程序二键(Windows 2000 或更高版本)。
LaunchApplication2 = 183,
--
-- 摘要:
-- The OEM 1 key.
Oem1 = 186,
--
-- 摘要:
-- 美式标准键盘上的 OEM 分号键(Windows 2000 或更高版本)。
OemSemicolon = 186,
--
-- 摘要:
-- 任何国家/地区键盘上的 OEM 加号键(Windows 2000 或更高版本)。
Oemplus = 187,
--
-- 摘要:
-- 任何国家/地区键盘上的 OEM 逗号键(Windows 2000 或更高版本)。
Oemcomma = 188,
--
-- 摘要:
-- 任何国家/地区键盘上的 OEM 减号键(Windows 2000 或更高版本)。
OemMinus = 189,
--
-- 摘要:
-- 任何国家/地区键盘上的 OEM 句点键(Windows 2000 或更高版本)。
OemPeriod = 190,
--
-- 摘要:
-- 美式标准键盘上的 OEM 问号键(Windows 2000 或更高版本)。
OemQuestion = 191,
--
-- 摘要:
-- The OEM 2 key.
Oem2 = 191,
--
-- 摘要:
-- 美式标准键盘上的 OEM 波形符键(Windows 2000 或更高版本)。
Oemtilde = 192,
--
-- 摘要:
-- The OEM 3 key.
Oem3 = 192,
--
-- 摘要:
-- The OEM 4 key.
Oem4 = 219,
--
-- 摘要:
-- 美式标准键盘上的 OEM 左括号键(Windows 2000 或更高版本)。
OemOpenBrackets = 219,
--
-- 摘要:
-- 美式标准键盘上的 OEM 管道键(Windows 2000 或更高版本)。
OemPipe = 220,
--
-- 摘要:
-- The OEM 5 key.
Oem5 = 220,
--
-- 摘要:
-- The OEM 6 key.
Oem6 = 221,
--
-- 摘要:
-- 美式标准键盘上的 OEM 右括号键(Windows 2000 或更高版本)。
OemCloseBrackets = 221,
--
-- 摘要:
-- The OEM 7 key.
Oem7 = 222,
--
-- 摘要:
-- 美式标准键盘上的 OEM 单/双引号键(Windows 2000 或更高版本)。
OemQuotes = 222,
--
-- 摘要:
-- The OEM 8 key.
Oem8 = 223,
--
-- 摘要:
-- The OEM 102 key.
Oem102 = 226,
--
-- 摘要:
-- RT 102 键的键盘上的 OEM 尖括号或反斜杠键(Windows 2000 或更高版本)。
OemBackslash = 226,
--
-- 摘要:
-- Process Key 键。
ProcessKey = 229,
--
-- 摘要:
-- 用于将 Unicode 字符当作键击传递。Packet 键值是用于非键盘输入法的 32 位虚拟键值的低位字。
Packet = 231,
--
-- 摘要:
-- The ATTN key.
Attn = 246,
--
-- 摘要:
-- Crsel 键。
Crsel = 247,
--
-- 摘要:
-- Exsel 键。
Exsel = 248,
--
-- 摘要:
-- ERASE EOF 键。
EraseEof = 249,
--
-- 摘要:
-- The PLAY key.
Play = 250,
--
-- 摘要:
-- The ZOOM key.
Zoom = 251,
--
-- 摘要:
-- 保留以备将来使用的常数。
NoName = 252,
--
-- 摘要:
-- PA1 键。
Pa1 = 253,
--
-- 摘要:
-- Clear 键。
OemClear = 254,
--
-- 摘要:
-- 从键值提取键代码的位屏蔽。
KeyCode = 65535,
--
-- 摘要:
-- Shift 修改键。
Shift = 65536,
--
-- 摘要:
-- Ctrl 修改键。
Control = 131072,
--
-- 摘要:
-- Alt 修改键。
Alt = 262144,
}

+ 145
- 0
Editor/Camera2DControllerTool.lua Näytä tiedosto

@@ -0,0 +1,145 @@
-- 显示鼠标当前位置(客户端窗口位置、坐标系的位置、GLView的位置)
-- 处理按下鼠标中键移动场景的功能

require("CSharpConstants")
local Camera2DControllerTool = class("Camera2DControllerTool")

function Camera2DControllerTool:moveTo(endPos)
local offset = cc.pSub(endPos , self.startPos);
local scale = app.setting.ScreenScale;

offset.x = -offset.x / scale;
offset.y = -offset.y / scale;
local newWorld = cc.pAdd(self.originPos , offset);
app.mainCamera:getNode():setTranslation(newWorld);
end

function Camera2DControllerTool:MouseMove(button , x , y)
local glViewPos = app.visibleRect:convertScreenToGLView(x, y);
if self.startPos then
-- 计算结束点
self:moveTo(glViewPos);
end
local point = app.visibleRect:convertScreenToCoordinate(x, y);

local strMapCoord = "";
if app.editor and app.editor.Map then
local tilePos = app.editor.Map:getTilePosition(point.x , point.y);
strMapCoord = string.format(" TilePos:%d,%d" , tilePos.x , tilePos.y);
end
return string.format("Mouse:%d,%d Coordinate:%d,%d GLView:%d,%d" .. strMapCoord , x , y , point.x , point.y , glViewPos.x , glViewPos.y);
end

function Camera2DControllerTool:MoveDown(button, x, y)
-- 鼠标中键按下可以移动场景
if button ~= MouseButtons.Middle then return end
-- 鼠标的按下位置
self.startPos = app.visibleRect:convertScreenToGLView(x, y);
-- 场景的位置
self.originPos = app.mainCamera:getNode():getTranslation();
end

function Camera2DControllerTool:MoveUp(button, x, y)
if not self.startPos then return end
-- 计算结束点
self:moveTo(app.visibleRect:convertScreenToGLView(x, y));
self.startPos = nil;
self.originPos = nil;
end

function Camera2DControllerTool:KeyDown(Control , Alt , Shift , KeyCode)

end

function Camera2DControllerTool:update()

end

-- 摆放物件时使用这个函数计算物件应该放在什么位置
function Camera2DControllerTool:convertScreenToWorldPos(mouseX , mouseY)
return app.visibleRect:convertScreenToWorldPos2D(mouseX , mouseY);
end

-- 刷新设置时调用
function Camera2DControllerTool:refreshSetting()
app.setting.ScreenScale = cc.clampf(app.setting.ScreenScale , app.setting.ScreenScaleMin , app.setting.ScreenScaleMax);
-- 设置相机缩放
app.mainCamera:getNode():setScale(1 / app.setting.ScreenScale);

app.background:removeAllChildren();
-- 设置OpenGL背景颜色
gl.clearColor(0,0,0,0);

-- 画手机外壳
if app.setting.ShowIPhone5 then
local bgIphone5 = cc.Sprite:create("Editor/iphone5.png");
app.background:addChild(bgIphone5)
end

-- 设置背景颜色
local bgColor = cc.LayerColor:create(app.setting.BackgroundColor);
bgColor:setContentSize(cc.size(app.setting.ResourceSize.width,app.setting.ResourceSize.height))
bgColor:setAnchorPoint(app.setting.OriginAnchor)
bgColor:ignoreAnchorPointForPosition(false);
bgColor:setGlobalZOrder(-100000000);
--app.background:addChild(bgColor)
-- 创建背景图
if app.setting.BackgroundImage ~= "" then
local bg = cc.Sprite:create(app.setting.BackgroundImage);
local size = bg:getContentSize();
bg:setAnchorPoint(app.setting.OriginAnchor)
app.background:addChild(bg)
end

if app.setting.ShowGrid then
-- 创建网格
local vertices = {};
local viewSize = cc.size(app.setting.ResourceSize.width,app.setting.ResourceSize.height);
local gridWidth = app.setting.GridSize.width
local gridHeight = app.setting.GridSize.height
local gridCountY = math.floor(viewSize.height / gridHeight);

local vertexFormat = {};
table.insert(vertexFormat , {size = 3 , usage = cc.VertexFormatUsage.POSITION});
table.insert(vertexFormat , {size = 4 , usage = cc.VertexFormatUsage.COLOR});
local vertices = ManualVertices:new(vertexFormat);
vertices:setColor(app.setting.GridColor);

-- 画横向网格
for i = -gridCountY , gridCountY do
vertices:drawLine(cc.vec3(-viewSize.width , i * gridHeight , 0) , cc.vec3(viewSize.width , i * gridHeight , 0));
end

-- 画竖向网格
local gridCountX = math.floor(viewSize.width / gridWidth);
for i = -gridCountX , gridCountX do
vertices:drawLine(cc.vec3(i * gridWidth , -viewSize.height , 0) , cc.vec3(i * gridWidth , viewSize.height , 0))
end
vertices:setColor(app.setting.AxisColor);
-- 画轴
vertices:drawLine(cc.vec3(-viewSize.width , 0 , 0) , cc.vec3(viewSize.width , 0 , 0))
vertices:drawLine(cc.vec3(0 , -viewSize.height , 0) , cc.vec3(0 , viewSize.height , 0))

local mesh = cc.Mesh:createMesh(vertexFormat , vertices:getVertexCount());
mesh:setPrimitiveType(cc.PrimitiveType.LINES);
mesh:setVertexData(vertices:getVertices() , 0 , vertices:getVertexCount());
mesh:setBoundingBox(vertices:getBoundingBox());

local model = cc.Model:create(mesh);
local material = cc.Material:create("core/preload/shaders/ccDefault.material#ShaderPositionColor");
material:setParameterAutoBinding("CC_MVPMatrix" , "WORLD_VIEW_PROJECTION_MATRIX");
model:setMaterialPointer(material);
local node = cc.Node3D:create();
node:addComponent(model);
app.background:addChild(node);
end
end

return Camera2DControllerTool;

+ 218
- 0
Editor/Camera3DControllerTool.lua Näytä tiedosto

@@ -0,0 +1,218 @@
-- 处理3D相机的移动控制

require("CSharpConstants")
local Camera3DControllerTool = class("Camera3DControllerTool")

function Camera3DControllerTool:ctor()
-- 相机的球面坐标系
-- 半径,离原点的距离,一般是一个正数
-- 经度,0~2PI,0代表正前方,PI代表正后方
-- 纬度,HALF_PI代表水平位置,+PI代表底,0代表顶
self.spherical = cc.vec3(30,1.4,1.4);
-- 相机旋转中心点
self.rotationCenter = cc.vec3(0,0,0);
end

function Camera3DControllerTool:moveTo(button , offsetPos)
-- ALT + 鼠标右键拉近拉远
if button == MouseButtons.Right then
--local offset = (offsetPos.x + -offsetPos.y) * 0.1;
local offset = -offsetPos.x + offsetPos.y;
self.spherical.x = math.max(self.spherical.x + offset * 0.00075 * self.spherical.x);
-- 拉得太近了,就把原点丢远一点
if self.spherical.x <= 1 then
-- 丢10格
local fullOut = 30;
local ray = app.mainCamera:pickRay(0.5,0.5);
-- 沿着屏幕射线把旋转中心点往前移动
self.rotationCenter = cc.vec3Add(cc.vec3Mul(ray:getDirection() , fullOut) , self.rotationCenter);
self.spherical.x = self.spherical.x + fullOut;
end
-- ALT + 鼠标中键平移
elseif button == MouseButtons.Middle then
local offset = app.mainCamera:moveByViewPlane(cc.vec3(offsetPos.x * 0.00075 * self.spherical.x , -offsetPos.y * 0.00075 * self.spherical.x, 0));
self.rotationCenter.x = self.rotationCenter.x + offset.x;
self.rotationCenter.y = self.rotationCenter.y + offset.y;
self.rotationCenter.z = self.rotationCenter.z + offset.z;
-- ALT + 鼠标左键旋转
elseif button == MouseButtons.Left then
self.spherical.y = self.spherical.y + offsetPos.x * 0.003;
self.spherical.z = self.spherical.z + offsetPos.y * 0.003;
end
self:update();
end

function Camera3DControllerTool:update()
-- 计算相对rotationCenter的位置
local pos = Math.SphericalToCartesian(cc.vec3(self.spherical.x , self.spherical.y , self.spherical.z));
pos.x = pos.x + self.rotationCenter.x
pos.y = pos.y + self.rotationCenter.y
pos.z = pos.z + self.rotationCenter.z
app.mainCamera:getNode():setTranslation(pos);
app.mainCamera:lookAt(self.rotationCenter);
end


function Camera3DControllerTool:MoveDown(button, x, y)
-- 按下ALT控制相机
if app.cs.getModifierKeys() ~= Keys.Alt then return end
-- 鼠标的按下位置
self.startPos = app.visibleRect:convertScreenToGLView(x, y);
-- 相机的位置
self.originPos = app.mainCamera:getNode():getPosition();
end

function Camera3DControllerTool:MouseMove(button , x , y)
local glViewPos = app.visibleRect:convertScreenToGLView(x, y);
if self.startPos then
local delta = cc.pSub(glViewPos , self.startPos);
-- 计算结束点
self:moveTo(button , delta);
self.startPos = glViewPos;
end

local point = self:convertScreenToWorldPos(x, y);

local strMapCoord = "";
if app.editor and app.editor.Map then
local tilePos = app.editor.Map:getTilePosition(point.x , point.z);
strMapCoord = string.format(" TilePos:%d,%d" , tilePos.x , tilePos.y);
end
local ort = cc.Orientation:new();
ort:fromQuaternion(app.mainCamera:getNode():getQuaternion());
local dir = ort:toDirection();

return string.format("Mouse:%d,%d Coordinate:%.2f,%.2f,%.2f GLView:%d,%d CameraPos:%.2f,%.2f,%.2f CameraDir:%.2f,%.2f,%.2f" .. strMapCoord , x , y , point.x , point.y , point.z , glViewPos.x , glViewPos.y
, app.mainCamera:getNode():getTranslationX()
, app.mainCamera:getNode():getTranslationY()
, app.mainCamera:getNode():getTranslationZ()
, dir.x
, dir.y
, dir.z
);
end

function Camera3DControllerTool:MoveUp(button, x, y)
if not self.startPos then return end
-- 计算结束点
--self:moveTo(app.visibleRect:convertScreenToGLView(x, y));
self.startPos = nil;
self.originPos = nil;
end

function Camera3DControllerTool:KeyDown(Control , Alt , Shift , KeyCode)
-- F按下
if Control == false and Alt == false and Shift == false and KeyCode == Keys.F then
local node;
-- 如果有物件被选中,就定位到第一个物件
if app.editor and app.editor.SelectedNodes and next(app.editor.SelectedNodes) then
node = next(app.editor.SelectedNodes);
end
-- 如果没物件被选中,则定位到当前物件
if not node and app.editor and app.editor.node then
node = app.editor.node;
end

if node then
self.rotationCenter = node:getWorldTranslation();
local box = node:getSelectBox();
local max = box:getMax();
local distance = math.max(max.x , max.y , max.z , 1)
self.spherical = cc.vec3(distance ,1.4,1.4);
else
self.rotationCenter = cc.vec3(0,0,0);
self.spherical = cc.vec3(30,1.4,1.4);
end
self:update();

end
end

-- 摆放物件时使用这个函数计算物件应该放在什么位置
function Camera3DControllerTool:convertScreenToWorldPos(mouseX , mouseY)
local floorPlane = cc.Plane:new(cc.vec3(0,1,0) , 0);

-- 计算出mainlayer的世界位置
local screenSize = cc.Director:getInstance():getWinSizeInPixels();
local ray = app.mainCamera:pickRay(mouseX / screenSize.width , mouseY / screenSize.height);
local distance = ray:intersectsPlane(floorPlane);
if distance >= 0 then
return ray:getPoint(distance);
else
return ray:getPoint(0);
end
end


-- 刷新设置时调用
function Camera3DControllerTool:refreshSetting()

app.background:removeAllChildren();

-- 画手机外壳
if app.setting.ShowIPhone5 then
local bgIphone5 = cc.Sprite:create("Editor/iphone5.png");
app.background:addChild(bgIphone5)
end
-- 设置OpenGL背景颜色
gl.clearColor(app.setting.BackgroundColor.r / 255 , app.setting.BackgroundColor.g / 255 , app.setting.BackgroundColor.b / 255 ,0);

if app.setting.ShowGrid then
-- 创建网格

local vertexFormat = {};
table.insert(vertexFormat , {size = 3 , usage = cc.VertexFormatUsage.POSITION});
table.insert(vertexFormat , {size = 4 , usage = cc.VertexFormatUsage.COLOR});
local vertices = ManualVertices:new(vertexFormat);
vertices:setColor(app.setting.GridColor);


local viewSize = cc.size(100,100);
local gridWidth = app.setting.GridSize.width
local gridHeight = app.setting.GridSize.height
local gridCountY = math.floor(viewSize.height / gridHeight);

vertices:setColor(app.setting.GridColor);
-- 画横向网格
for i = -gridCountY , gridCountY do
if i ~= 0 then
vertices:drawLine(cc.vec3(-viewSize.width , 0 , i * gridHeight) , cc.vec3(viewSize.width , 0 , i * gridHeight))
end
end

vertices:setColor(app.setting.GridColor);
-- 画竖向网格
local gridCountX = math.floor(viewSize.width / gridWidth);
for i = -gridCountX , gridCountX do
if i ~= 0 then
vertices:drawLine(cc.vec3(i * gridWidth , 0 , -viewSize.height) , cc.vec3(i * gridWidth , 0 , viewSize.height))
end
end
vertices:setColor(app.setting.AxisColor);
-- 画轴
vertices:drawLine(cc.vec3(-viewSize.width , 0 , 0) , cc.vec3(viewSize.width , 0 , 0))
vertices:drawLine(cc.vec3(0 , 0 , -viewSize.height) , cc.vec3(0 , 0 , viewSize.height))

local mesh = cc.Mesh:createMesh(vertexFormat , vertices:getVertexCount());
mesh:setPrimitiveType(cc.PrimitiveType.LINES);
mesh:setVertexData(vertices:getVertices() , 0 , vertices:getVertexCount());
mesh:setBoundingBox(vertices:getBoundingBox());

local model = cc.Model:create(mesh);
local material = cc.Material:create("core/preload/shaders/ccDefault.material#ShaderPositionColor3D");
material:setParameterAutoBinding("CC_MVPMatrix" , "WORLD_VIEW_PROJECTION_MATRIX");
model:setMaterialPointer(material);
local node = cc.Node3D:create();
node:addComponent(model);
app.background:addChild(node);
end
end

return Camera3DControllerTool;

+ 111
- 0
Editor/CombineEffectCommands.lua Näytä tiedosto

@@ -0,0 +1,111 @@
-- 技能撤销操作
-- 删除技能轨迹
function Commands:deleteTrack(ce, track)
local releaseTrack = false
local function redo()
-- 如果preTrack不为空
local preTrack = track:getPrevTrack()
if preTrack ~= nil then
track.PrevTrack = preTrack;
preTrack:setNextTrack(-1);
end
-- nextTrack不为空
local nextTrack = track:getNextTrack()
if nextTrack ~= nil then
track.NextTrack = nextTrack
track:setNextTrack(-1)
end
track:retain()
releaseTrack = true
-- 移除这个轨迹
track:removeFromParent();
-- 更新树
app.cs.updateCombineTree();
-- 选中空
app.cs.selectTrackObject(ce);
return true;
end
local function undo()
ce:addTrack(track);
track:release()
releaseTrack = false
if not tolua.isnull(track.PrevTrack) then
track.PrevTrack:setNextTrack(track:getTrackId())
end
if not tolua.isnull(track.NextTrack) then
track:setNextTrack(track.NextTrack:getTrackId())
end
app.cs.updateCombineTree();
app.cs.selectTrackObject(track);
end
local function clear()
if releaseTrack then
track:release()
end
end
return {redo = redo , undo = undo, clear = clear};
end

-- 创建技能轨迹
function Commands:createTrack(ce, track)
local releaseTrack = false
local function redo()
-- 如果preTrack不为空
local preTrack = track:getPrevTrack()
if preTrack ~= nil then
track.PrevTrack = preTrack;
preTrack:setNextTrack(-1);
end
-- nextTrack不为空
local nextTrack = track:getNextTrack()
if nextTrack ~= nil then
track.NextTrack = nextTrack
track:setNextTrack(-1)
end
-- 添加
ce:addTrack(track);
if releaseTrack then
track:release()
releaseTrack = false
end
-- 更新树
app.cs.updateCombineTree();
-- 选中空
app.cs.selectTrackObject(track);
return true;
end
local function undo()
if not tolua.isnull(track.PrevTrack) then
track.PrevTrack:setNextTrack(track:getTrackId())
end
if not tolua.isnull(track.NextTrack) then
track:setNextTrack(track.NextTrack:getTrackId())
end
track:retain()
releaseTrack = true
-- 移除这个轨迹
track:removeFromParent();
app.cs.updateCombineTree();
app.cs.selectTrackObject(ce);
end
local function clear()
if releaseTrack then
track:release()
end
end
return {redo = redo , undo = undo, clear = clear};
end

+ 378
- 0
Editor/CombineEffectEditor.lua Näytä tiedosto

@@ -0,0 +1,378 @@
local CombineEffectEditor = class("CombineEffectEditor" , require("NodeEditor"));

function CombineEffectEditor:ctor()
CombineEffectEditor.super.ctor(self);
-- 根节点
self.node = nil;
-- 源模型集合的父节点
self.sourceRootNode = nil;
-- 源点集合的父节点
self.sourcePosRootNode = nil;
-- 目标模型集合的父节点
self.targetRootNode = nil;
-- 目标点集合的父节点
self.targetPosRootNode = nil;
-- 技能action
self.CombineEffectAction = nil;
-- 背景场景
self.SceneFile = nil;
end

function CombineEffectEditor:activate()
-- 基类
CombineEffectEditor.super.ctor(self);
-- 设置锚点位置
app.setting.OriginAnchor = cc.p(0.5,0.5);
app:refreshSetting();
-- 初始化技能环境
self:initCombineEffectEnv();
-- 创建一个文本框,用于显示技能是否为无限长
local debugLabel = cc.Text:createNode();
debugLabel:setDefaults();
local config = debugLabel:getFontConfig();
config.fontSize = 40;
config.texColor = cc.c4b(255,0,0,255);
debugLabel:setFontConfig(config);

-- 获取可见视野的像素大小
local screenSize = cc.Director:getInstance():getWinSizeInPixels();
debugLabel:setTranslation(screenSize.width / 2 , 100 , 0)
debugLabel:setText("");
self.debugText = debugLabel;
self.InfinityTipTextNode = cc.Scene:create()
self.InfinityTipTextNode:setActiveCamera(cc.Director:getInstance():getFixedCamera())
self.InfinityTipTextNode:addChild(self.debugText)
app.mainScene:addChild(self.InfinityTipTextNode);
self.InfinityTipTextNode:setVisible(false)
end

function CombineEffectEditor:unactivate()
if self.SceneFile then
self.SceneFile:removeFromParent();
self.SceneFile = nil;
end
self.InfinityTipTextNode:removeFromParent();
-- 清空技能环境
self:unInitCombineEffectEnv();
self:closeCombineEffect();
end

-- 是否可以选中此节点
function CombineEffectEditor:canSelectNode(flag, node)
return true;
end

-- 保存技能文件
function CombineEffectEditor:save(filename)
self.ce:saveToFile(filename);
-- 清空undoredoManager
app.undoRedoManager:clear();
end

-- 创建测试模型
local function createTestHero(modelFile)
-- 这里需要跟游戏里面保持一致
-- 所有需要创建一个中间节点
local heroView;

local pathName , baseName , ext = string.splitFilename(modelFile);
if string.lower(ext) == "gpb" then
heroView = cc.Node:create();
local skeleton = cc.ModelNode:create(modelFile);
createHeroEntity(skeleton);
skeleton.selectTest = function(rect)return false end
heroView:addChild(skeleton);
heroView.ModelNode = skeleton;
heroView.getSelectBox = function()return skeleton:getSelectBox()end
-- 默认播放站立动画
--animEntity:setValue("", );
else
heroView = cc.Node2D:create();
heroView:setContentSize(app.setting.ResourceSize);
local node = createNodeFromFile(modelFile);
heroView.ModelNode = node;
heroView:addChild(node);

heroView.getSelectBox = function()return node:getSelectBox();end;
node:visitNode(function(n)
n.selectTest = function(rect)return false;end;
end);
end
return heroView;
end

-- 创建目标点和目标模型
local function createPositionNode()
local skeleton = cc.ModelNode:create("res/default/DefaultPoint/DefaultPoint.gpb");
-- 默认播放站立动画
--animEntity:setValue("", );
return skeleton;
end

-- 激活技能编辑器时创建技能环境
function CombineEffectEditor:initCombineEffectEnv()
--创建一个源模型、源点、目标模型、目标点
self.defaultCEParams = createDefaultCombineEffectParams();
-- 创建所有的根节点
self.node = cc.Node:create();
app.mainLayer:addChild(self.node);
self.sourceRootNode = cc.Node:create();
self.node:addChild(self.sourceRootNode);
self.sourcePosRootNode = cc.Node:create();
self.node:addChild(self.sourcePosRootNode);
self.targetRootNode = cc.Node:create();
self.node:addChild(self.targetRootNode);
self.targetPosRootNode = cc.Node:create();
self.node:addChild(self.targetPosRootNode);
end

-- 激活技能编辑器时创建技能环境
function CombineEffectEditor:unInitCombineEffectEnv()
self.defaultCEParams = nil;
self.node:removeFromParent();
end

--C#那边调用
function CombineEffectEditor:createCEParamsNode(paramType, posWithMouse)
local node = nil;
if paramType == "SourceModel" then
-- 创建一个源模型
node = createTestHero(app.setting.SourceModelFile);
-- 加入到节点系统
self.sourceRootNode:addChild(node);
elseif paramType == "TargetModel" then
-- 创建一个源模型
node = createTestHero(app.setting.TargetModelFile);
-- 加入到节点系统
self.targetRootNode:addChild(node);
elseif paramType == "SourcePos" then
-- 创建一个源模型
node = createPositionNode();
-- 加入到节点系统
self.sourcePosRootNode:addChild(node);
elseif paramType == "TargetPos" then
-- 创建一个源模型
node = createPositionNode();
-- 加入到节点系统
self.targetPosRootNode:addChild(node);
end
-- 设置世界坐标
if posWithMouse then
local worldPos = app.cameraController:convertScreenToWorldPos(posWithMouse.x , posWithMouse.y);
local nodePos = node:getParent():convertToNodeSpace(worldPos);
node:setTranslation(worldPos);
end
return node;
end

function CombineEffectEditor:play()
-- 播放一个技能
if self.ce == nil then
return;
end
-- 先停止技能
self:stop()
-- 清空数据
self.defaultCEParams.SourceNode = {};
self.defaultCEParams.TargetNode = {};
self.defaultCEParams.SourcePos = {};
self.defaultCEParams.TargetPos = {};
-- 收集技能参数
self.defaultCEParams.ParentNode = app.mainLayer;
self.defaultCEParams.CameraNode = app:getMainCameraShakeNode()
-- 源模型
for i, v in pairs(self.sourceRootNode:getChildren()) do
table.insert(self.defaultCEParams.SourceNode, v.ModelNode);
end
-- 目标模型
for i, v in pairs(self.targetRootNode:getChildren()) do
table.insert(self.defaultCEParams.TargetNode, v.ModelNode);
end
-- 源点
for i, v in pairs(self.sourcePosRootNode:getChildren()) do
-- 获取坐标点
local pos = getWorldPositionToNode(v, self.defaultCEParams.ParentNode);
table.insert(self.defaultCEParams.SourcePos, pos);
end
-- 目标点
for i, v in pairs(self.targetPosRootNode:getChildren()) do
-- 获取坐标点
local pos = getWorldPositionToNode(v, self.defaultCEParams.ParentNode);
table.insert(self.defaultCEParams.TargetPos, pos);
end
-- 创建一个action来播放
self.CombineEffectAction = cc.CombineEffectAction:createWithInstance(self.ce, self.defaultCEParams, nil, nil)
self.node:runAction(self.CombineEffectAction)
-- 检查技能是否为无限长
self:checkCombineEffectInfinity()
end

function CombineEffectEditor:stop()
if not tolua.isnull(self.CombineEffectAction) then
self.node:stopAction(self.CombineEffectAction)
self.CombineEffectAction = nil
end
if not tolua.isnull(self.ce) then
self.ce:stop()
end
end

-- 检测技能是否无限长
function CombineEffectEditor:checkCombineEffectInfinity()
if self.ce == nil then
return
end
local text = ""
local hitCount = 0;
for i , v in pairs(self.ce:getChildren()) do
if v:isInfinite() then
text = text .. "轨迹名字:" .. v:getName() .. " 轨迹ID:" .. tostring(v:getTrackId()) .. "为无限长,请注意!!!\n";
end
if v:getStartEventName() == "OnHit" then
hitCount = hitCount + 1;
end
end

if hitCount ~= 1 then
if hitCount == 0 then
text = text .. "OnHit事件没配置,必须配置一个OnHit事件!!\n";
else
text = text .. "OnHit事件被配置了多于1个,只能配置一个OnHit事件!!\n";
end
end

if text == "" then
self.InfinityTipTextNode:setVisible(false)
else
self.debugText:setText(text);

self.InfinityTipTextNode:setVisible(true)
end
end

-- 关闭光效
function CombineEffectEditor:closeCombineEffect()
if not tolua.isnull(self.CombineEffectAction) then
self.node:stopAction(self.CombineEffectAction)
self.CombineEffectAction = nil
end
-- 释放技能
if not tolua.isnull(self.ce) then
self.ce:release()
end
end

-- 创建新的光效
function CombineEffectEditor:newCombineEffect()
self:closeCombineEffect();
self.ce = cc.CombineEffect:create();
self.ce:retain()
return self.ce;
end


function CombineEffectEditor:loadCombineEffect(ceFile)
self:closeCombineEffect();
local ce = createCombineEffect(ceFile);
self.ce = ce;
self.ce:retain()
-- 检查技能是否为无限长
self:checkCombineEffectInfinity()
return self.ce;
end

-- 删除所有选中的节点
-- 技能编辑器根其他编辑器不一样,这里不支持撤销
function CombineEffectEditor:commandDeleteSelectNodes()
if next(self.SelectedNodes) == nil then
return;
end
-- 这里需要自己搜集,因为self.sourceRootNode等空节点也会被select出来所以这里需要手动搜索
-- 搜集技能参数
local ceNodes = {}
-- 源模型
for i, v in pairs(self.sourceRootNode:getChildren()) do
if self.SelectedNodes[v] then
table.insert(ceNodes, v);
end
end
-- 目标模型
for i, v in pairs(self.targetRootNode:getChildren()) do
if self.SelectedNodes[v] then
table.insert(ceNodes, v);
end
end
-- 源点
for i, v in pairs(self.sourcePosRootNode:getChildren()) do
if self.SelectedNodes[v] then
table.insert(ceNodes, v);
end
end
-- 目标点
for i, v in pairs(self.targetPosRootNode:getChildren()) do
if self.SelectedNodes[v] then
table.insert(ceNodes, v);
end
end
for i,v in pairs(ceNodes) do
self:deleteNode(v);
end
end

-- 删除一个轨迹
function CombineEffectEditor:commandDeleteTrack(track)
local command = Commands:deleteTrack(self.ce, track);
app.undoRedoManager:doCommand(command);
end

-- 通过命令创建一个轨迹
function CombineEffectEditor:commandCreateTrack(trackType)
local track = cc[trackType]:create();
local command = Commands:createTrack(self.ce, track);
app.undoRedoManager:doCommand(command);
end

-- 复制节点到另一个节点下面
function CombineEffectEditor:commandCopyNode(track)
track:setTrackId(0)
local command = Commands:createTrack(self.ce, track);
app.undoRedoManager:doCommand(command);
end

-- 设置背景场景
function CombineEffectEditor:setSceneFile(sceneFile)
if self.SceneFile then
self.SceneFile:removeFromParent();
end
local node = createNodeFromFile(sceneFile);
self.SceneFile = node;
self.node:addChild(node);
end

return CombineEffectEditor;


+ 471
- 0
Editor/Commands.lua Näytä tiedosto

@@ -0,0 +1,471 @@
Commands = {}

-- 批量命令
function Commands:batchCommand(commands)
--[[
local function isParent(node , parent)
local myParent = node:getParent();
if myParent == parent then
return true;
else
if myParent then
return isParent(myParent , parent);
end
end
end

local function sortFunction(a , b)
return isParent(b.node , a.node);
end
table.sort(commands , sortFunction);

print("BatchStart");
for i, v in ipairs(commands) do
print("节点" , v.node:getName());
end
print("BatchEnd");
]]

local function redo()
if next(commands) == nil then
return false;
end
for i, v in ipairs(commands) do
v:redo();
end
return true;
end
--
local function undo()
for i = #commands , 1 , -1 do
commands[i]:undo();
end
end
local function clear()
for i, v in ipairs(commands) do
if type(v.clear) == "function" then
v:clear();
end
end
end
return { redo = redo, undo = undo, clear = clear };
end

-- 选中命令
--[[function Commands:select(nodes)
local selectNodes = clone(nodes);
-- 恢复操作
local function redo()
if table.nums(selectNodes) <= 0 then
return false;
end
-- 通知c#那边选中第一个
if selectNodes[1] then
app.cs.setPropertyObject(selectNodes[1]);
end
for i , v in pairs(selectNodes) do
app.editor:selectNode(v);
end
return true;
end
-- 撤销操作
local function undo()
for i , v in pairs(selectNodes) do
app.editor:unSelectNode(v);
end
end
return {redo = redo , undo = undo};
end

-- 取消选中命令
function Commands:unselect(nodes)
local selectNodes = clone(nodes);
-- 恢复操作
local function redo()
if table.nums(selectNodes) <= 0 then
return false;
end
for i , v in pairs(selectNodes) do
app.editor:unSelectNode(v);
end
return true;
end
-- 撤销操作
local function undo()
for i , v in pairs(selectNodes) do
app.editor:selectNode(v);
end
end
return {redo = redo , undo = undo};
end--]]

-- 移动命令
-- 这里使用的node的父节点空间的位置,使用者要在外部转换好
function Commands:moveNode(node , newPos)
local originalPos;
-- 恢复操作
local function redo()
if not node then
return false;
end
originalPos = node:getTranslation();
node:setTranslation(newPos);
-- 通知c#设置关键帧
if app.cs.setKeyFrame then
app.cs.setKeyFrame(node , "位置");
end
return true;
end
-- 撤销操作
local function undo()
node:setTranslation(originalPos);
-- 通知c#设置关键帧
if app.cs.setKeyFrame then
app.cs.setKeyFrame(node , "位置");
end
end
return {redo = redo , undo = undo , node = node};
end


-- 旋转命令
-- 这里使用的node的父节点空间的位置,使用者要在外部转换好
function Commands:rotateNode(node , newPos)
local originalPos;
-- 恢复操作
local function redo()
if not node then
return false;
end
originalPos = node:getEulerRotation();
node:setEulerRotation(newPos);
-- 通知c#设置关键帧
if app.cs.setKeyFrame then
app.cs.setKeyFrame(node , "旋转");
end
return true;
end
-- 撤销操作
local function undo()
node:setEulerRotation(originalPos);
-- 通知c#设置关键帧
if app.cs.setKeyFrame then
app.cs.setKeyFrame(node , "旋转");
end
end
return {redo = redo , undo = undo , node = node};
end


-- 移动命令
-- 这里使用的node的父节点空间的位置,使用者要在外部转换好
function Commands:setWorldPosition(node , newPos)
local originalPos;
-- 恢复操作
local function redo()
if not node then
return false;
end
originalPos = node:getWorldPosition();
node:setWorldPosition(newPos);
-- 通知c#设置关键帧
if app.cs.setKeyFrame then
app.cs.setKeyFrame(node , "位置");
end
return true;
end
-- 撤销操作
local function undo()
node:setWorldPosition(originalPos);
-- 通知c#设置关键帧
if app.cs.setKeyFrame then
app.cs.setKeyFrame(node , "位置");
end
end
return {redo = redo , undo = undo , node = node};
end



-- 改变大小命令
-- 这里使用的node的父节点空间的位置,使用者要在外部转换好
function Commands:sizeNode(node , newSize)
local originalSize;
-- 恢复操作
local function redo()
if not node then
return false;
end
originalSize = node:getSize();
node:setSize(newSize);
-- 通知c#设置关键帧
if app.cs.setKeyFrame then
app.cs.setKeyFrame(node , "尺寸");
end
app.editor:relayoutAll();
return true;
end
-- 撤销操作
local function undo()
node:setSize(originalSize);
-- 通知c#设置关键帧
if app.cs.setKeyFrame then
app.cs.setKeyFrame(node , "尺寸");
end
app.editor:relayoutAll();
end
return {redo = redo , undo = undo , node = node};
end

-- 删除一个节点
function Commands:deleteNode(node)
local parent;
local childrenIndexs = {};
local releaseNode = true;
-- 恢复操作
local function redo()
parent = node:getParent();
-- 记录子节点的索引位置
for i, v in pairs(parent:getChildren()) do
childrenIndexs[v] = i;
end
node:retain();
node:removeFromParent();
-- 通知c#更新树状结构
app.cs.deleteNode(node);
-- 删除这个节点
app.editor:deleteNode(node);
-- 选中当前节点
app.cs.setPropertyObject(parent);
--app.editor:selectNode(parent);
releaseNode = true;
app.editor:relayoutAll();
return true;
end
-- 撤销操作
local function undo()
parent:addChild(node);
app.editor:autoSetNodeName(node);
for i, v in pairs(parent:getChildren()) do
v:setOrderOfArrival(childrenIndexs[v]);
end
-- 重新排序
parent:sortAllChildren();
node:release();
-- 更新下树形结构
app.cs.addNode(node , node , childrenIndexs[node] - 1);
-- 清空序列
childrenIndexs = {};
-- 选中这个节点
app.editor:selectNode(node);
releaseNode = false;
app.editor:relayoutAll();
end
-- 清空操作
local function clear()
if releaseNode then
node:release();
end
end
return {redo = redo , undo = undo, clear = clear , node = node};
end

-- 改变节点
function Commands:modifyNode(node, newParent)
local originParent;
-- 恢复操作
local function redo()
if not node or not newParent or not node:getParent() then
return false;
end
originParent = node:getParent();
node:retain();
node:removeFromParent();
newParent:addChild(node);
app.editor:autoSetNodeName(node);
node:release();
-- 通知编辑器的树更新
app.cs.modifyNode(node, newParent);
app.editor:relayoutAll();
return true;
end
-- 撤销操作
local function undo()
node:retain();
node:removeFromParent();
originParent:addChild(node);
app.editor:autoSetNodeName(node);
node:release();
-- 通知编辑器的树更新
app.cs.modifyNode(node, originParent);
app.editor:relayoutAll();
end
return {redo = redo , undo = undo , node = node};
end

-- 交换节点
function Commands:swapNode(node1, node2)
local originParent;
-- 恢复操作
local function redo()
if not node1 or not node1:getParent() or node1:getParent() ~= node2:getParent() then
return false;
end
originParent = node1:getParent();
originParent:swapChild(node1 , node2);
-- 通知编辑器的树更新
app.cs.swapNode(node1, node2);
app.editor:relayoutAll();
return true;
end
-- 撤销操作
local function undo()
originParent:swapChild(node1 , node2);
-- 通知编辑器的树更新
app.cs.swapNode(node1, node2);
app.editor:relayoutAll();
end
return {redo = redo , undo = undo , node = node1};
end
-- 拷贝一个节点
function Commands:addNode(node, parentNode)
local releaseNode = false;
local function redo()
if node == nil or parentNode == nil then
return false;
end
local oldCount = node:getReferenceCount();
-- 添加节点
parentNode:addChild(node);
app.editor:autoSetNodeName(node);
local newCount = node:getReferenceCount();
-- 添加节点失败,例如UIPageView不支持添加非Layout派生的节点成为他的子节点
if newCount == oldCount then
return false;
end
if releaseNode then
node:release();
end
-- 更新树形结构
app.cs.addNode(node , node , -1);
-- 选中当前节点
app.cs.setPropertyObject(node);
releaseNode = false;
app.editor:relayoutAll();
return true;
end
local function undo()
if node == nil or parentNode == nil then
return;
end
-- 这里需要保存下
node:retain();
node:removeFromParent();
-- 更新树形结构
app.cs.deleteNode(node);
app.cs.setPropertyObject(parentNode);
releaseNode = true;
app.editor:relayoutAll();
end
local function clear()
if releaseNode then
node:release();
end
end
return { redo = redo, undo = undo, clear = clear , node = node };
end

-- 拷贝一个节点动画
function Commands:copyNodeAnim(node, parentNode)
local releaseNode = false;
local copyAnim = parentNode:saveAnimation(cc.CURVE_ANIMATION);
local function redo()
if node == nil or parentNode == nil then
return false;
end
-- 复制动画
parentNode:removeAllAnimations();
node:cloneIntoAnim(parentNode);

if releaseNode and not tolua.isnull(node) then
node:release();
end
-- 选中当前节点
app.cs.setPropertyObject(parentNode);
releaseNode = false;
app.editor:relayoutAll();
return true;
end
local function undo()
if node == nil or parentNode == nil then
return;
end
parentNode:removeAllAnimations();
local anim = parentNode:loadAnimation(copyAnim)
parentNode:addAnimation(anim);
-- 更新树形结构
app.cs.setPropertyObject(parentNode);
releaseNode = true;
app.editor:relayoutAll();
end
local function clear()
if releaseNode and not tolua.isnull(node) then
node:release();
end
end
return { redo = redo, undo = undo, clear = clear , node = node };
end

require("CombineEffectCommands")

+ 113
- 0
Editor/CompareVersion.lua Näytä tiedosto

@@ -0,0 +1,113 @@
-- 版本对比功能
local newRes = {}
local oldRes = {}
-- 读取xml文件
local function readXml(sourceFile, resList)
local pathName, baseName, ext = string.splitFilename(sourceFile);
if ext ~= "xml" or baseName == "update.json" then
return
end
if resList[baseName] == nil then
resList[baseName] = {}
end
-- 读取xml文件
local fileData = loadfileData(sourceFile)
-- 解密解压数据
local romFileData = cc.FilePackage:decrypt(FilePackage.uncompress(fileData))
-- 解析xml文件
local function onStartElement(name , atts)
if name == "file" then
resList[baseName][atts.name] = atts
end
end
local ret, result = tiny.eval(romFileData , onStartElement)
if ret == nil then
print("文件" .. sourceFile .. "解析失败", result);
end
end

-- 比较具体的目录
local function _compareRes(newPath, oldPath, resultPath, resVersion)
local newResPath = newPath .. "/" .. resVersion
local oldResPath = oldPath .. "/" .. resVersion
local resultResPath = resultPath .. "/" .. resVersion
createDir(newResPath);
createDir(oldResPath);
createDir(resultResPath);
-- 清空下资源
newRes.resVersion = {}
oldRes.resVersion = {}
-- 载入对应目录的xml文件
visitPath(newResPath, readXml, newRes.resVersion);
visitPath(oldResPath, readXml, oldRes.resVersion);
-- 创建一个xml文件
local versionInfo = xml.new("root");
-- 需要更新文件的数量
versionInfo.updateFileCount = 0
-- 需要更新文件的大小
versionInfo.updateFileSize = 0
local xmlFileName
-- 逐个文件对比
for i, v in pairs(newRes.resVersion) do
-- 创建一个xml文件
local fileXml = xml.new("root")
fileXml.updateFileCount = 0
fileXml.updateFileSize = 0
for name, fileInfo in pairs(v) do
-- 获取老版本对应的资源
local oldFileInfo
if oldRes.resVersion[i] == nil then
oldFileInfo = nil
else
oldFileInfo = oldRes.resVersion[i][name]
end
if oldFileInfo == nil or fileInfo.md5 ~= oldFileInfo.md5 then
-- 需要更新这个文件
local fileItem = xml.new("file")
fileItem.origin = fileInfo.origin
fileItem.name = fileInfo.name
fileItem.md5 = fileInfo.md5
fileItem.compressedSize = fileInfo.compressedSize
fileItem.size = fileInfo.size
fileItem.offset = fileInfo.offset
table.insert(fileXml, fileItem)
fileXml.updateFileCount = fileXml.updateFileCount + 1
fileXml.updateFileSize = fileXml.updateFileSize + fileInfo.compressedSize
end
end
-- 保存这个包需要更新的文件
versionInfo.updateFileCount = versionInfo.updateFileCount + fileXml.updateFileCount
versionInfo.updateFileSize = versionInfo.updateFileSize + fileXml.updateFileSize
local xmlInfoData = fileXml:toString();
saveFile(xmlInfoData, resultResPath .. "/" .. i);
end
-- 保存整个需要更新的文件
local xmlData = versionInfo:toString()
saveFile(xmlData, resultResPath .. "/" .. "result.xml");
-- 打印出这次需要更新资源的大小
local updateSizeStr
if versionInfo.updateFileSize / 1024 / 1024 >= 1 then
updateSizeStr = versionInfo.updateFileSize / 1024 / 1024 .. "M"
else
updateSizeStr = versionInfo.updateFileSize / 1024 .. "KB"
end
print(resVersion .. "需要更新的资源包大小:", updateSizeStr)
end

-- 对比两个目录下的资源版本
function compareVersion(newPath, oldPath, resultPath)
-- 比较png
_compareRes(newPath, oldPath, resultPath, "png")
-- 比较etc
_compareRes(newPath, oldPath, resultPath, "etc")
-- 比较pvr
_compareRes(newPath, oldPath, resultPath, "pvr")
end

+ 654
- 0
Editor/CompileFile.lua Näytä tiedosto

@@ -0,0 +1,654 @@
local bit32 = (bit32 or require("bit"))

-- 一个缓存文件
local CacheFile = defClass("CacheFile"
, defVar("origin" , VT_String)
, defVar("name" , VT_String)
, defVar("md5" , VT_String)
, defVar("originSize" , VT_Double)
, defVar("compileSize" , VT_Double)
, defVar("encryptSize" , VT_Double)
, defVar("compressedSize" , VT_Double)
, defVar("modifyTime" , VT_Double)
, defVar("compressedFile" , VT_String)
, defVar("encryptFile" , VT_String)
);
-- 一组缓存文件
local CacheFileList = defClass("CacheFileList"
, defVar("list" , VT_Map(VT_String , CacheFile))
);

-- 保存所有缓存的文件
gCacheFiles = CacheFileList:new();
-- 所有配置文件的缓存
gConfigDescCacheFiles = nil
-- 保存所有的xml文件对应的desc解析文件
gConfigXmlToDesc = {}

local function getNextPowerOfTwo(value)
local i = 1;
while i < value do
i = i * 2;
end

return i;
end

local function isPow2(size)
return getNextPowerOfTwo(size) == size;
end

-- 载入文件数据
function loadfileData(filename)
local fileData;
-- 读取整个文件数据
local file = io.open(filename , "rb");
fileData = file:read("*a");
file:close();
return fileData;
end


--/* These describe the color_type field in png_info. */
--/* color type masks */
PNG_COLOR_MASK_PALETTE = 1
PNG_COLOR_MASK_COLOR = 2
PNG_COLOR_MASK_ALPHA = 4

--/* color types. Note that not all combinations are legal */
PNG_COLOR_TYPE_GRAY = 0
PNG_COLOR_TYPE_PALETTE = (PNG_COLOR_MASK_COLOR + PNG_COLOR_MASK_PALETTE)
PNG_COLOR_TYPE_RGB = (PNG_COLOR_MASK_COLOR)
PNG_COLOR_TYPE_RGB_ALPHA = (PNG_COLOR_MASK_COLOR + PNG_COLOR_MASK_ALPHA)
PNG_COLOR_TYPE_GRAY_ALPHA =(PNG_COLOR_MASK_ALPHA)


-- 编译png文件成pvr文件,并返回pvr文件名
local function _compilePngToPvr(sourceFile)
local pathName , baseName , ext = string.splitFilename(sourceFile);
-- 只打包这三个目录
if not (string.startsWith(pathName , "res/effect/")
or string.startsWith(pathName , "res/animation/")
or string.startsWith(pathName , "res/scene/")) then
return sourceFile;
end

local image = cc.Image:analysisPngFile(sourceFile);

-- PVR转换规则,长宽相等,大小是2次幂。
if image.image_width ~= image.image_height then
return sourceFile;
end

-- 不是2次幂
if not isPow2(image.image_width) or not isPow2(image.image_height) then
return sourceFile;
end

-- 最小8*8
if image.image_width < 8 or image.image_height < 8 then
return sourceFile;
end

local pvrFormat;
print("image" , table.tostring(image));

-- 根据纹理格式来决定pvr格式
if image.color_type == PNG_COLOR_TYPE_RGB then
pvrFormat = "PVRTC1_4_RGB";
elseif image.color_type == PNG_COLOR_TYPE_RGB_ALPHA then
pvrFormat = "PVRTC1_4";
elseif image.color_type == PNG_COLOR_TYPE_GRAY_ALPHA then
pvrFormat = "PVRTC1_2";
elseif image.color_type == PNG_COLOR_TYPE_GRAY then
pvrFormat = "PVRTC1_2_RGB";
elseif image.color_type == PNG_COLOR_TYPE_PALETTE then
if image.expand_color_type == PNG_COLOR_TYPE_RGB_ALPHA then
print("调色板带透明");
pvrFormat = "PVRTC1_4";
else
print("调色板不带透明");
pvrFormat = "PVRTC1_2_RGB";
end
else
return sourceFile;
end
local pvrFile = "cache/" .. baseName .. "." .. pvrFormat .. ".pvr";

local exFlags = "";
-- 场景光效人物,要用mipmap
--exFlags = exFlags .. " -m";

local cmdLine = string.format('PVRTexTool -i "%s" -o "%s" -f "%s"%s' , sourceFile , pvrFile , pvrFormat , exFlags);
local out = io.popen(cmdLine , "r");
print("正在转换成pvr:" .. cmdLine);
print(out:read("*a"));
out:close();
local atts = lfs.attributes(pvrFile , "modification");
if not atts then
error("转换pvr失败" .. sourceFile);
return sourceFile;
end
return pvrFile;
end
-- 编译png文件成pvr文件,并返回pvr文件数据
local function compilePngToPvr(sourceFile)
local fileName = _compilePngToPvr(sourceFile);
return loadfileData(fileName);
end

-- 编译png文件成etc文件,并返回etc文件名
local function _compilePngToEtc(sourceFile)
local pathName , baseName , ext = string.splitFilename(sourceFile);
-- 只打包这三个目录
if not (string.startsWith(pathName , "res/effect/")
or string.startsWith(pathName , "res/animation/")
or string.startsWith(pathName , "res/scene/")) then
return sourceFile;
end

local image = cc.Image:analysisPngFile(sourceFile);

-- 不是2次幂
if not isPow2(image.image_width) or not isPow2(image.image_height) then
return sourceFile;
end

-- 最小8*8
if image.image_width < 8 or image.image_height < 8 then
return sourceFile;
end


local etcFormat;

-- 根据纹理格式来决定etc格式
if image.expand_color_type == PNG_COLOR_TYPE_RGB or image.expand_color_type == PNG_COLOR_TYPE_GRAY then
etcFormat = "ETC1";
else
return sourceFile;
end
local etcFile = "cache/" .. baseName .. "." .. etcFormat .. ".pvr";

local exFlags = "";
-- 场景光效人物,要用mipmap
--exFlags = exFlags .. " -m";

local cmdLine = string.format('PVRTexTool -i "%s" -o "%s" -f "%s"%s' , sourceFile , etcFile , etcFormat , exFlags);
local out = io.popen(cmdLine , "r");
print("正在转换成etc:" .. cmdLine);
print(out:read("*a"));
out:close();
local atts = lfs.attributes(etcFile , "modification");
if not atts then
error("转换etc失败" .. sourceFile);
return sourceFile;
end
return etcFile;
end
-- 编译png文件成etc文件,并返回etc文件数据
local function compilePngToEtc(sourceFile)
local fileName = _compilePngToEtc(sourceFile);
return loadfileData(fileName);
end

-- 编译png文件成etc文件,并返回etc文件名
local function _compilePngToAtc(sourceFile)
local pathName , baseName , ext = string.splitFilename(sourceFile);
if string.startsWith(pathName , "res/scene/scene_maoxian_002") then
print("res/scene/scene_maoxian_002不能压缩纹理,文件名" .. sourceFile);
return sourceFile;
end
-- 只打包这三个目录
if not (string.startsWith(pathName , "res/effect/")
or string.startsWith(pathName , "res/animation/")
or string.startsWith(pathName , "res/ui/")
or string.startsWith(pathName , "res/scene/"))then
print("指定目录之外的纹理不需要压缩,文件名" .. sourceFile);
return sourceFile;
end

local image = cc.Image:analysisPngFile(sourceFile);

-- 最小8*8
if image.image_width < 8 or image.image_height < 8 then
print("长宽小于8不能压缩纹理,文件名" .. sourceFile);
return sourceFile;
end


local etcFormat;
-- 根据纹理格式来决定atc格式
if image.color_type == PNG_COLOR_TYPE_RGB or image.expand_color_type == PNG_COLOR_TYPE_RGB then
etcFormat = "RGB";
elseif image.color_type == PNG_COLOR_TYPE_RGB_ALPHA or image.expand_color_type == PNG_COLOR_TYPE_RGB_ALPHA then
etcFormat = "RGBA"
else
print("Texture color type is", image.color_type)
print("Texture expand color type is", image.expand_color_type)
print("纹理格式不是RGB或者是RGBA格式,不能转换成压缩纹理,文件名" .. sourceFile);
return sourceFile;
end
--
local atcFile = "cache/" .. baseName .. "." .. etcFormat .. ".atc";
local cmdLine = string.format('atc_texture "%s" "%s"' , sourceFile , atcFile);
local out = io.popen(cmdLine , "r");
print("正在转换成atc:" .. cmdLine);
print(out:read("*a"));
out:close();
local atts = lfs.attributes(atcFile , "modification");
if not atts then
error("转换atc失败" .. sourceFile);
return sourceFile;
end
return atcFile;
end

-- 编译png文件成atc文件,并返回atc文件数据
local function compilePngToAtc(sourceFile)
local fileName = _compilePngToAtc(sourceFile);
return loadfileData(fileName);
end

-- 编译lua文件,并返回编译后的数据
function compileLua52(filename)
-- 编译lua
print("正在编译Lua52:" , filename);
local cmdLine = string.format('luac.exe -o "luac_tmp.bin" "%s"' , cc.FileUtils:getInstance():fullPathForFilename(filename));
local out = io.popen(cmdLine , "r");
print("正在运行:" .. cmdLine);
print(out:read("*a"));
local r , what , code = out:close();
if code ~= 0 then
error("编译脚本出错:" .. filename);
end
return loadfileData(cc.FileUtils:getInstance():fullPathForFilename("luac_tmp.bin"));
end

-- 编译lua文件,并返回编译后的数据
function compileLuajit(filename)
-- 编译lua
print("正在编译Luajit:" , filename);
local cmdLine = string.format('luajit -b -g "%s" "luac_tmp.bin"' , cc.FileUtils:getInstance():fullPathForFilename(filename));
local out = io.popen(cmdLine , "r");
print("正在运行:" .. cmdLine);
print(out:read("*a"));
local r , what , code = out:close();
if code ~= 0 then
error("编译脚本出错:" .. filename);
end
return loadfileData(cc.FileUtils:getInstance():fullPathForFilename("luac_tmp.bin"));
end

function compileLua(filename)
if hasCmdArg("-lua") then
return compileLua52(filename);
else
return compileLuajit(filename);
end
end


local ConfigLoaded = false;
function loadAllXML()
if ConfigLoaded then return; end
ConfigLoaded = true;
local s = app.config.Setting;
local r = app.config.RomSetting;
app.config = require("LoadAllConfigs")
app.config.Setting = s;
app.config.RomSetting = r;
for i, v in pairs(app.config) do
if type(v) == "function" then
app.config[i] = v()
end
end
end

-- 获取对应版本的lua后缀名
local function getLuaExtName(baseName)
local saveBaseName
if hasCmdArg("-lua") then
saveBaseName = baseName .. ".lua52";
else
saveBaseName = baseName .. ".luajit";
end
return saveBaseName
end

-- 判断一个策划配置的xml文件依赖的desc文件是否改变
local function isConfigXmlDescChanged(xmlFileName)
local descFileName = gConfigXmlToDesc[xmlFileName]
if not descFileName then
print("配置文件:" .. xmlFileName .. "统计不到对应的desc缓存文件,xml文件需要重新打包")
return true
end
-- 读取文件
local atts = lfs.attributes(descFileName);
if not atts then
error("找不到文件" .. descFileName);
return true;
end
-- 拆分desc文件名
local pathName, baseName, ext = string.splitFilename(descFileName);
local saveBaseName = getLuaExtName(baseName)
local cacheFile = gConfigDescCacheFiles.list[saveBaseName];
if cacheFile then
if cacheFile.origin == descFileName and cacheFile.modifyTime == atts.modification and cacheFile.originSize == atts.size then
-- 文件没有改变则不需要重新生成
return false
end
end
print("配置文件:" .. xmlFileName .. "对应的desc文件:" .. descFileName .. "改变了,xml文件需要重新打包")
return true
end

local function optimiseRewardConfig(RewardConfig)
local deleted = {}
for i , v in pairs(RewardConfig) do
--print("删掉空奖励:" , table.tostring(v));
if not v.epFull
and not v.apFull
and #v.gold == 1 and v.gold[1] == ""
and #v.ticket == 1 and v.ticket[1] == ""
and #v.redGem == 1 and v.redGem[1] == ""
and #v.goods == 1 and #v.goods[1] == 1 and v.goods[1][1] == ""
and #v.treasure == 0
and #v.awardHero == 0
and #v.awardHeroSaga == 0
and #v.awardRune == 0
and #v.awardRuneChip == 0
and #v.awardHeroSoul == 0
and (not v.awardPrivilege or v.awardPrivilege == 0)
then
table.insert(deleted , i);
print("删掉空奖励:" , i);
end
end
print("总共删掉空奖励:" , #deleted);
for i , v in ipairs(deleted) do
RewardConfig[v] = nil;
end
end

local function optimiseHeroAwardConfig(AwardConfig)
local deleted = {}
for i , v in pairs(AwardConfig) do
if #v.awardValue == 0 or (#v.awardDungeon == 1 and #v.awardDungeon[1] == 0) then
table.insert(deleted , i);
print("删掉如何获得的空配置:" , i);
end
end
print("总共删掉如何获得空配置:" , #deleted);
for i , v in ipairs(deleted) do
AwardConfig[v] = nil;
end
end

local function copyFile(dstFile , srcFile)
local src = io.open(srcFile , "rb");
local dst = io.open(dstFile , "wb");
dst:write(src:read("*a"));
dst:close();
src:close();
end

-- 编译xml文件,并返回编译后的数据
function compileXml(sourceFile)
loadAllXML();
local luaData;
for i , v in pairs(app.config) do
if i ~= "Setting" and i ~= "RomSetting" then
if type(v.LuaFile) == "string" then
local filename = v.XmlFile;
if "dataconfig/" .. filename == sourceFile then
local luaFile = "cache/" .. filename .. ".lua";
if filename == "pvpRewardConfig.xml"
or filename == "riftRewardConfig.xml"
or filename == "castleRewardConfig.xml"
or filename == "vipRewardConfig.xml"
or filename == "commonRewardConfig.xml"
or filename == "appRewardConfig.xml"
or filename == "rankRewardConfig.xml"
or filename == "pveRewardConfig.xml"
or filename == "achieveRewardConfig.xml" then
optimiseRewardConfig(v);
end
if filename == "awardHeroSoulConfig.xml"
or filename == "awardStarUpFoodConfig.xml" then
optimiseHeroAwardConfig(v);
end
copyFile(luaFile , v.LuaFile);
luaData = compileLua(luaFile);
break;
end
else
local desc = v:getConfigDesc();
local filename = desc.XMLFile;

if "dataconfig/" .. filename == sourceFile then
local luaFile = "cache/" .. filename .. ".lua";
if filename == "pvpRewardConfig.xml"
or filename == "riftRewardConfig.xml"
or filename == "castleRewardConfig.xml"
or filename == "vipRewardConfig.xml"
or filename == "commonRewardConfig.xml"
or filename == "appRewardConfig.xml"
or filename == "rankRewardConfig.xml"
or filename == "pveRewardConfig.xml"
or filename == "achieveRewardConfig.xml" then
optimiseRewardConfig(v);
end
if filename == "awardHeroSoulConfig.xml"
or filename == "awardStarUpFoodConfig.xml" then
optimiseHeroAwardConfig(v);
end

saveLuaXMLConfig(v , desc, luaFile);
luaData = compileLua(luaFile);
break;
end
end
end
end
if luaData ~= nil then
return lzma.compress(luaData);
end
end

local keepFiles = {};

-- 编译文件
function compileFile(sourceFile, targetPath)
local pathName , baseName , ext = string.splitFilename(sourceFile);
local lowerExt = string.lower(ext);
if isIgnoreFile(pathName , baseName , ext) then
return;
end
local atts = lfs.attributes(sourceFile);
if not atts then
error("找不到文件" .. sourceFile);
return;
end

local keepFile = keepFiles[pathName];
if not keepFile then
keepFile = {};
keepFiles[pathName] = keepFile;
local f , r = io.open(pathName .. "/keep.txt" , "rb");
print("open keep" , f , r);
if f then
while true do
local fileName = f:read("*l");
print("read keep" , fileName);
if fileName then
fileName = string.trim(fileName);
keepFile[fileName] = true;
print("set keep " , fileName);
else
break;
end
end
f:close();
end
end

local saveBaseName = baseName;
if not keepFile[baseName] then
-- 处理png
if lowerExt == "png" then
-- preload要用png格式,有些机子不支持etc
if pathName ~= "preload" then
-- 是否支持PVR格式
if hasCmdArg("-pvr") then
saveBaseName = saveBaseName .. ".pvr";
end
-- 是否支持PVR格式
if hasCmdArg("-etc") then
saveBaseName = saveBaseName .. ".etc";
end
-- 是否支持PVR格式
if hasCmdArg("-atc") then
saveBaseName = saveBaseName .. ".atc";
end
end
end

-- lua文件
if (isLuaFileExt(lowerExt) or (lowerExt == "xml" and pathName == "dataconfig")) then
saveBaseName = getLuaExtName(saveBaseName)
end
else
print("file keeped : " , baseName);
saveBaseName = baseName .. ".keep";
end

local cacheFile = gCacheFiles.list[saveBaseName];
if cacheFile then
if cacheFile.origin == sourceFile and cacheFile.modifyTime == atts.modification and cacheFile.originSize == atts.size then
-- 如果是dataconfig里面的xml则需要对比下desc文件是否改变了
if lowerExt == "xml" and pathName == "dataconfig" then
if isConfigXmlDescChanged(baseName) == false then
print("配置文件没有改变,不需要重新打包", baseName)
return cacheFile
end
elseif baseName ~= "Setting.lua" then
return cacheFile;
end
end
end

print("编译文件" .. sourceFile)

local fileData;

if not keepFile[baseName] then
print("skip keeped : " , baseName);

-- 处理png
if lowerExt == "png" then
-- preload要用png格式,有些机子不支持etc
if pathName ~= "preload" then
-- 是否支持PVR格式
if hasCmdArg("-pvr") then
fileData = compilePngToPvr(sourceFile);
end
if hasCmdArg("-etc") then
fileData = compilePngToEtc(sourceFile);
end
if hasCmdArg("-atc") then
fileData = compilePngToAtc(sourceFile);
end
else
print("preload的文件不用编译png" , sourceFile);
end
-- 编译配置文件
elseif lowerExt == "xml" then
fileData = compileXml(sourceFile);
-- 编译lua文件
elseif isLuaFileExt(lowerExt) then
fileData = compileLua(sourceFile);
end
end
-- 普通文件加载
if fileData == nil then
fileData = loadfileData(sourceFile);
end

-- 计算文件信息
local fileInfo = CacheFile:new();
fileInfo.origin = sourceFile;
fileInfo.name = baseName;
fileInfo.md5 = md5.sumhexa(fileData);
fileInfo.compileSize = #fileData;
fileInfo.originSize = atts.size;
-- 保存修改时间
fileInfo.modifyTime = atts.modification;

-- 加密文件
local encryptData = FilePackage.encrypt(fileData)
fileInfo.encryptSize = string.len(encryptData);
-- 加密完毕后,计算出加密后大小
fileInfo.encryptFile = targetPath .. "/cache/" .. saveBaseName .. ".encrypt";
saveFile(encryptData , fileInfo.encryptFile);
-- 压缩文件
local compressedData = FilePackage.compress(encryptData)
fileInfo.compressedSize = string.len(compressedData);
-- 压缩完毕后,计算出压缩后大小
fileInfo.compressedFile = targetPath .."/cache/" .. saveBaseName .. ".compressed";
saveFile(compressedData , fileInfo.compressedFile);

gCacheFiles.list[saveBaseName] = fileInfo;

--print("编译文件完毕" .. sourceFile);
return fileInfo;
end


-- 保存文件列表
function saveCacheFile(filename)
local stream = NetStream.new();
gCacheFiles:write(stream);
print("保存缓存数据:" , #gCacheFiles.list)
local cacheData = NetStream.getWriteData(stream);
saveFile(cacheData , filename);
NetStream.delete(stream);
end

-- 载入文件列表
function loadCacheFile(filename)
gCacheFiles = CacheFileList:new();
local cacheData = loadFile(filename);
if cacheData then
local stream = NetStream.new(cacheData);
gCacheFiles = CacheFileList:read(stream);
print("载入缓存数据:" , #gCacheFiles.list)
NetStream.delete(stream);
end
end

-- 载入配置描述列表
function loadConfigDescCacheFile(configDescFileName)
gConfigDescCacheFiles = CacheFileList:new();
local cacheData = loadFile(configDescFileName);
if cacheData then
local stream = NetStream.new(cacheData);
gConfigDescCacheFiles = CacheFileList:read(stream);
NetStream.delete(stream);
end
end

+ 61
- 0
Editor/Editor.lua Näytä tiedosto

@@ -0,0 +1,61 @@
local Editor = class("Editor")

function Editor:activate()

end

function Editor:unactivate()

end

function Editor:play()

end

function Editor:stop()

end

function Editor:save(filename)
end

function Editor:relayoutAll()
end



-- 自动命名成不重名
function Editor:autoSetNodeName(node)
if not self.node then
return;
end
local names = {};
self.node:visitNode(function(child)
if child ~= node then
names[child:getName()] = child;
end
return true;
end);

while(names[node:getName()]) do
local name = node:getName();
local ret , matchNum = string.gsub(name , "(.*_)([0-9]+)$" , function(...)
local args = {...}
return args[1] .. tostring(tonumber(args[2]) + 1);
end);
if matchNum == 0 then
node:setName(ret .. "_1");
else
node:setName(ret);
end

end
-- 所有子节点也要做这个处理
for i , child in pairs(node:getChildren()) do
self:autoSetNodeName(child);
end
end

return Editor;

+ 738
- 0
Editor/EditorApp.lua Näytä tiedosto

@@ -0,0 +1,738 @@
-- package.path = ";preload/?.lua"
-- package.path = package.path .. "?;?.lua;preload/?.lua"
-- package.path = package.path .. ";preload/tools/?.lua"
-- package.path = package.path .. ";Editor/?.lua"
-- package.path = package.path .. ";luaScript/?.lua"
-- package.path = package.path .. ";dataconfig/?.lua"
-- package.path = package.path .. ";romFiles/?.lua"
-- package.path = package.path .. ";luaScript/cc/?.lua"
-- package.path = package.path .. ";luaScript/Tools/?.lua"
-- package.path = package.path .. ";luaScript/Tools/Nodes/?.lua"
-- package.path = package.path .. ";luaScript/Tools/Widgets/?.lua"
-- package.path = package.path .. ";luaScript/Tools/Tracks/?.lua"
-- package.path = package.path .. ";luaScript/Tools/Effect/?.lua"
-- package.path = package.path .. ";luaScript/Tools/Other/?.lua"
-- package.path = package.path .. ";luaScript/Tools/Effect/ParticleSystem/?.lua"
-- package.path = package.path .. ";luaScript/Tools/Effect/ParticleSystem/Affector/?.lua"
-- package.path = package.path .. ";luaScript/Tools/Effect/ParticleSystem/Emitter/?.lua"
-- package.path = package.path .. ";luaScript/Protocol/?.lua"
-- package.path = package.path .. ";luaScript/Config/?.lua"
-- package.path = package.path .. ";luaScript/Extension/?.lua"
-- package.path = package.path .. ";luaScript/Map/?.lua"
-- package.path = package.path .. ";luaScript/Views/?.lua"
-- package.path = package.path .. ";luaScript/Config/Languages/?.lua"
-- package.path = package.path .. ";luaScript/Config/ConfigDesc/?.lua"
-- package.path = package.path .. ";luaScript/User/?.lua"
-- package.path = package.path .. ";luaScript/Learning/?.lua"
-- package.path = package.path .. ";luaScript/Learning/Script/?.lua"
-- cc.FileUtils:getInstance():addSearchPath("core")
-- cc.FileUtils:getInstance():addSearchPath("core/preload")
-- cc.FileUtils:getInstance():addSearchPath("core/preload/tools")
-- cc.FileUtils:getInstance():addSearchPath("core/Editor")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript")
-- cc.FileUtils:getInstance():addSearchPath("core/dataconfig")
-- cc.FileUtils:getInstance():addSearchPath("core/romFiles")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/cc")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Other")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Nodes")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Widgets")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Tracks")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Effect")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Effect/ParticleSystem")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Effect/ParticleSystem/Affector")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Effect/ParticleSystem/Emitter")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Protocol")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Config")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Extension")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Map")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Views")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Config/Languages")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Config/ConfigDesc")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/User")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Plugins")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/PluginAdvertise")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Learning")
-- cc.FileUtils:getInstance():addSearchPath("core/luaScript/Learning/Script")

require("EditorGlobalFunction")
require("CCBoxNode")

require("NodeEditor")
require("ObstacleTool")
require("CombineEffectEditor")

require("CCNode")
require("CCEffectNode")
require("CCEffectFileEffectNode")
require("CCParticleEffectNode")
require("CCCombineEffect")

require("MapEditor")
require("EditorNodeZorder")
require("AnimEntityInstance")
require("UndoRedoManager")

require("MoveTool")
require("Move2DTool")
require("Move3DTool")
require("preload")

local EditorApp = class("EditorApp", cc.mvc.AppBase)

function EditorApp:ctor()
EditorApp.super.ctor(self);

-- 用来保存C#提供的回调函数
-- NodeEditor提供setPropertyObject
self.cs = {};

-- 当前的编辑器
self.editor = nil;

-- 鼠标移动工具
self.cameraController = require("Camera2DControllerTool"):new();
-- 撤销管理器
self.undoRedoManager = require("UndoRedoManager"):new();

-- 主场景
self.mainScene = nil
-- 主画布
self.mainLayer = nil
-- 主相机
self.mainCamera = nil
-- 移动工具
self.activeMoveTool = require("Move2DTool"):new();
-- 底图
self.background = nil
-- 自定义侦听渲染的listener
self.eventAfterDrawListener = nil
-- 对齐工具
self.alignTool = require("AlignTool"):new();
self.setting =
{
GridColor = cc.c4f(1,1,0,1),
AxisColor = cc.c4f(1,1,1,1),
GridSize = cc.size(100,100),
ResourceSize = cc.size(1280,720),
BackgroundColor = cc.c4b(0,0,0 , 255),
BackgroundImage = "",
ShowFPS = false,
ShowGrid = true,
ShowIPhone5 = false,
ScreenScale = 1,
ScreenScaleMax = 16,
ScreenScaleMin = 0.1,
-- 技能源模型文件
SourceModelFile = "res/default/DefaultModel/DefaultModel.gpb";
-- 技能目标模型文件
TargetModelFile = "res/default/DefaultModel/DefaultModel.gpb";
-- 显示碰撞体的调试信息
ShowCollision = false;
OriginAnchor = cc.p(0.5,0.5),
DisableAudio = false;
-- 默认是否播放UI动画
PlayUIAnimation = false;
}
self.config = {Setting = self.setting};
-- 可见区域
self.visibleRect = require("VisibleRect"):new();

self.cameraNode3D = nil;
end

function EditorApp:createObject(name)
return require(name):new();
end

-- 获取操作的相机
function EditorApp:getMainCameraShakeNode()
return self.mainCamera:getNode();
end

-- 激活一个编辑器
function EditorApp:activateEditor(editorName)
if self.editor then
self.editor:unactivate();
end
self.editor = require(editorName):new();
self.editor:activate();
-- 清空undo redo列表
self.undoRedoManager:clear();
end

function EditorApp:activate2DCamera()
self.mainCamera = cc.Director:getInstance():getActiveCamera();
self.cameraController = require("Camera2DControllerTool"):new();
self.mainLayer:setActiveCamera(nil);
self.cameraController:update();
self.cameraController:refreshSetting();
-- 切换移动工具
self.activeMoveTool:clear();
self.activeMoveTool = require("Move2DTool"):new();

cc.AudioListener:getInstance():setCamera(self.mainCamera);
end

function EditorApp:activate3DCamera()
if not self.cameraNode3D then
-- 创建透视投影相机
local camera = cc.Camera:createPerspective(45 , 1 , 1 , 1000);
cc.Director:getInstance():getActiveCamera():getNode():setScale(1.0);
local cameraNode = cc.Node3D:create("CameraNode3D");
cameraNode:addComponent(camera);
local cameraParentNode = cc.Node3D:create();
cameraParentNode:addChild(cameraNode)
self.mainLayer:addChild(cameraParentNode);
self.cameraNode3D = cameraNode;
end

self.mainLayer:setActiveCamera(self.cameraNode3D:getCamera());
self.mainCamera = self.cameraNode3D:getCamera();
self.mainCamera:setAspectRatio(cc.Director:getInstance():getWinSize().width / cc.Director:getInstance():getWinSize().height);

self.cameraController = require("Camera3DControllerTool"):new();
self.cameraController:update();
self.cameraController:refreshSetting();
-- 切换移动工具
self.activeMoveTool:clear();
self.activeMoveTool = require("Move3DTool"):new();

cc.AudioListener:getInstance():setCamera(self.mainCamera);
end

-- 获取相机
function EditorApp:getActivateCamera()
return self.mainCamera
end

-- 激活一个自定义相机
function EditorApp:activateCustomCamera(camera)
self.mainLayer:setActiveCamera(camera);
self.mainCamera = camera;


self.cameraController = require("Camera3DControllerTool"):new();
self.cameraController:update();
self.cameraController:refreshSetting();
-- 切换移动工具
self.activeMoveTool:clear();
self.activeMoveTool = require("Move3DTool"):new();


cc.AudioListener:getInstance():setCamera(self.mainCamera);
end

function EditorApp:isActiveCamera(camera)
return self.mainCamera == camera;
end

function EditorApp:is3DCamera()
if self.mainLayer:getActiveCamera() == nil or self.mainLayer:getActiveCamera() then
return false;
end
return true;
end

-- 反激活一个编辑器
function EditorApp:unactivateEditor(editorName)
if self.editor and iskindof(self.editor , editorName) then
self.editor:unactivate();
self.editor = nil;
end
-- 清空undo redo列表
self.undoRedoManager:clear();
end

function EditorApp:run()
-- 创建默认场景
self.mainScene = cc.Scene:create();
local layer = cc.Scene:create();
layer:setContentSize(self.setting.ResourceSize);
layer:setAnchorPoint(cc.p(0,0));
self.mainLayer = layer;
self.mainScene:addChild(layer);
-- 默认不使用这个2D相机
self.mainLayer:setActiveCamera(nil);
local background = cc.Layer:create();
self.background = background;
self.mainLayer:addChild(background, EditorNodeZorder.CoordinateNodeZorder);
-- 默认加载通用图
cc.SpriteFrameCache:getInstance():addSpriteFramesWithFile("res/default/default-textures.plist");
cc.SpriteFrameCache:getInstance():addSpriteFramesWithFile("res/ui/zy_tongyong/t_tongyong_1.plist");
cc.SpriteFrameCache:getInstance():addSpriteFramesWithFile("res/ui/zy_tongyong/t_tongyong_2.plist");
-- 默认使用2D相机
self:activate2DCamera();
cc.StreamObject:addIgnoreDir("core");
cc.StreamObject:addIgnoreDir("huanle");
cc.StreamObject:addIgnoreDir("chuannan");
cc.StreamObject:addIgnoreDir("youxianmj");
cc.StreamObject:addIgnoreDir("chongqing");
cc.StreamObject:addIgnoreDir("shuzhou");

cc.Director:getInstance():runWithScene(self.mainScene)
self:refreshSetting();
end

function EditorApp:getOriginOffset()
return cc.p(cc.Director:getInstance():getWinSize().width * self.setting.OriginAnchor.x , cc.Director:getInstance():getWinSize().height * self.setting.OriginAnchor.y);
end

-- 改变编辑器大小
function EditorApp:resize(w , h)
self.mainCamera:setAspectRatio(w/h);

cc.Application:getInstance():applicationScreenSizeChanged(w, h);
cc.Director:getInstance():getOpenGLView():setDesignResolutionSize(w , h , cc.ResolutionPolicy.EXACT_FIT);
self.mainScene:setScale(self.setting.ScreenScale);
-- 通知可见区域更新
self.visibleRect:updateVisibleRect();

--self.mainScene:setContentSize(cc.Director:getInstance():getWinSize());
self.background:setContentSize(cc.Director:getInstance():getWinSize());
--self.mainLayer:setContentSize(cc.Director:getInstance():getWinSize());
self:refreshSetting();
end

-- 创建网格
function EditorApp:refreshSetting()
-- 设置全局缩放
local pDirector = cc.Director:getInstance();
local pEGLView = cc.Director:getInstance():getOpenGLView();
cc.Director:getInstance():getOpenGLView():setDesignResolutionSize(pEGLView:getFrameSize().width , pEGLView:getFrameSize().height , cc.ResolutionPolicy.EXACT_FIT);
--self.mainScene:setScale(self.setting.ScreenScale);
-- 居中
--self.mainLayer:setPosition(self:getOriginOffset());


-- 更新相机控制器
self.cameraController:refreshSetting();

local pDirector = cc.Director:getInstance();
pDirector:setDisplayStats(self.setting.ShowFPS);
-- 是否需要显示碰撞体
if self.setting.ShowCollision == true and self.eventAfterDrawListener == nil then
self.eventAfterDrawListener = cc.EventListenerCustom:create("director_after_draw" , handler(self , self.onUpdate));
cc.Director:getInstance():getEventDispatcher():addEventListenerWithFixedPriority(self.eventAfterDrawListener, 1);
elseif self.setting.ShowCollision == false and self.eventAfterDrawListener ~= nil then
cc.Director:getInstance():getEventDispatcher():removeEventListener(self.eventAfterDrawListener)
self.eventAfterDrawListener = nil
end



local winSize = self.setting.ResourceSize;
local resourceSize = {width = 1280 ; height = 720};
-- 实际比率
local radio = winSize.width / winSize.height;
-- 标准比率
local resourceRadio = resourceSize.width / resourceSize.height;

print("实际分辨率" , winSize.width , winSize.height);

local finalResourceSize;
-- 比16:9还扁,就用标准高度,让宽度变宽
if radio > resourceRadio then
finalResourceSize = {width = resourceSize.height * radio ; height = resourceSize.height};
-- 比16:9高,就固定宽度,让高度变高
else
finalResourceSize = {width = resourceSize.width ; height = resourceSize.width / radio};
end
print("资源分辨率" , finalResourceSize.width , finalResourceSize.height);


-- 改变屏幕大小
self.mainLayer:setContentSize(finalResourceSize);
-- 更新UI尺寸
if self.editor and self.editor.node and self.editor.node.updateSizeAndPosition then
self.editor.node:updateSizeAndPosition();
end
end

function EditorApp:onUpdate()
cc.PhysicsController:getInstance():drawDebug(self.mainCamera:getViewProjectionMatrix())
end

function EditorApp:reload()
if self.effect then
local xmlNode = self.effect:createXmlNode();
self.effect:removeFromParent();
cc.TextureCache:sharedTextureCache():removeUnusedTextures();
self.effect = createEffectFromXmlNode(xmlNode);
self:initEffect(self.effect)
return self.effect;
elseif self.combineEffect then
cc.TextureCache:sharedTextureCache():removeUnusedTextures();
return self.combineEffect;
end
end



-- 生成一个目录
local function visitPath(sourcePath , func , ...)
print("开始生成目录" .. sourcePath)
-- 递归遍历sourcePath的所有目录
for file in lfs.dir(sourcePath) do
if file ~= "." and file ~= ".." then
local f = sourcePath..'/'..file
local attr = lfs.attributes (f , "mode")
if attr == "directory" then
if visitPath(f , func , ...) then
return true;
end
else
if func(f , ...) then
return true;
end
end
end
end
print("生成目录完毕" .. sourcePath)
end

-- 重新保存所有UI
function EditorApp:resaveAllUI()

local function saveui(fileName)
-- 返回pathName , baseName , ext
local pathName , baseName , ext = string.splitFilename(fileName);
print(pathName , baseName , ext);
if ext ~= "ui" then
return false;
end

local function resaveUI()
print("\n\n");
print("正在加载UI:" , fileName);
local node = createNodeFromFile(fileName);
print("正在重新计算PList");
node:recalcAllPList();
print("正在保存UI:" , fileName);
node:saveToFile(fileName);
end

xpcall(resaveUI , function(msg)print("处理界面“" .. fileName .. "”时出错了:" , msg , debug.traceback());alert("处理界面“" .. fileName .. "”时出错了");end);

end
cc.BaseObject:setUpgradingMode(true);
visitPath("res" , saveui);
cc.BaseObject:setUpgradingMode(false);
end



-- 重新保存所有Model
function EditorApp:resaveAllModel()

local function saveui(fileName)
-- 返回pathName , baseName , ext
local pathName , baseName , ext = string.splitFilename(fileName);
print(pathName , baseName , ext);
if ext ~= "gpb" then
return false;
end

local function resaveUI()
print("\n\n");
print("正在加载Model:" , fileName);
local node = cc.ModelNode:create(fileName);
local function onLoad(index)
local skinMesh = node:_getFirstMeshSkin();
if skinMesh then
print("蒙皮骨头数量:" , skinMesh:getJointCount());
if skinMesh:getJointCount() >= 39 then
print("蒙皮骨头数量超过了39个:" , skinMesh:getJointCount());
end
end
node:autorelease();
end
node:runOnLoad(onLoad);
node:retain();
print("正在保存Model:" , fileName);
--node:saveToFile(fileName);
end

xpcall(resaveUI , function()print("处理Effect“" .. fileName .. "”时出错了");alert("处理Effect“" .. fileName .. "”时出错了");end);

end
cc.BaseObject:setUpgradingMode(true);
visitPath("res" , saveui);
cc.BaseObject:setUpgradingMode(false);
end

-- 重新保存所有Effect
function EditorApp:resaveAllEffect()

local function saveui(fileName)
-- 返回pathName , baseName , ext
local pathName , baseName , ext = string.splitFilename(fileName);
print(pathName , baseName , ext);
if ext ~= "effect" then
return false;
end

local function resaveUI()
print("\n\n");
print("正在加载Effect:" , fileName);
local node = createNodeFromFile(fileName);
print("正在保存Effect:" , fileName);
node:saveToFile(fileName);
end

xpcall(resaveUI , function()print("处理Effect“" .. fileName .. "”时出错了");alert("处理Effect“" .. fileName .. "”时出错了");end);

end
cc.BaseObject:setUpgradingMode(true);
visitPath("res" , saveui);
cc.BaseObject:setUpgradingMode(false);
end

-- 重新保存所有CE
function EditorApp:resaveAllCE()

local function saveCE(fileName)
-- 返回pathName , baseName , ext
local pathName , baseName , ext = string.splitFilename(fileName);
print(pathName , baseName , ext);
if ext ~= "ce" then
return false;
end

local function resaveCE()
print("\n\n");
print("正在加载CE:" , fileName);
local node = createCombineEffectFromXmlFile(fileName);
print("正在保存CE:" , fileName);
node:saveToFile(fileName);
end

xpcall(resaveCE , function()print("处理CE“" .. fileName .. "”时出错了");alert("处理CE“" .. fileName .. "”时出错了");end);

end
cc.BaseObject:setUpgradingMode(true);
visitPath("res" , saveCE);
cc.BaseObject:setUpgradingMode(false);
end


-- 重新保存所有Scene
function EditorApp:resaveAllScene()
-- 载入场景文件
local function loadScene(nodeFile)
print("加载场景" , nodeFile);
TimeSpan:enterSpan("loadScene" .. nodeFile);

TimeSpan:enterSpan("createNodeFromFile");
print("加载模型");
LoadingScene = true;
local node = createNodeFromFile(nodeFile);
LoadingScene = false;
node:setCollectAnimationClip(false);
TimeSpan:leaveSpan();
if not EditorMode then
-- 普通模式,屏蔽掉HD内容
local hd = node:findNode("HD");
if hd then
local function onQualityChanged(key , value)
-- 高质量
hd:setVisible(value == 1);
end
hd:bind(app.systemSetting.info , "graphicQuality" , onQualityChanged);
end
end

-- 创建一个题图载入资源
TimeSpan:enterSpan("requireMap");
print("加载障碍块");
local map = require("Map"):new();
local arr = string.split(nodeFile, ".");
map:loadLua(arr[1] .. ".lmap");
TimeSpan:leaveSpan();

TimeSpan:leaveSpan();
return node , map;
end


local function saveui(fileName)
-- 返回pathName , baseName , ext
local pathName , baseName , ext = string.splitFilename(fileName);
print(pathName , baseName , ext);
if ext ~= "scene" then
return false;
end

local function resaveUI()
print("\n\n");
print("正在加载Scene:" , fileName);
local scene , map = loadScene(fileName);
print("正在保存Scene:" , fileName);
scene:saveToFile(fileName);

local arr = string.split(fileName, ".");

map:saveLua(arr[1] .. ".lmap");
map:saveXml(arr[1] .. ".map");

end

xpcall(resaveUI , function(msg)print("处理Scene“" .. fileName .. "”时出错了:" , msg);alert("处理Scene“" .. fileName .. "”时出错了:" .. tostring(msg));end);

end
cc.BaseObject:setUpgradingMode(true);
visitPath("res" , saveui);
cc.BaseObject:setUpgradingMode(false);
end

-- 解析所有的配置,导出所有使用过的资源
function EditorApp:exportAllRes(destPath)
local fileVisitor = cc.ReferanceResourceVisitor:new()
local function exportRes(resFile)
print("资源名字", resFile)
if string.endsWith(resFile, ".gpb") then
local model = cc.ModelNode:create(resFile);
model:visitReferanceResource(fileVisitor)
elseif string.endsWith(resFile, ".scene") then
local object = cc.StreamObject:loadFromFile(resFile)
if object then
object:visitReferanceResource(fileVisitor)
-- 保存地图相关的资源
fileVisitor:visitFile(resFile)
local stringArr = string.split(resFile, ".");
fileVisitor:visitFile(stringArr[1] .. ".lmap")
fileVisitor:visitFile(stringArr[1] .. ".lmap.blocks")
fileVisitor:visitFile(stringArr[1] .. ".map")
end
elseif string.endsWith(resFile, ".ui")
or string.endsWith(resFile, ".ce")
or string.endsWith(resFile, ".effect") then
-- 导出资源本身
local object = cc.StreamObject:loadFromFile(resFile)
if object then
fileVisitor:visitFile(resFile)
object:visitReferanceResource(fileVisitor)
end
elseif string.endsWith(resFile, ".ogg")
or string.endsWith(resFile, ".png")
or string.endsWith(resFile, ".jpg") then
fileVisitor:visitFile(resFile)
elseif string.endsWith(resFile, ".plist") then
local stringArr = string.split(resFile, ".");
fileVisitor:visitFile(resFile)
fileVisitor:visitFile(stringArr[1] .. ".png")
end
end
local function visitOneData(cf)
if table.nums(cf) <= 0 then
return
end
for i, v in pairs(cf) do
if type(v) == "string" and v ~= "" then
local strs = string.split(v, ";")
for ii, vv in pairs(strs) do
exportRes(vv)
end
end
end
end
local function parseXmlFile(fileName)
print("解析xml文件", fileName)
-- 读取整个文件数据
local file = io.open(fileName , "rb");
local fileData = file:read("*a");
file:close();
-- 解析数据
local function onElementStart(name, atts)
visitOneData(atts)
end
-- 这里不能使用xml.eval来解析,android下面,如果下载的文件不是xml格式的,则会宕机
local result , err = tiny.eval(fileData, onElementStart)
if not result then
print("xml文件解析失败", fileName)
return;
end
end
local function parseLuaFile(fileName)
print("处理lua文件", fileName)
local file = io.open(fileName , "rb");
local fileData = file:read("*a");
file:close();
local uiFile = nil
-- 导出UI
for w in string.gmatch(fileData, '"([%w_/]+)%.ui"') do
uiFile = w .. ".ui"
exportRes(uiFile)
end
-- 导出技能
for w in string.gmatch(fileData, '"([%w_/]+)%.ce"') do
uiFile = w .. ".ce"
exportRes(uiFile)
end
-- 导出光效
for w in string.gmatch(fileData, '"([%w_/]+)%.effect"') do
uiFile = w .. ".effect"
exportRes(uiFile)
end
-- 导出模型
for w in string.gmatch(fileData, '"([%w_/]+)%.gpb"') do
uiFile = w .. ".gpb"
exportRes(uiFile)
end
-- 导出plist
for w in string.gmatch(fileData, '"([%w_/]+)%.plist"') do
uiFile = w .. ".plist"
exportRes(uiFile)
end
-- 导出png
for w in string.gmatch(fileData, '"([%w_/]+)%.png"') do
uiFile = w .. ".png"
exportRes(uiFile)
end
-- 导出jpg
for w in string.gmatch(fileData, '"([%w_/]+)%.jpg"') do
uiFile = w .. ".jpg"
exportRes(uiFile)
end
-- 导出声音
for w in string.gmatch(fileData, '"([%w_/]+)%.ogg"') do
uiFile = w .. ".ogg"
exportRes(uiFile)
end
-- 字体
for w in string.gmatch(fileData, '"([%w_/]+)%.fnt"') do
uiFile = w .. ".fnt"
exportRes(uiFile)
end
end
-- 遍历dataconfig目录的所有文件
visitPath("dataconfig", parseXmlFile);
visitPath("luaScript", parseLuaFile);
visitPath("preload", parseLuaFile);
--exportRes("res/animation/XJL_1/XJL_1.effect")
fileVisitor:saveAllRes(destPath)
print("导出资源路径", destPath)
alert("资源导出完毕")
end

return EditorApp;

+ 20
- 0
Editor/EditorConfig.lua Näytä tiedosto

@@ -0,0 +1,20 @@
require("XMLConfigReader")


Config = {}
-- 一般设置
Config.Setting = require("Setting")
-- 客户端效果配置
Config.ClientEffect = loadXMLConfig(require("ClientEffectConfigDesc"))
-- 编辑器模式
Config.IsEditor = true;

runXMLPostload();
-- 所有语言存在这里
local Languages = require("languages");
local Language = Languages[Config.Setting.Language] or Languages[kLanguageChinese];
-- 根据传入的文字字符串,自动翻译成玩家机器所设定的语言
function RT(str)
return Language[str];
end


+ 27
- 0
Editor/EditorGlobalFunction.lua Näytä tiedosto

@@ -0,0 +1,27 @@
-- 编辑器里面的全局函数
-- 判断一个节点的付节点是否在一个列表里面
-- table的格式是
--{
-- xxx : node,
--}
function ParentNodeIsInTable(node, nodeTable)
if node:getParent() == nil then
return false;
end
if table.find(nodeTable, node:getParent()) then
return true;
end
local parentNode = node:getParent();
return ParentNodeIsInTable(parentNode, nodeTable);
end

function createLuaTable()
local tab = {};
return tab;
end

function addValueToTable(tab, value)
table.insert(tab, value)
end

+ 8
- 0
Editor/EditorNodeZorder.lua Näytä tiedosto

@@ -0,0 +1,8 @@
EditorNodeZorder =
{
-- 坐标系Node
CoordinateNodeZorder = -100,
-- 地图网格Node
MapGridNodeZorder = -90
}

+ 124
- 0
Editor/EffectEditor.lua Näytä tiedosto

@@ -0,0 +1,124 @@
local EffectEditor = class("EffectEditor" , require("NodeEditor"));

function EffectEditor:ctor()
EffectEditor.super.ctor(self);
end

function EffectEditor:activate()
EffectEditor.super.activate(self);
app.setting.OriginAnchor = cc.p(0.5,0.5);
app:refreshSetting();
-- 创建一个文本框,用于显示光效是否为无限长
local debugLabel = cc.Text:createNode();
debugLabel:setDefaults();
local config = debugLabel:getFontConfig();
config.fontSize = 40;
config.texColor = cc.c4b(255,0,0,255);
debugLabel:setFontConfig(config);

-- 获取可见视野的像素大小
local screenSize = cc.Director:getInstance():getWinSizeInPixels();
debugLabel:setTranslation(screenSize.width / 2 , 100 , 0)
debugLabel:setText("这个光效是无限长的,请注意!!!!");
self.debugText = debugLabel;
self.InfinityTipTextNode = cc.Scene:create()
self.InfinityTipTextNode:setActiveCamera(cc.Director:getInstance():getFixedCamera())
self.InfinityTipTextNode:addChild(self.debugText)
app.mainScene:addChild(self.InfinityTipTextNode);
self.InfinityTipTextNode:setVisible(false)
end

function EffectEditor:unactivate()
-- 移除提示框
self.InfinityTipTextNode:removeFromParent()
EffectEditor.super.unactivate(self);
end

function EffectEditor:play()
-- supper class
EffectEditor.super.play(self);
self:checkInfinity();
end

-- 检测光效是否为无限长的
function EffectEditor:checkInfinity()
-- 如果是光效并且是无限长需要给出提示
if self.node and self.node.ClassName == "EffectNode" and self.node:isInfinite() then
self.InfinityTipTextNode:setVisible(true)
else
self.InfinityTipTextNode:setVisible(false)
end
end

-- 创建新的光效
function EffectEditor:newNode()
self:closeNode();
local node = self:createNode("EffectNode");
self:initNode(node)
return node;
end

-- 关闭光效
function EffectEditor:closeNode()
EffectEditor.super.closeNode(self);
end

function EffectEditor:createNode(nodeType)
local node = EffectEditor.super.createNode(self , nodeType);
-- 默认播放一下
node:play();
return node;
end

-- 从文件载入节
-- 初始化光效,添加到场景中
function EffectEditor:initNode(node)
EffectEditor.super.initNode(self , node)
end

-- 从文件载入节点
function EffectEditor:loadNode(nodeFile)
local effectNode = EffectEditor.super.loadNode(self , nodeFile);
effectNode:play();
self:checkInfinity();
return effectNode;
end


function EffectEditor:loadModelNode(filename)
self:closeNode();
self.node = cc.ModelNode:createNode();
self.node:setName("ModelNode")
self.node:setMeshFile(filename);
self:initNode(self.node);
return self.node;
end

-- 创建新的光效
function EffectEditor:newModelNode()
self:closeNode();
local node = self:createNode("ModelNode");
self:initNode(node)
return node;
end

function EffectEditor:loadSoundNode(filename)
self:closeNode();
self.node = cc.SoundSourceNode:createNode();
self.node.SoundSource:setAudioFile(filename);
self:initNode(self.node);
return self.node;
end

-- 创建新的光效
function EffectEditor:newSoundNode()
self:closeNode();
local node = self:createNode("SoundSourceNode");
self:initNode(node)
return node;
end

return EffectEditor;

+ 22
- 0
Editor/GenerateAnimationClips.lua Näytä tiedosto

@@ -0,0 +1,22 @@
require("Editor.CompileFile")


local function processAnimation(fileName)
local animationClip = cc.AnimationClipFileCache:getInstance():load(fileName);
print("载入AnimationClip:" , fileName);
end

-- 生成所有语言
function generateAnimationClips(textureFile)

local function saveui(fileName)
-- 返回pathName , baseName , ext
local pathName , baseName , ext = string.splitFilename(fileName);
print(pathName , baseName , ext);
if string.lower(ext) == "animation" then
processAnimation(fileName);
end
end
visitPath("res" , saveui);
cc.AnimationClipFileCache:getInstance():saveToFile(textureFile);
end

+ 121
- 0
Editor/GenerateDict.lua Näytä tiedosto

@@ -0,0 +1,121 @@
require("Editor.CompileFile")


-- 收集languageCN.lua里的语言
local function collectLanguages(transDict)
local Languages = require("languageCN");
for i , v in pairs(Languages) do
print("收集Lang文本" , v);
local trans = XmlTranslator:collect(v);
transDict[trans] = "";
end
end

-- 收集一个语言片
local function collectConfig(transDict , record , fieldName , translator)
local trans = translator:collect(record[fieldName]);
if type(trans) ~= "string" then
error("trans不是字符串" .. type(trans) .. tostring(trans));
end
transDict[trans] = "";
end

-- 收集一个配置
local function collectLanguageConfig(transDict , config)
local desc = config:getConfigDesc();
print("正在收集配置的语言:" , desc.XMLFile);
if desc.Translation then
for i , v in pairs(desc.Translation) do
print("正在收集字段:" , i);
for ii , vv in pairs(config) do
if desc.SecondKeyName then
for iii , vvv in pairs(vv) do
collectConfig(transDict , vvv , i , v);
end
else
collectConfig(transDict , vv , i , v);
end
end
end
end
end

-- 保存到文件
local function saveXmlFile(transDict , dictFile)
local f = io.open(dictFile , "wb");
for i , v in pairsByKeys(transDict)do
f:write(i);
f:write("\n");
end
f:close();
end

-- 收集一个ui
local function collectSingleUI(transDict , ui)
if ui.collectText then
local result = ui:collectText();
for i , v in ipairs(result) do
print("收集到UI语言:" , v);
transDict[v] = "";
end
end
end
-- 收集一个ui
local function collectUI(transDict , ui)
collectSingleUI(transDict , ui);
-- 递归所有子
for i , v in pairs(ui:getChildren()) do
collectUI(transDict , v);
end
end

-- 收集所有UI的语言
local function collectUILanguage(transDict)
local function saveui(fileName)
-- 返回pathName , baseName , ext
local pathName , baseName , ext = string.splitFilename(fileName);
print(pathName , baseName , ext);
if ext ~= "ui" then
return false;
end

print("\n\n");
print("正在加载UI:" , fileName);
local ui = cc.StreamObject:loadFromFile(fileName);
collectUI(transDict , ui);
end
visitPath("res/ui" , saveui);
end

-- 生成所有语言
function generateDict(dictFile)

-- initialize director
local director = cc.Director:getInstance();
local glview = director:getOpenGLView();
if not glview then
glview = cc.GLView:createWithRect("applyDict", {x=0,y=0,width=100,height=100});
director:setOpenGLView(glview);
end
-- 加载xml
loadAllXML()

local transDict = {};

-- 生成所有配置的语言
for i , v in pairs(app.config) do
if i ~= "Setting" and i ~= "RomSetting" then
local desc = v:getConfigDesc();
local filename = desc.XMLFile;
collectLanguageConfig(transDict , v);
end
end

-- 收集languageCN.lua里的语言
collectLanguages(transDict);

collectUILanguage(transDict);
saveXmlFile(transDict , dictFile);

end

+ 22
- 0
Editor/GenerateMaterials.lua Näytä tiedosto

@@ -0,0 +1,22 @@
require("Editor.CompileFile")


local function processAnimation(fileName)
local Material = cc.MaterialFileCache:getInstance():load(fileName);
print("载入Material:" , fileName);
end

-- 生成所有语言
function generateMaterials(textureFile)

local function saveui(fileName)
-- 返回pathName , baseName , ext
local pathName , baseName , ext = string.splitFilename(fileName);
print(pathName , baseName , ext);
if string.lower(ext) == "animation" then
processAnimation(fileName);
end
end
visitPath("res" , saveui);
cc.MaterialFileCache:getInstance():saveToFile(textureFile);
end

+ 31
- 0
Editor/GenerateTextureSize.lua Näytä tiedosto

@@ -0,0 +1,31 @@
require("Editor.CompileFile")


local function processPng(fileName)
local image = cc.Image:analysisPngFile(fileName);
print("png图片大小:" , fileName , image.image_width , image.image_height);
cc.Director:getInstance():getTextureCache():addTextureSize(fileName , cc.size(image.image_width , image.image_height));
end

local function processJpg(fileName)
local image = cc.Image:analysisJpgFile(fileName);
print("jpg图片大小:" , fileName , image.image_width , image.image_height);
cc.Director:getInstance():getTextureCache():addTextureSize(fileName , cc.size(image.image_width , image.image_height));
end

-- 生成所有语言
function generateTextureSize(textureFile)

local function saveui(fileName)
-- 返回pathName , baseName , ext
local pathName , baseName , ext = string.splitFilename(fileName);
print(pathName , baseName , ext);
if string.lower(ext) == "png" then
processPng(fileName);
elseif string.lower(ext) == "jpg" then
processJpg(fileName);
end
end
visitPath("res" , saveui);
cc.Director:getInstance():getTextureCache():saveTextureSize(textureFile);
end

+ 274
- 0
Editor/GenerateVersion.lua Näytä tiedosto

@@ -0,0 +1,274 @@

require("preload.tools.socket")
require("preload.tools.url")
url = require("socket.url")
require("preload.tools.headers")
require("preload.tools.http")
http = require("socket.http")

require("luaScript.all")
require("luaScript.Tools.LuaXml")
require("luaScript.Tools.GlobalFunction")
require("luaScript.Protocol.Protocol");
require("luaScript.Protocol.ProtoDef");
require("luaScript.Protocol.ModuleName");
require("Editor.GenerateDict");
require("Editor.GenerateTextureSize");
require("Editor.GenerateAnimationClips");
require("Editor.GenerateMaterials");
require("Editor.ApplyDict");
require("Editor.CompileFile")
require("Editor.LinkFile")
require("Editor.CompareVersion")

local bit32 = (bit32 or require("bit"))
local lfs = lfs or require("lfs")

-- avoid memory leak
collectgarbage("setpause", 100)
collectgarbage("setstepmul", 5000)

-- 调试信息
function __G__TRACKBACK__(msg)
print("----------------------------------------")
print("LUA ERROR: " .. tostring(msg) .. "\n")
print(debug.traceback())
print("----------------------------------------")
end

FilePackage = {};
function FilePackage.encrypt(data)
return cc.FilePackage:getInstance():encrypt(data);
end

function FilePackage.compress(data)
return lzma.compress(data);
end

function FilePackage.uncompress(data)
return lzma.uncompress(data);
end

-- 是否有命令行参数被指定
function hasCmdArg(name)
for i , v in pairs(CommandArguments) do
if v == name then
return true;
end
end
return false;
end

-- 深度创建目录
function createDir(targetPath)
local path = string.gsub(targetPath , "\\" , "/")
local paths = string.split(path , "/");
local currentPath = "";
for i , v in ipairs(paths) do
if i == 1 then
currentPath = v;
else
currentPath = currentPath .. "/" .. v;
end
if lfs.attributes(currentPath , "mode") ~= "directory" then
lfs.mkdir(currentPath);
end
end
end

-- 加密文件
function encryptFile(fileData , targetFile)
targetFile:write(FilePackage.encrypt(fileData));
end

function saveFile(str , targetFile)
local file = io.open(targetFile , "wb");
file:write(str);
file:close();
end

function loadFile(filename)
-- 读取整个文件数据
local file = io.open(filename , "rb");
if not file then
return;
end
fileData = file:read("*a");
file:close();
return fileData;
end

-- 遍历一个目录,对目录中的每个文件执行 func 回调
function visitPath(sourcePath , func , ...)
print("开始生成目录" .. sourcePath)
-- 递归遍历sourcePath的所有目录
--local sourcePath = "d:\\WorkSpace\\DingDing\\Core\\debug\\src\\logs"
for file in lfs.dir(sourcePath) do
if file ~= "." and file ~= ".." and file ~= ".svn" then
local f = sourcePath..'/'..file
local attr = lfs.attributes (f , "mode")
if attr == "directory" then
if visitPath(f , func , ...) then
return true;
end
else
if func(f , ...) then
return true;
end
end
end
end
print("生成目录完毕" .. sourcePath)
end

-- 执行一个系统命令
local function runCmd(cmd)
local out = io.popen(cmd , "r");
print(out:read("*a"));
local exit_code = out:close();
return exit_code
end

local index = 0;
local stackMap = {}
local function decodeLog(fileName)
index = index + 1
-- 返回pathName , baseName , ext
local basePath , baseName , ext = string.splitFilename(fileName);
print(index, basePath, baseName, ext);
if ext ~= "7z" then
return false;
end
-- 3_1033_7004668_97d3fd7fcf8a2c046905f4c0c85d1655_20180106003900_7A97365E.7z
--[[
names =
{
[1] = "平台",
[2] = "资源版本",
[3] = "玩家ID",
[4] = "堆栈MD5",
[5] = "日期",
[6] = "随机数",
}
fileName = "logs/堆栈/日期_版本_平台_玩家ID_随机数.log"
]]--
local names = string.split(baseName , "_");
local platform = names[1]
local version = names[2]
local user_id = names[3]
local stack = names[4]
local log_date = names[5]
local randnum = names[6]
local logFilePath = "logs" .. "/" .. stack .. "/";
local logFileName = log_date .. "_" .. version .. "_" .. platform .. "_" .. user_id .. "_" .. randnum .. ".log";
if not stackMap[stack] then
stackMap[stack] = {}
end
table.insert(stackMap[stack], logFileName)
pathName = basePath .. "/" .. logFilePath;
if #names == 6 then
createDir(pathName);
local newFileName = pathName .. logFileName;
local logFile = io.open(fileName , "rb");
local allData = logFile:read("*a");
logFile:close();

local uncompressData = lzma.uncompress(allData);
if uncompressData ~= nil then
local newLogFile = io.open(newFileName , "wb");
newLogFile:write(lzma.decodeLog(uncompressData));
newLogFile:close();
end
-- 删除原始文件
os.remove(fileName)
end
end

local function decodeLogs()
visitPath("logs" , decodeLog);
end

local function decodeCrash(fileName)
-- 返回pathName , baseName , ext
local pathName , baseName , ext = string.splitFilename(fileName);
print("pathName, baseName, ext:", pathName , baseName , ext);
if ext ~= "7z" then
return false;
end
local names = string.split(baseName , "_");
local newFileName, baseFileName, logFlag
-- 如果是android则需要分平台创建
if tonumber(names[2]) == 3 or tonumber(names[2]) == 4 or tonumber(names[2]) == 5 then
pathName = pathName .. "/" .. names[2] .. "/" .. names[3] .. "/" .. names[4] .. "/";
baseFileName = names[5]
logFlag = names[6]
else
-- 其他平台
pathName = pathName .. "/" .. names[2] .. "/" .. names[3] .. "/";
baseFileName = names[4]
logFlag = names[5]
end
local dumpPathName = pathName .. "dump/"
local logPathName = pathName .. "log/"
-- 创建dump目录
createDir(dumpPathName)
-- 创建对应的log目录
createDir(logPathName)
-- 再拆分一次
local secNames = string.split(baseFileName, ".");
if logFlag then
-- 解析log
newFileName = logPathName .. secNames[1] .. ".log";
local logFile = io.open(fileName , "rb");
local allData = logFile:read("*a");
logFile:close();

local uncompressData = lzma.uncompress(allData);
if uncompressData ~= nil then
local newLogFile = io.open(newFileName , "wb");
newLogFile:write(lzma.decodeLog(uncompressData));
newLogFile:close();
end
else
-- 解析dump
newFileName = dumpPathName .. secNames[1] .. ".dmp";
local logFile = io.open(fileName , "rb");
local allData = logFile:read("*a");
logFile:close();

local uncompressData = lzma.uncompress(allData);
if uncompressData ~= nil then
local newLogFile = io.open(newFileName , "wb");
newLogFile:write(uncompressData);
newLogFile:close();
end
end
end

local function decodeCrashs()
visitPath("crash" , decodeCrash);
end

function main()
print("CommandArguments" , CommandArguments);
if hasCmdArg("-BuildLogs") then
print("请把log文件拷贝到logs目录")
decodeLogs();
elseif hasCmdArg("-BuildCrash") then
print("请把crash文件拷贝到crash目录")
decodeCrashs();
end
end

local result = nil
local function main_exe()
result = main()
end
xpcall(main_exe, __G__TRACKBACK__)

return result

+ 46
- 0
Editor/LinkFile.lua Näytä tiedosto

@@ -0,0 +1,46 @@

-- 保存已经生成过的文件,
-- 如果当前要生成的文件在列表里面已经存在了,
-- 则表示文件重名
g_files = {};

-- 生成一个文件
function linkFile(sourceFile , targetPath, targetFile , versionInfo)
print("linkFile" , sourceFile);
local pathName , baseName , ext = string.splitFilename(sourceFile);
if isIgnoreFile(pathName , baseName , ext) then
return;
end
--print("链接文件" .. sourceFile)
local fileInfo = g_files[baseName];
if fileInfo then
error("文件重名:[" .. sourceFile .. "] 与 [" .. fileInfo.origin .. "]");
end
fileInfo = xml.new("file");
versionInfo.files[baseName] = fileInfo;
-- 保存全局文件列表
g_files[baseName] = fileInfo;

local cacheFile = compileFile(sourceFile, targetPath);
fileInfo.origin = cacheFile.origin;
fileInfo.name = cacheFile.name;
fileInfo.md5 = cacheFile.md5;
fileInfo.size = cacheFile.compileSize;
fileInfo.preload = false -- 是否新手期文件
if not hasCmdArg("-onlyServer") then
-- 保存加密文件到客户端
local assetFileName = targetPath .. "/assets/" .. fileInfo.md5
local targetClientFile = io.open(assetFileName, "wb");
targetClientFile:write(loadFile(cacheFile.encryptFile));
targetClientFile:close();
end
-- 保存加密并压缩后的文件到服务端
fileInfo.offset = targetFile:seek();
local compressedData = loadFile(cacheFile.compressedFile);
targetFile:write(compressedData);
fileInfo.compressedSize = string.len(compressedData)
end

+ 23
- 0
Editor/MapEditor.lua Näytä tiedosto

@@ -0,0 +1,23 @@
local MapEditor = class("MapEditor")

function MapEditor:ctor()
end

function MapEditor:init()
-- 创建障碍块和地图可见范围
self.ObstacleNode = app.editor.Map:createObstacleNode();
app.mainLayer:addChild(self.ObstacleNode);
-- 创建菱形网格
self.GridNode = app.editor.Map:createGridNode();
app.mainLayer:addChild(self.GridNode);
end

-- 关闭光效
function MapEditor:close()
-- 移除glNode
self.GridNode:removeFromParent();
-- 移除障碍块
self.ObstacleNode:removeFromParent();
end

return MapEditor;

+ 139
- 0
Editor/Move2DTool.lua Näytä tiedosto

@@ -0,0 +1,139 @@

MoveLockedMode =
{
no = 0;
x = 1;
y = 2;
}

-- 2D平移工具功能
local Move2DTool = class("Move2DTool", require("MoveTool"))
function Move2DTool:ctor()

-- 当前锁定模式
self.lockedMode = MoveLockedMode.no;

self.super.ctor(self);
end

function Move2DTool:clear()
self.super.clear(self);
end

function Move2DTool:MouseDown(button , x , y)
self.super.MouseDown(self, button, x, y)
end

local function roundVec3(vec)
vec.x = math.floor(vec.x + 0.5)
vec.y = math.floor(vec.y + 0.5)
vec.z = math.floor(vec.z + 0.5)
return vec;
end


-- 根据Shift键决定锁定哪个轴,并返回移动目标
function Move2DTool:getMoveEndPos(screenX , screenY)
-- 转换坐标,将屏幕坐标转换成GLView的坐标
local startPos = app.visibleRect:convertScreenToGLView(self.startPos.x , self.startPos.y);
local endPos = app.visibleRect:convertScreenToGLView(screenX , screenY);

local key = app.cs.getModifierKeys();
-- Shift锁定横竖移动
if key == Keys.Shift then
if self.lockedMode == MoveLockedMode.no then
-- x 方向移动的距离更远
if math.abs(endPos.x - startPos.x) > math.abs(endPos.y - startPos.y) then
self.lockedMode = MoveLockedMode.x;
else
self.lockedMode = MoveLockedMode.y;
end
end
-- x 方向移动的距离更远
if self.lockedMode == MoveLockedMode.x then
endPos.y = startPos.y;
else
endPos.x = startPos.x;
end
else
self.lockedMode = MoveLockedMode.no;
end
return {startPos = startPos , endPos =endPos};
end

function Move2DTool:moveTo(screenX, screenY)
-- 转换坐标,将屏幕坐标转换成GLView的坐标
local startEndPos = self:getMoveEndPos(screenX , screenY);
local startPos = startEndPos.startPos;
local endPos = startEndPos.endPos;

-- 通过命令来移动
local scale = app.setting.ScreenScale;
local scale = app.setting.ScreenScale;
local offset = cc.pSub(endPos , startPos)
-- 增量
local targetOffset = cc.vec3(offset.x / scale, offset.y / scale, 0);
for i , v in pairs(self.originPoies) do
local originWorld = i:getParent():convertToWorldSpace(v.pos);
local newWorld = cc.vec3Add(originWorld , targetOffset);
local newLocal = roundVec3(i:getParent():convertToNodeSpace(newWorld));
i:setTranslation(newLocal);
end
end

function Move2DTool:commandMoveTo(screenX, screenY)
-- 转换坐标,将屏幕坐标转换成GLView的坐标
local startEndPos = self:getMoveEndPos(screenX , screenY);
local startPos = startEndPos.startPos;
local endPos = startEndPos.endPos;
-- 如果没有发生偏移则不需要移动
if cc.pEqual(endPos, startPos) then
return;
end
-- 通过命令来移动
local commands = {};
local scale = app.setting.ScreenScale;
local offset = cc.pSub(endPos , startPos);
-- 增量
local targetOffset = cc.vec3(offset.x / scale, offset.y / scale, 0);
for i , v in pairs(self.originPoies) do
local originWorld = i:getParent():convertToWorldSpace(v.pos);
local newWorld = cc.vec3Add(originWorld , targetOffset);
local newLocal = roundVec3(i:getParent():convertToNodeSpace(newWorld));
-- 将节点的位置恢复到原始位置
i:setTranslation(v.pos);
table.insert(commands, Commands:moveNode(i, newLocal));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

function Move2DTool:commandMoveBy(offset)
-- 如果没有发生偏移则不需要移动
if cc.pEqual(offset, {x = 0, y = 0}) then
return;
end
-- 增量
local scale = app.setting.ScreenScale;
local targetOffset = cc.vec3(offset.x, offset.y, 0);
-- 通过命令来移动
local commands = {};
for i , v in pairs(app.editor.SelectedNodes) do
local originWorld = v:getParent():convertToWorldSpace(v:getPosition());
local newWorld = cc.vec3Add(originWorld , targetOffset);
local newLocal = roundVec3(v:getParent():convertToNodeSpace(newWorld));

-- v:setPosition(newLocal);
table.insert(commands, Commands:moveNode(v, newLocal));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

return Move2DTool;

+ 171
- 0
Editor/Move3DTool.lua Näytä tiedosto

@@ -0,0 +1,171 @@
-- 3D平訂伽邿佴艤
local Move3DTool = class("Move3DTool", require("MoveTool"))
function Move3DTool:ctor()
self.super.ctor(self);
self.factor = 1.0;
self.startScreenPos = nil;
end

function Move3DTool:clear()
self.super.clear(self);
self.startScreenPos = nil;
end

function Move3DTool:MouseDown(button , x , y)
if self.super.MouseDown(self, button, x, y) then
self.startScreenPos = cc.p(x, y);
end
end

function Move3DTool:convertScreenToWorldPos(mouseX, mouseY, planeNormal, planeDistance)
local floorPlane = cc.Plane:new(planeNormal , planeDistance);

-- 輪蹋远mainlayer謩藔蕨位變
local screenSize = cc.Director:getInstance():getWinSizeInPixels();
local ray = app.mainCamera:pickRay(mouseX / screenSize.width , mouseY / screenSize.height);
local dist = ray:intersectsPlane(floorPlane);
if dist >= 0 then
return ray:getPoint(dist);
else
return ray:getPoint(0);
end
end

function Move3DTool:moveTo(screenX, screenY)
-- 斩
local targetOffset;
--[[local offset = cc.pSub(endPos , self.startPos);
if app.cs.getModifierKeys() == Keys.Control then
-- 只艤覙Y住蕪袀訂织
targetOffset = cc.vec3(0, offset.y * self.factor, 0);
else
-- 諝XZ平摩蕪摩平訂
targetOffset = cc.vec3(offset.x * self.factor, 0, offset.y * self.factor);
end--]]

-- Shift酄樧喲阶?
if app.cs.getModifierKeys() == Keys.Shift then
for i , v in pairs(self.originPoies) do
local originWorld = v.rotate;
i:setEulerRotation(originWorld.x , originWorld.y + (screenX - self.startScreenPos.x) , originWorld.z);
end
else
for i , v in pairs(self.originPoies) do
local originWorld = i:getParent():convertToWorldSpace(v.pos);
if app.cs.getModifierKeys() == Keys.Control then
-- 只艤覙Y住蕪袀訂织
-- 顺要写袀时謩藔蕨位變
local normal
if originWorld.z > 0 then
normal = cc.vec3(0,0,-1)
else
normal = cc.vec3(0,0,1)
end
local downWorldPos = self:convertScreenToWorldPos(self.startScreenPos.x, self.startScreenPos.y, normal, originWorld.z);
-- 毡前顺要謩藔蕨位變
local curWorldPos = self:convertScreenToWorldPos(screenX, screenY, normal, originWorld.z);
targetOffset = cc.vec3(0, curWorldPos.y - downWorldPos.y, 0);
else
local normal
if originWorld.y > 0 then
normal = cc.vec3(0,-1,0)
else
normal = cc.vec3(0,1,0)
end
-- 顺要写袀时謩藔蕨位變
local downWorldPos = self:convertScreenToWorldPos(self.startScreenPos.x, self.startScreenPos.y, normal, originWorld.y);
-- 毡前顺要謩藔蕨位變
local curWorldPos = self:convertScreenToWorldPos(screenX, screenY, normal, originWorld.y);
targetOffset = cc.vec3(curWorldPos.x - downWorldPos.x, 0, curWorldPos.z - downWorldPos.z);
end
local newWorld = cc.vec3Add(originWorld , targetOffset);
local newLocal = i:getParent():convertToNodeSpace(newWorld);
i:setTranslation(newLocal);
end
end
end

function Move3DTool:commandMoveTo(screenX, screenY)
local endPos = cc.p(screenX, screenY);
-- 骚诨没詯注屎偏訂詹一穴要訂织
if cc.pEqual(endPos, self.startPos) then
return;
end
-- 通诮募庐4訂织
local commands = {};
-- 斩
local targetOffset;
if app.cs.getModifierKeys() == Keys.Shift then
for i , v in pairs(self.originPoies) do
local originWorld = v.rotate;
local newLocal = cc.vec3(originWorld.x , originWorld.y + (screenX - self.startScreenPos.x) , originWorld.z);
i:setEulerRotation(v.rotate);
table.insert(commands, Commands:rotateNode(i, newLocal));
end
else
for i , v in pairs(self.originPoies) do
local originWorld = i:getParent():convertToWorldSpace(v.pos);
if app.cs.getModifierKeys() == Keys.Control then
-- 只艤覙Y住蕪袀訂织
-- 顺要写袀时謩藔蕨位變
local normal
if originWorld.z > 0 then
normal = cc.vec3(0,0,-1)
else
normal = cc.vec3(0,0,1)
end
local downWorldPos = self:convertScreenToWorldPos(self.startScreenPos.x, self.startScreenPos.y, normal, originWorld.z);
-- 毡前顺要謩藔蕨位變
local curWorldPos = self:convertScreenToWorldPos(screenX, screenY, normal, originWorld.z);
targetOffset = cc.vec3(0, curWorldPos.y - downWorldPos.y, 0);
else
local normal
if originWorld.y > 0 then
normal = cc.vec3(0,-1,0)
else
normal = cc.vec3(0,1,0)
end
-- 顺要写袀时謩藔蕨位變
local downWorldPos = self:convertScreenToWorldPos(self.startScreenPos.x, self.startScreenPos.y, normal, originWorld.y);
-- 毡前顺要謩藔蕨位變
local curWorldPos = self:convertScreenToWorldPos(screenX, screenY, normal, originWorld.y);
targetOffset = cc.vec3(curWorldPos.x - downWorldPos.x, 0, curWorldPos.z - downWorldPos.z);
end
local newWorld = cc.vec3Add(originWorld , targetOffset);
local newLocal = i:getParent():convertToNodeSpace(newWorld);
i:setTranslation(v.pos);
table.insert(commands, Commands:moveNode(i, newLocal));
end
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

function Move3DTool:commandMoveBy(offset)
-- 骚诨没詯注屎偏訂詹一穴要訂织
if cc.pEqual(offset, {x = 0, y = 0}) then
return;
end
-- 斩
local targetOffset = cc.vec3(offset.x, 0, offset.y);
-- 通诮募庐4訂织
local commands = {};
for i , v in pairs(app.editor.SelectedNodes) do
local originWorld = v:getParent():convertToWorldSpace(v:getPosition());
local newWorld = cc.vec3Add(originWorld , targetOffset);
local newLocal = v:getParent():convertToNodeSpace(newWorld);
table.insert(commands, Commands:moveNode(v, newLocal));
end
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

return Move3DTool;

+ 292
- 0
Editor/MoveTool.lua Näytä tiedosto

@@ -0,0 +1,292 @@
require("EditorGlobalFunction")

local MoveTool = class("MoveTool")
function MoveTool:ctor()
self.onSelect = nil;
end

function MoveTool:clear()
self.startPos = nil;
self.originPoies = nil;
if self.selectRectNode then
self.selectRectNode:removeFromParent();
self.selectRectNode = nil;
end
end

-- 计算节点是否跟矩形相交,如果相交,则插入到intersects表中
local function intersectNode(node , rect , intersects , all)
-- 隐藏节点不给选中
if not node:isVisible() then
return;
end
node:sortAllChildren();
-- 递归
local children = node:getChildren();
for i = #children , 1 , -1 do
intersectNode(children[i] , rect , intersects , all)
end
if node:selectTest(rect) then
-- 是否忽略空节点
if app.editor:canSelectNode(all, node) then
table.insert(intersects , node);
end
end
end

function MoveTool:MouseDown(button , x , y)
-- 按下ALT控制相机
if app.cs.getModifierKeys() == Keys.Alt then
return false;
end
-- 不是鼠标左键按下不处理
if button ~= MouseButtons.Left then
if button == MouseButtons.Right then
return true;
end
return false;
end
self.startPos = cc.p(x, y);
self.originPoies = {};

local size = cc.Director:getInstance():getWinSize();
local screenSize = cc.Director:getInstance():getWinSizeInPixels();
local ray = app.mainCamera:pickRay(self.startPos.x / screenSize.width , self.startPos.y / screenSize.height);
--[[local hitTest = cc.PhysicsController:getInstance():rayTest(ray, 100000)
if hitTest == true then
print("击中目标了")
end--]]
-- 计算点选的区域
local rect = cc.Rectangle:new(self.startPos.x / size.width , self.startPos.y / size.height , 1 / size.width , 1 / size.height);
-- 看是否点中的是已选择的,如果是,则只是记录点选位置
local hitNode;
for i , v in pairs(app.editor.SelectedNodes) do
if v:selectTest(rect) then
hitNode = v;
end
end
-- 没选中任何东西
if not hitNode then
if self.selectRectNode then
self.selectRectNode:removeFromParent();
self.selectRectNode = nil;
end
-- 这里需要支持撤销
--[[local commands = {};
-- 有选中的东西则需要通过命令来撤销
if next(app.editor.SelectedNodes) ~= nil then
local command = Commands:unselect(app.editor.SelectedNodes);
table.insert(commands, command);
end--]]
-- 实现Ctrl按住可以多选
if app.cs.getModifierKeys() ~= Keys.Control then
app.editor:clearSelect();
end
local intersects = {};
-- 递归计算哪些节点相交
intersectNode(app.editor.node , rect , intersects);
-- 选中第一个
local selectedNode = intersects[1];
if selectedNode then
-- 选中
app.cs.selectNodes({selectedNode});
app.editor:selectNode(selectedNode);
app.cs.setPropertyObject(selectedNode);
-- 通过命令来选中
--[[local command = Commands:select(intersects);
table.insert(commands, command);--]]
else
self.selectRectNode = cc.BoxNode:create();
self.selectRectNode.startPos = app.visibleRect:convertScreenToGLView(self.startPos.x, self.startPos.y);
self.selectRectNode.endPos = app.visibleRect:convertScreenToGLView(self.startPos.x, self.startPos.y);
-- 计算开始点
app.mainLayer:addChild(self.selectRectNode);
end
--app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end
-- 记录下所有节点的位置
for i , v in pairs(app.editor.SelectedNodes) do
-- 如果自己的父节点在这个列表里面则不需要统计了
if not ParentNodeIsInTable(v, app.editor.SelectedNodes) then
self.originPoies[v] =
{
pos = v:getTranslation();
rotate = v:getEulerRotation();
}
end
end
return true;
end

-- 派生类重写
function MoveTool:moveTo(screenX, screenY)

end

-- 派生类重写
function MoveTool:commandMoveTo(screenX, screenY)
end

-- 派生类重写
function MoveTool:commandMoveBy(offset)
end

-- 派生类重写
function MoveTool:MouseMove(button , x , y)
if not self.startPos then return end
-- 计算结束点
if self.selectRectNode then
self.selectRectNode.endPos = app.visibleRect:convertScreenToGLView(x, y);
end
self:moveTo(x, y);
end

function MoveTool:MouseUp(button , x , y)
if button == MouseButtons.Right then
local editor = app.editor;
--editor:clearSelect ();
local size = cc.Director:getInstance():getWinSize();
local intersects = {};
local rect = cc.Rectangle:new(x / size.width , y / size.height , 1 / size.width , 1 / size.height);
-- 递归计算哪些节点相交
intersectNode(editor.node ,rect, intersects, true);

local items = {};
for _ , item in pairs(intersects) do
table.insert(items , {
text = item:getName () ;
func = function()
editor:clearSelect ();
editor:selectNode (item);
app.cs.selectNodes ({item});
app.cs.setPropertyObject (item);
end;
});
end
app.cs.popMenu(items,{x=x;y=y;});
return;
end

if not self.startPos then return end
-- 计算结束点
self:commandMoveTo(x, y);

-- 如果没有元素
if next(app.editor.SelectedNodes) == nil then
local startPos = self.startPos;
local endPos = cc.p(x, y);
-- 计算框选的区域
local size = cc.Director:getInstance():getWinSize();
local rect = cc.Rectangle:new(math.min(startPos.x , endPos.x) / size.width
, math.min(startPos.y , endPos.y) / size.height
, math.abs(endPos.x - startPos.x) / size.width
, math.abs(endPos.y - startPos.y) / size.height
);
local intersects = {};
-- 计算哪些节点相交
-- 递归
intersectNode(app.editor.node , rect , intersects);
-- 实现Ctrl按住可以多选
if app.cs.getModifierKeys() ~= Keys.Control then
app.editor:clearSelect();
end
-- 通过命令来选中
--[[local command = Commands:select(intersects);
app.undoRedoManager:doCommand(command);--]]
if intersects[1] then
app.cs.setPropertyObject(intersects[1]);
end
app.cs.selectNodes(intersects);
for i , v in pairs(intersects) do
app.editor:selectNode(v);
end
end

self:clear();
end

function MoveTool:KeyDown(Control, Alt, Shift, KeyCode)
end

function MoveTool:KeyUp(Control, Alt, Shift, KeyCode)

end

function MoveTool:DialogKey(Control, Alt, Shift, KeyCode)
if Alt then
if KeyCode == Keys.Up then
local maxY = 0;
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
maxY = math.max(maxY , node:getPositionY() + node:getAnchorPoint().y * node:getContentSize().height);
end
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
local offsetY = maxY - (node:getPositionY() + node:getAnchorPoint().y * node:getContentSize().height);
node:setPositionY(node:getPositionY() + offsetY);
end
elseif KeyCode == Keys.Down then
local minY = 65536;
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
minY = math.min(minY , node:getPositionY() - node:getAnchorPoint().y * node:getContentSize().height);
end
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
local offsetY = minY - (node:getPositionY() - node:getAnchorPoint().y * node:getContentSize().height);
node:setPositionY(node:getPositionY() + offsetY);
end
elseif KeyCode == Keys.Left then
local minX = 65536;
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
minX = math.min(minX , node:getPositionX() - node:getAnchorPoint().x * node:getContentSize().width);
end
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
local offsetX = minX - (node:getPositionX() - node:getAnchorPoint().x * node:getContentSize().width);
node:setPositionX(node:getPositionX() + offsetX);
end
elseif KeyCode == Keys.Right then
local maxX = 0;
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
maxX = math.max(maxX , node:getPositionX() + node:getAnchorPoint().x * node:getContentSize().width);
end
for i , v in pairs(app.editor.SelectedNodes) do
local node = v;
local offsetX = maxX - (node:getPositionX() + node:getAnchorPoint().x * node:getContentSize().width);
node:setPositionX(node:getPositionX() + offsetX);
end
end

else
local offset = cc.p(0,0);
if KeyCode == Keys.Up then
offset.y = 1;
end
if KeyCode == Keys.Down then
offset.y = -1;
end
if KeyCode == Keys.Left then
offset.x = -1;
end
if KeyCode == Keys.Right then
offset.x = 1;
end
self:commandMoveBy(offset);
end
end

return MoveTool;

+ 269
- 0
Editor/NodeEditor.lua Näytä tiedosto

@@ -0,0 +1,269 @@
require("UIWidget");
require("CCRectNode");
local NodeEditor = class("NodeEditor" , require("Editor"));

function NodeEditor:ctor()
self.SelectedNodes = {}
-- 节点计数器
self.NodeCount = 1
self.SelectedIndex = 1;
end

function NodeEditor:activate()
-- 恢复场景的位置
app.mainScene:setPosition(cc.p(0,0));
-- 恢复下场景的缩放
app.setting.ScreenScale = 1;
app.mainScene:setScale(app.setting.ScreenScale);
end

function NodeEditor:unactivate()
self:closeNode();
end

function NodeEditor:play()
if self.node then
self.node:playCurveAnimation();
if self.node.stop then
self.node:stop();
end
if self.node.play then
self.node:play();
end
end
end

-- 是否可以选中此节点
function NodeEditor:canSelectNode(flag, node)
-- 忽略空节点
if not flag and table.valueOfItem({"Layout", "GridLine" , "Scaler" , "Node" , "Scene"} , node.ClassName) then
return false;
end
return true;
end

function NodeEditor:stop()
if self.node then
self.node:stopCurveAnimation();
if self.node.stop then
self.node:stop();
end
end
end

-- 各个派生类可以重写这个函数
function NodeEditor:save(filename)
NodeEditor.super.save(self, filename);
--self.node:save(filename);
self.node:saveToFile(filename);

-- 清空undoredoManager
app.undoRedoManager:clear();
end

-- 关闭光效
function NodeEditor:closeNode()
if self.node then
self.node:removeFromParent();
self.node = nil;
end
self:clearSelect();
end

-- 初始化光效,添加到场景中
function NodeEditor:initNode(node)
self.node = node
app.mainLayer:addChild(self.node)
end

function NodeEditor:createNode(nodeType)
local node = cc[nodeType]:createNode()
-- 设置节点的名字
node:setName(nodeType)
if type(node.setDefaults) == "function" then
node:setDefaults();
end
self:autoSetNodeName(node);
return node;
end

-- 从文件载入节点
function NodeEditor:loadNode(nodeFile)
self:closeNode();
--self.node = createNodeFromFile(nodeFile);
self.node = tolua.cast(cc.StreamObject:loadFromFile(nodeFile) , "cc.Node3D");
self:initNode(self.node);
return self.node;
end

-- 清除所有选择
function NodeEditor:clearSelect()
for i , v in pairs(self.SelectedNodes) do
v.selectedNode:removeFromParent();
v.selectedNode = nil;
end
self.SelectedNodes = {};
end

--[[-- 通过命令清除所有选择
function NodeEditor:commandClearSelect()
if table.nums(self.SelectedNodes) <= 0 then
return;
end
-- 通过command来清空选择
local command = Commands:unselect(self.SelectedNodes);
app.undoRedoManager:doCommand(command);
end--]]

-- 取消选择一个节点
function NodeEditor:unSelectNode(node)
if not self.SelectedNodes[node] then
return
end
-- 去掉选择框
local curNode = self.SelectedNodes[node];
curNode.selectedNode:removeFromParent();
curNode.selectedNode = nil;
-- 从列表中去掉
self.SelectedNodes[node] = nil;
end

-- 通过命令取消选择一个节点
--[[function NodeEditor:commandUnselectNode(node)
local nodes = {};
table.insert(nodes, node);
local command = Commands:unselect(nodes);
app.undoRedoManager:doCommand(command);
end--]]

-- 选择一个节点
function NodeEditor:selectNode(node)
if self.SelectedNodes[node] then
return;
end
self.SelectedNodes[node] = node;
-- 保存计数值,记录选中的顺序
node.SelectedIndex = self.SelectedIndex;
self.SelectedIndex = self.SelectedIndex + 1;

local rectNode = cc.RectNode:create(node);
node.selectedNode = rectNode;
app.mainLayer:addChild(rectNode);
end

-- 通过命令选择一个节点
--[[function NodeEditor:commandSelectNode(node)
local nodes = {};
table.insert(nodes, node);
local command = Commands:select(nodes);
app.undoRedoManager:doCommand(command);
end--]]

-- 删除选中的节点
function NodeEditor:deleteNode(node)
-- 不在选中队列里不能删除
if not self.SelectedNodes[node] then
return;
end
-- 去掉选择框
local curNode = self.SelectedNodes[node];
curNode.selectedNode:removeFromParent();
curNode.selectedNode = nil;
-- 从列表中去掉
self.SelectedNodes[node] = nil;
node:removeFromParent();
end

-- 通过命令删除一个节点
function NodeEditor:commandDeleteNode(node)
local command = Commands:deleteNode(node);
app.undoRedoManager:doCommand(command);
end

-- 删除所有选中的节点
function NodeEditor:commandDeleteSelectNodes()
if next(self.SelectedNodes) == nil then
return;
end
-- 如果子节点和父节点都在删除的范围里面则只删除父节点就可以了
local deleteNodes = {};
for i, v in pairs(self.SelectedNodes) do
if not ParentNodeIsInTable(v, self.SelectedNodes) then
table.insert(deleteNodes, v);
end
end
local commands = {};
for i, v in pairs(deleteNodes) do
local command = Commands:deleteNode(v);
table.insert(commands, command);
end
-- 清空所有选中
self:clearSelect();
app.undoRedoManager:doCommand(Commands:batchCommand(commands));
end

-- 改变节点的父子关系
function NodeEditor:commandModityNode(node, newParent)
local command = Commands:modifyNode(node, newParent);
app.undoRedoManager:doCommand(command);
end

-- 复制节点到另一个节点下面
function NodeEditor:commandCopyNode(node, parentNode)
local command = Commands:addNode(node, parentNode);
app.undoRedoManager:doCommand(command);
end

-- 复制一个节点的动画到另一个节点下面
function NodeEditor:commandCopyNodeAnim(node, parentNode)
local command = Commands:copyNodeAnim(node, parentNode);
app.undoRedoManager:doCommand(command);
end

function NodeEditor:sceneToMouse(x , y)
return app.mainLayer:convertToWorldSpace(cc.p(x,y));
end

function NodeEditor:mouseToScene(x , y)
return app.mainLayer:convertToNodeSpace(cc.p(x,y));
end

-- 摆放一个节点到场景中
-- @nodeType 节点类型名字
-- @parentNode 父节点
-- @posWithMouse 鼠标的窗口位置
function NodeEditor:placeNode(nodeType , parentNode , posWithMouse)
local node = self:createNode(nodeType);
local pNode = nil;
if parentNode then
pNode = parentNode;
else
pNode = self.node;
end
-- 设置世界坐标
if posWithMouse then
local worldPos = app.cameraController:convertScreenToWorldPos(posWithMouse.x , posWithMouse.y);
local nodePos = pNode:convertToNodeSpace(worldPos);
node:setTranslation(nodePos);
end
-- 通过命令添加到节点树里面
local command = Commands:addNode(node, pNode);
app.undoRedoManager:doCommand(command);

return node;
end

return NodeEditor;

+ 101
- 0
Editor/ObstacleTool.lua Näytä tiedosto

@@ -0,0 +1,101 @@
-- 填充障碍块工具
local ObstacleTool = class("ObstacleTool")

local ToolSize = 0;

function ObstacleTool:MouseDown(button , x , y)
-- 按下ALT控制相机
if app.cs.getModifierKeys() == Keys.Alt then return end

-- 转换坐标
local worldPos = app.cameraController:convertScreenToWorldPos(x, y);
-- 将像素坐标转换成逻辑坐标
local logicalPos = app.editor.Map:getTilePosition(worldPos.x, worldPos.z);
-- 左键按下添加障碍快
if (button == MouseButtons.Left) then
for x = -ToolSize , ToolSize do
for y = -ToolSize , ToolSize do
app.editor.Map:addObstacle(logicalPos.x + x, logicalPos.y + y);
end
end
end
-- 右键按下删除障碍块
if (button == MouseButtons.Right) then
for x = -ToolSize , ToolSize do
for y = -ToolSize , ToolSize do
app.editor.Map:removeObstacle(logicalPos.x + x, logicalPos.y + y);
end
end
end

-- 中间填充
if button == MouseButtons.Middle then
local map = app.editor.Map;
local function FillShape(x, y)
if not map:isInMap(x , y) then
return
end
if not map:isObstacle(x,y) then
map:addObstacle(x, y);
FillShape(x+1, y);
FillShape(x-1, y);
FillShape(x, y+1);
FillShape(x, y-1);
end
end
FillShape(logicalPos.x , logicalPos.y);
end
end

function ObstacleTool:MouseMove(button, x , y)
-- 按下ALT控制相机
if app.cs.getModifierKeys() == Keys.Alt then return end

-- 转换坐标
local worldPos = app.cameraController:convertScreenToWorldPos(x, y);
-- 将像素坐标转换成逻辑坐标
local logicalPos = app.editor.Map:getTilePosition(worldPos.x, worldPos.z);
-- 左键按下添加障碍快
if (button == MouseButtons.Left) then
for x = -ToolSize , ToolSize do
for y = -ToolSize , ToolSize do
app.editor.Map:addObstacle(logicalPos.x + x, logicalPos.y + y);
end
end
end
-- 右键按下删除障碍块
if (button == MouseButtons.Right) then
for x = -ToolSize , ToolSize do
for y = -ToolSize , ToolSize do
app.editor.Map:removeObstacle(logicalPos.x + x, logicalPos.y + y);
end
end
end
end


function ObstacleTool:DialogKey(Control, Alt, Shift, KeyCode)
if KeyCode == Keys.Up then
ToolSize = ToolSize + 1;
elseif KeyCode == Keys.Down then
ToolSize = ToolSize - 1;
elseif KeyCode == Keys.Left then
ToolSize = ToolSize - 10;
elseif KeyCode == Keys.Right then
ToolSize = ToolSize + 10;
end
if ToolSize > 100 then
ToolSize = 100;
elseif ToolSize < 0 then
ToolSize = 0;
end
ToolSize = math.ceil(ToolSize);
end


function ObstacleTool:MouseUp(button, x, y)
end

return ObstacleTool;

+ 453
- 0
Editor/PostloadResource.lua Näytä tiedosto

@@ -0,0 +1,453 @@
--这里指定客户端后期加载
return
{
--后期加载的目录
Dirs=
{
["res/ui/b_baowu"]=true,
["res/ui/c_chengjiu"]=true,
["res/ui/d_dixiacheng"]=true,
["res/ui/c_chongzhi"]=true,
["res/ui/h_haoyou"]=true,
["res/ui/z_zhulizhongzu"]=true,
["res/ui/ui_lianmeng"]=true,
["res/ui/j_jiuguan"]=true,
["res/ui/q_qianghua"]=true,
["res/ui/ui_wjinchanglang"]=true,
["res/ui/z_zhuangbeihecheng"]=true,
["res/ui/ui_huodong"]=true,
["res/ui/s_shangdian"]=true,
["res/sound/BattleVoice"]=true,
["res/ui/ui_chongzhi"]=true,
["res/animation/YM_1"]=true,
["res/animation/SFMN"]=true,
["res/animation/SDHB"]=true,
["res/animation/DXLZ"]=true,
["res/animation/JSZZ"]=true,
["res/animation/WTQS"]=true,
["res/animation/XGJ"]=true,
["res/animation/BSWY"]=true,
["res/animation/LXZY"]=true,
["res/animation/TKBZ"]=true,
["res/animation/CJZ"]=true,
["res/animation/TQBZ"]=true,
["res/animation/XDZ"]=true,
["res/animation/EMZS"]=true,
["res/animation/KJMW"]=true,
["res/animation/TLWN"]=true,
["res/animation/AYLR"]=true,
["res/animation/XSNW"]=true,
["res/animation/TYS"]=true,
["res/animation/HYS"]=true,
["res/animation/SYS"]=true,
["res/animation/FYS"]=true,
["res/animation/LL"]=true,
["res/animation/DLY"]=true,
["res/animation/XJL"]=true,
["res/animation/KMJY"]=true,
["res/animation/JDZY"]=true,
["res/animation/YXZ"]=true,
["res/animation/ZZMR"]=true,
["res/animation/monster/JXBB"]=true,
["res/animation/monster/JS"]=true,
["res/animation/monster/HAIBO"]=true,
["res/animation/monster/WLTF"]=true,
["res/animation/monster/TC"]=true,
["res/animation/monster/DZZ"]=true,
["res/animation/monster/DJEM"]=true,
["res/animation/monster/YJ"]=true,
["res/animation/monster/XX"]=true,
["res/animation/monster/NJS"]=true,
["res/animation/monster/BMX"]=true,
["res/animation/monster/LX"]=true,
["res/animation/monster/HB"]=true,
["res/animation/monster/XEJXS"]=true,
["res/animation/monster/JBGX"]=true,
["res/animation/monster/KLGS"]=true,
["res/animation/BH_1"]=true,
["res/animation/BSWY_1"]=true,
["res/animation/EMZS_1"]=true,
["res/animation/LL_1"]=true,
["res/animation/SDHB_1"]=true,
["res/animation/TYS_1"]=true,
["res/animation/XCJS_1"]=true,
["res/animation/XJL_1"]=true,
["res/animation/ZZMR_1"]=true,
["res/animation/YM"]=true,
["res/effect/ActorSkillEffect/YM"]=true,
["res/effect/ActorSkillEffect/SFMN"]=true,
["res/effect/ActorSkillEffect/SDHB"]=true,
["res/effect/ActorSkillEffect/DXLZ"]=true,
["res/effect/ActorSkillEffect/JSZZ"]=true,
["res/effect/ActorSkillEffect/WTQS"]=true,
["res/effect/ActorSkillEffect/XGJ"]=true,
["res/effect/ActorSkillEffect/BSWY"]=true,
["res/effect/ActorSkillEffect/LXZY"]=true,
["res/effect/ActorSkillEffect/TKBZ"]=true,
["res/effect/ActorSkillEffect/CJZ"]=true,
["res/effect/ActorSkillEffect/TQBZ"]=true,
["res/effect/ActorSkillEffect/XDZ"]=true,
["res/effect/ActorSkillEffect/EMZS"]=true,
["res/effect/ActorSkillEffect/KJMW"]=true,
["res/effect/ActorSkillEffect/XCJS"]=true,
["res/effect/ActorSkillEffect/TLWN"]=true,
["res/effect/ActorSkillEffect/AYLR"]=true,
["res/effect/ActorSkillEffect/XSNW"]=true,
["res/effect/ActorSkillEffect/TYS"]=true,
["res/effect/ActorSkillEffect/HYS"]=true,
["res/effect/ActorSkillEffect/SYS"]=true,
["res/effect/ActorSkillEffect/FYS"]=true,
["res/effect/ActorSkillEffect/LL"]=true,
["res/effect/ActorSkillEffect/DLY"]=true,
["res/effect/ActorSkillEffect/XJL"]=true,
["res/effect/ActorSkillEffect/KMJY"]=true,
["res/effect/ActorSkillEffect/JDZY"]=true,
["res/effect/ActorSkillEffect/YXZ"]=true,
["res/effect/ActorSkillEffect/ZZMR"]=true,
["res/scene/scene_LMDT_001"]=true,
["res/scene/scene_LMDT_zhanchang_001"]=true,
["res/scene/scene_fukongdao_pve_001"]=true,
["res/scene/scene_fukongdao_pvp_002"]=true,
["res/scene/sc_hd_zhanchang"]=true,
["res/scene/sc_mx_hd_001"]=true,
},
--后期加载的文件
Files=
{
["res/ui/gengengxinbao/jingyingdixiachengditu_01.png"]=true,
["res/ui/gengengxinbao/jingyingdixiachengditu_02.png"]=true,
["res/ui/gengengxinbao/qianghua_quan_di.png"]=true,
["res/ui/gengengxinbao/kaifuhuodong_renwu.png"]=true,
["res/ui/gengengxinbao/chognzhi_mingzilibao.jpg"]=true,
["res/ui/gengengxinbao/kaiqikunnanmoashi.jpg"]=true,
["res/ui/gengengxinbao/kaifuhuodong_wenzi.png"]=true,
["res/ui/gengengxinbao/pingjia_app_01.png"]=true,
["res/ui/gengengxinbao/q_jing_09_faguang.png"]=true,
["res/ui/gengengxinbao/shaungbei_yeqian_03.png"]=true,
["res/ui/gengengxinbao/zuiqiangzhengduo_shang.png"]=true,
["res/ui/gengengxinbao/q_jing_09.png"]=true,
["res/ui/gengengxinbao/q_jing_10_faguang.png"]=true,
["res/ui/gengengxinbao/shaungbei_yeqian_01.png"]=true,
["res/ui/gengengxinbao/zuiqiangzhengduo_xia.png"]=true,
["res/ui/gengengxinbao/q_jing_10.png"]=true,
["res/ui/gengengxinbao/chunjie_beijing.png"]=true,
["res/ui/gengengxinbao/shaungbei_yeqian_02.png"]=true,
["res/ui/gengengxinbao/shaungbei_yeqian_04.png"]=true,
["res/sound/scene/map_3.ogg"]=true,
["res/sound/scene/zhanchang_PVP_002.ogg"]=true,
["res/sound/scene/zhanchang_PVE_005.ogg"]=true,
["res/sound/scene/map_4.ogg"]=true,
["res/sound/scene/zhanchang_PVP_001.ogg"]=true,
["res/sound/scene/zhanchang_PVE_003.ogg"]=true,
["res/sound/scene/zhucheng_1.ogg"]=true,
["res/sound/scene/zhanchang_PVE_006.ogg"]=true,
["res/sound/scene/zhanchang_PVP_003.ogg"]=true,
["res/sound/scene/zhanchang_PVE_002.ogg"]=true,
["res/sound/scene/zhanchang_PVE_001.ogg"]=true,
["res/sound/scene/Sweeping.ogg"]=true,
["res/sound/scene/zhanchang_PVE_004.ogg"]=true,
["res/sound/scene/zhanchang_PVS_001.ogg"]=true,
["res/sound/scene/zhanchang_PVS_002.ogg"]=true,
["res/sound/scene/zhanchang_PVS_003.ogg"]=true,
["res/sound/scene/jingjichang_1.ogg"]=true,
["res/sound/scene/map_1.ogg"]=true,
["res/sound/scene/LianMeng_2.ogg"]=true,
["res/sound/scene/jingjichang_2.ogg"]=true,
["res/sound/scene/JiuGuan_1.ogg"]=true,
["res/sound/scene/JiuGuan_2.ogg"]=true,
["res/sound/scene/JiuGuan_3.ogg"]=true,
["res/sound/scene/AHorseThrough.ogg"]=true,
["res/sound/scene/RunToMainCity.ogg"]=true,
["res/sound/Nico/Nico_02.ogg"]=true,
["res/sound/Nico/Nico_03.ogg"]=true,
["res/sound/Nico/Nico_05.ogg"]=true,
["res/sound/Nico/Nico_06.ogg"]=true,
["res/sound/Nico/Nico_07.ogg"]=true,
["res/sound/Nico/Nico_08.ogg"]=true,
["res/sound/Nico/Nico_09.ogg"]=true,
["res/sound/Nico/Nico_10.ogg"]=true,
["res/sound/Nico/Nico_11.ogg"]=true,
["res/sound/Nico/Nico_12.ogg"]=true,
["res/sound/Nico/Nico_13.ogg"]=true,
["res/sound/Nico/Nico_14.ogg"]=true,
["res/sound/Nico/Nico_17.ogg"]=true,
["res/sound/Nico/Nico_18.ogg"]=true,
["res/sound/Nico/Nico_19.ogg"]=true,
["res/sound/Nico/Nico_21.ogg"]=true,
["res/sound/Nico/Nico_23.ogg"]=true,
["res/sound/Nico/Nico_24.ogg"]=true,
["res/sound/Nico/Nico_27.ogg"]=true,
["res/sound/Nico/Nico_28.ogg"]=true,
["res/sound/Nico/Nico_29.ogg"]=true,
["res/sound/Nico/Nico_30.ogg"]=true,
["res/sound/Nico/Nico_31.ogg"]=true,
["res/sound/Nico/Nico_32.ogg"]=true,
["res/sound/Nico/Nico_33.ogg"]=true,
["res/sound/Nico/Nico_34.ogg"]=true,
["res/sound/Nico/Nico_35.ogg"]=true,
["res/sound/Nico/Nico_36.ogg"]=true,
["res/sound/Nico/Nico_37.ogg"]=true,
["res/sound/Nico/Nico_38.ogg"]=true,
["res/sound/Nico/Nico_39.ogg"]=true,
["res/sound/Nico/Nico_40.ogg"]=true,
["res/sound/Nico/Nico_44.ogg"]=true,
["res/sound/Nico/Nico_45.ogg"]=true,
["res/sound/Nico/Nico_46.ogg"]=true,
["res/sound/Nico/Nico_47.ogg"]=true,
["res/sound/Nico/Nico_48.ogg"]=true,
["res/sound/Nico/Nico_49.ogg"]=true,
["res/sound/Nico/Nico_50.ogg"]=true,
["res/sound/Nico/Nico_51.ogg"]=true,
["res/sound/Nico/Nico_52.ogg"]=true,
["res/sound/Nico/Nico_53.ogg"]=true,
["res/sound/Nico/Nico_54.ogg"]=true,
["res/sound/Nico/Nico_55.ogg"]=true,
["res/sound/Nico/Nico_56.ogg"]=true,
["res/sound/Nico/Nico_57.ogg"]=true,
["res/sound/Nico/Nico_58.ogg"]=true,
["res/sound/Nico/Nico_59.ogg"]=true,
["res/sound/Nico/Nico_60.ogg"]=true,
["res/sound/Nico/Nico_62.ogg"]=true,
["res/sound/Nico/Nico_63.ogg"]=true,
["res/sound/UI/EnterWounder.ogg"]=true,
["res/sound/UI/EnterKingView.ogg"]=true,
["res/sound/UI/Lose.ogg"]=true,
["res/sound/UI/EnterAchieveView.ogg"]=true,
["res/sound/UI/SagaSynthesis.ogg"]=true,
["res/sound/AYLR/AYLR_born_1.ogg"]=true,
["res/sound/AYLR/AYLR_born_2.ogg"]=true,
["res/sound/AYLR/AYLR_born_3.ogg"]=true,
["res/sound/BH/BH_born_1.ogg"]=true,
["res/sound/BH/BH_born_2.ogg"]=true,
["res/sound/BH/BH_born_3.ogg"]=true,
["res/sound/BSWY/BSWY_born_1.ogg"]=true,
["res/sound/BSWY/BSWY_born_2.ogg"]=true,
["res/sound/BSWY/BSWY_born_3.ogg"]=true,
["res/sound/CJTS/CJTS_born_1.ogg"]=true,
["res/sound/CJTS/CJTS_born_2.ogg"]=true,
["res/sound/CJTS/CJTS_born_3.ogg"]=true,
["res/sound/CJZ/CJZ_born_1.ogg"]=true,
["res/sound/CJZ/CJZ_born_2.ogg"]=true,
["res/sound/CJZ/CJZ_born_3.ogg"]=true,
["res/sound/DJSS/DJSS_born_1.ogg"]=true,
["res/sound/DJSS/DJSS_born_2.ogg"]=true,
["res/sound/DJSS/DJSS_born_3.ogg"]=true,
["res/sound/DLY/DLY_born_1.ogg"]=true,
["res/sound/DLY/DLY_born_2.ogg"]=true,
["res/sound/DLY/DLY_born_3.ogg"]=true,
["res/sound/DMFS/DMFS_born_1.ogg"]=true,
["res/sound/DMFS/DMFS_born_2.ogg"]=true,
["res/sound/DMFS/DMFS_born_3.ogg"]=true,
["res/sound/DSPG/DSPG_born_1.ogg"]=true,
["res/sound/DSPG/DSPG_born_2.ogg"]=true,
["res/sound/DSPG/DSPG_born_3.ogg"]=true,
["res/sound/DXLZ/DXLZ_born_1.ogg"]=true,
["res/sound/DXLZ/DXLZ_born_2.ogg"]=true,
["res/sound/DXLZ/DXLZ_born_3.ogg"]=true,
["res/sound/DYH/DYH_born_1.ogg"]=true,
["res/sound/DYH/DYH_born_2.ogg"]=true,
["res/sound/DYH/DYH_born_3.ogg"]=true,
["res/sound/EMZS/EMZS_born_1.ogg"]=true,
["res/sound/EMZS/EMZS_born_2.ogg"]=true,
["res/sound/EMZS/EMZS_born_3.ogg"]=true,
["res/sound/FYS/FYS_born_1.ogg"]=true,
["res/sound/FYS/FYS_born_2.ogg"]=true,
["res/sound/FYS/FYS_born_3.ogg"]=true,
["res/sound/GSZZ/GSZZ_born_1.ogg"]=true,
["res/sound/GSZZ/GSZZ_born_2.ogg"]=true,
["res/sound/GSZZ/GSZZ_born_3.ogg"]=true,
["res/sound/HBNW/HBNW_born_1.ogg"]=true,
["res/sound/HBNW/HBNW_born_2.ogg"]=true,
["res/sound/HBNW/HBNW_born_3.ogg"]=true,
["res/sound/HJSJ/HJSJ_born_1.ogg"]=true,
["res/sound/HJSJ/HJSJ_born_2.ogg"]=true,
["res/sound/HJSJ/HJSJ_born_3.ogg"]=true,
["res/sound/HLLZ/HLLZ_born_1.ogg"]=true,
["res/sound/HLLZ/HLLZ_born_2.ogg"]=true,
["res/sound/HLLZ/HLLZ_born_3.ogg"]=true,
["res/sound/HYS/HYS_born_1.ogg"]=true,
["res/sound/HYS/HYS_born_2.ogg"]=true,
["res/sound/HYS/HYS_born_3.ogg"]=true,
["res/sound/HYZD/HYZD_born_1.ogg"]=true,
["res/sound/HYZD/HYZD_born_2.ogg"]=true,
["res/sound/HYZD/HYZD_born_3.ogg"]=true,
["res/sound/JDZY/JDZY_born_1.ogg"]=true,
["res/sound/JDZY/JDZY_born_2.ogg"]=true,
["res/sound/JDZY/JDZY_born_3.ogg"]=true,
["res/sound/JSZZ/JSZZ_born_1.ogg"]=true,
["res/sound/JSZZ/JSZZ_born_2.ogg"]=true,
["res/sound/JSZZ/JSZZ_born_3.ogg"]=true,
["res/sound/KCHY/KCHY_born_1.ogg"]=true,
["res/sound/KCHY/KCHY_born_2.ogg"]=true,
["res/sound/KCHY/KCHY_born_3.ogg"]=true,
["res/sound/KJMW/KJMW_born_1.ogg"]=true,
["res/sound/KJMW/KJMW_born_2.ogg"]=true,
["res/sound/KJMW/KJMW_born_3.ogg"]=true,
["res/sound/KMJY/KMJY_born_1.ogg"]=true,
["res/sound/KMJY/KMJY_born_2.ogg"]=true,
["res/sound/KMJY/KMJY_born_3.ogg"]=true,
["res/sound/KSYR/KSYR_born_1.ogg"]=true,
["res/sound/KSYR/KSYR_born_2.ogg"]=true,
["res/sound/KSYR/KSYR_born_3.ogg"]=true,
["res/sound/LJSS/LJSS_born_1.ogg"]=true,
["res/sound/LJSS/LJSS_born_2.ogg"]=true,
["res/sound/LJSS/LJSS_born_3.ogg"]=true,
["res/sound/LL/LL_born_1.ogg"]=true,
["res/sound/LL/LL_born_2.ogg"]=true,
["res/sound/LL/LL_born_3.ogg"]=true,
["res/sound/LN/LN_born_1.ogg"]=true,
["res/sound/LN/LN_born_2.ogg"]=true,
["res/sound/LN/LN_born_3.ogg"]=true,
["res/sound/LXZY/LXZY_born_1.ogg"]=true,
["res/sound/LXZY/LXZY_born_2.ogg"]=true,
["res/sound/LXZY/LXZY_born_3.ogg"]=true,
["res/sound/SDHB/SDHB_born_1.ogg"]=true,
["res/sound/SDHB/SDHB_born_2.ogg"]=true,
["res/sound/SDHB/SDHB_born_3.ogg"]=true,
["res/sound/SFMN/SFMN_born_1.ogg"]=true,
["res/sound/SFMN/SFMN_born_2.ogg"]=true,
["res/sound/SFMN/SFMN_born_3.ogg"]=true,
["res/sound/SH/SH_born_1.ogg"]=true,
["res/sound/SH/SH_born_2.ogg"]=true,
["res/sound/SH/SH_born_3.ogg"]=true,
["res/sound/SLJR/SLJR_born_1.ogg"]=true,
["res/sound/SLJR/SLJR_born_2.ogg"]=true,
["res/sound/SLJR/SLJR_born_3.ogg"]=true,
["res/sound/STMQ/STMQ_born_1.ogg"]=true,
["res/sound/STMQ/STMQ_born_2.ogg"]=true,
["res/sound/STMQ/STMQ_born_3.ogg"]=true,
["res/sound/SYS/SYS_born_1.ogg"]=true,
["res/sound/SYS/SYS_born_2.ogg"]=true,
["res/sound/SYS/SYS_born_3.ogg"]=true,
["res/sound/TKBZ/TKBZ_born_1.ogg"]=true,
["res/sound/TKBZ/TKBZ_born_2.ogg"]=true,
["res/sound/TKBZ/TKBZ_born_3.ogg"]=true,
["res/sound/TLNW/TLNW_born_1.ogg"]=true,
["res/sound/TLNW/TLNW_born_2.ogg"]=true,
["res/sound/TLNW/TLNW_born_3.ogg"]=true,
["res/sound/TQBZ/TQBZ_born_1.ogg"]=true,
["res/sound/TQBZ/TQBZ_born_2.ogg"]=true,
["res/sound/TQBZ/TQBZ_born_3.ogg"]=true,
["res/sound/TYS/TYS_born_1.ogg"]=true,
["res/sound/TYS/TYS_born_2.ogg"]=true,
["res/sound/TYS/TYS_born_3.ogg"]=true,
["res/sound/WTQS/WTQS_born_1.ogg"]=true,
["res/sound/WTQS/WTQS_born_2.ogg"]=true,
["res/sound/WTQS/WTQS_born_3.ogg"]=true,
["res/sound/XCJS/XCJS_born_1.ogg"]=true,
["res/sound/XCJS/XCJS_born_2.ogg"]=true,
["res/sound/XCJS/XCJS_born_3.ogg"]=true,
["res/sound/XDMM/XDMM_born_1.ogg"]=true,
["res/sound/XDMM/XDMM_born_2.ogg"]=true,
["res/sound/XDMM/XDMM_born_3.ogg"]=true,
["res/sound/XDZ/XDZ_born_1.ogg"]=true,
["res/sound/XDZ/XDZ_born_2.ogg"]=true,
["res/sound/XDZ/XDZ_born_3.ogg"]=true,
["res/sound/XGJ/XGJ_born_1.ogg"]=true,
["res/sound/XGJ/XGJ_born_2.ogg"]=true,
["res/sound/XGJ/XGJ_born_3.ogg"]=true,
["res/sound/XJL/XJL_born_1.ogg"]=true,
["res/sound/XJL/XJL_born_2.ogg"]=true,
["res/sound/XJL/XJL_born_3.ogg"]=true,
["res/sound/XSNW/XSNW_born_1.ogg"]=true,
["res/sound/XSNW/XSNW_born_2.ogg"]=true,
["res/sound/XSNW/XSNW_born_3.ogg"]=true,
["res/sound/XXJTS/XXJTS_born_1.ogg"]=true,
["res/sound/XXJTS/XXJTS_born_2.ogg"]=true,
["res/sound/XXJTS/XXJTS_born_3.ogg"]=true,
["res/sound/YM/YM_born_1.ogg"]=true,
["res/sound/YM/YM_born_2.ogg"]=true,
["res/sound/YM/YM_born_3.ogg"]=true,
["res/sound/YXZ/YXZ_born_1.ogg"]=true,
["res/sound/YXZ/YXZ_born_2.ogg"]=true,
["res/sound/YXZ/YXZ_born_3.ogg"]=true,
["res/sound/ZZMR/ZZMR_born_1.ogg"]=true,
["res/sound/ZZMR/ZZMR_born_2.ogg"]=true,
["res/sound/ZZMR/ZZMR_born_3.ogg"]=true,
["res/sound/HJSJ/HJSJ_death.ogg"]=true,
["res/sound/DMFS/DMFS_death.ogg"]=true,
["res/sound/YM/YM_death.ogg"]=true,
["res/sound/SFMN/SFMN_death.ogg"]=true,
["res/sound/SDHB/SDHB_death.ogg"]=true,
["res/sound/DXLZ/DXLZ_death.ogg"]=true,
["res/sound/LJSS/LJSS_death.ogg"]=true,
["res/sound/SLJR/SLJR_death.ogg"]=true,
["res/sound/LN/LN_death.ogg"]=true,
["res/sound/DJSS/DJSS_death.ogg"]=true,
["res/sound/DSPG/DSPG_death.ogg"]=true,
["res/sound/CJTS/CJTS_death.ogg"]=true,
["res/sound/JSZZ/JSZZ_death.ogg"]=true,
["res/sound/WTQS/WTQS_death.ogg"]=true,
["res/sound/XGJ/XGJ_death.ogg"]=true,
["res/sound/BSWY/BSWY_death.ogg"]=true,
["res/sound/LXZY/LXZY_death.ogg"]=true,
["res/sound/TKBZ/TKBZ_death.ogg"]=true,
["res/sound/CJZ/CJZ_death.ogg"]=true,
["res/sound/TQBZ/TQBZ_death.ogg"]=true,
["res/sound/STMQ/STMQ_death.ogg"]=true,
["res/sound/DYH/DYH_death.ogg"]=true,
["res/sound/HYZD/HYZD_death.ogg"]=true,
["res/sound/KSYR/KSYR_death.ogg"]=true,
["res/sound/KCHY/KCHY_death.ogg"]=true,
["res/sound/XXJTS/XXJTS_death.ogg"]=true,
["res/sound/BH/BH_death.ogg"]=true,
["res/sound/SH/SH_death.ogg"]=true,
["res/sound/XDMM/XDMM_death.ogg"]=true,
["res/sound/HBNW/HBNW_death.ogg"]=true,
["res/sound/HLLZ/HLLZ_death.ogg"]=true,
["res/sound/XDZ/XDZ_death.ogg"]=true,
["res/sound/EMZS/EMZS_death.ogg"]=true,
["res/sound/KJMW/KJMW_death.ogg"]=true,
["res/sound/XCJS/XCJS_death.ogg"]=true,
["res/sound/TLNW/TLNW_death.ogg"]=true,
["res/sound/AYLR/AYLR_death.ogg"]=true,
["res/sound/XSNW/XSNW_death.ogg"]=true,
["res/sound/TYS/TYS_death.ogg"]=true,
["res/sound/HYS/HYS_death.ogg"]=true,
["res/sound/SYS/SYS_death.ogg"]=true,
["res/sound/FYS/FYS_death.ogg"]=true,
["res/sound/LL/LL_death.ogg"]=true,
["res/sound/DLY/DLY_death.ogg"]=true,
["res/sound/XJL/XJL_death.ogg"]=true,
["res/sound/GSZZ/GSZZ_death.ogg"]=true,
["res/sound/KMJY/KMJY_death.ogg"]=true,
["res/sound/JDZY/JDZY_death.ogg"]=true,
["res/sound/YXZ/YXZ_death.ogg"]=true,
["res/sound/ZZMR/ZZMR_death.ogg"]=true,
["res/ui/icons/yingxiongyuanhua/anyinglangren.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/bushiwuyao.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/chongjizhe.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/dixuelingzhu.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/dushetuteng.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/emozhishou.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/fengyuansu.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/heilonglingzhu.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/huoyuansu.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/jiangshizhizhu.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/juduzhiyuan.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/jumoyuanhua.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/kongjumownang.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/kumujuyi.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/linglong.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/luxingzhanying.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/niutouqiuzhang.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/shefamonv.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/shenlinshouwei.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/shuangdaomobao.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/shuiyuansu.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/taluowunv.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/tiankongbazhu.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/tianqibazhu.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/tuyuansu.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/wutouqishi.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/xiaochoujingshen.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/xiaojingling.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/xieduzhe.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/xuegongjue.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/xunshounvwang.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/yanmo.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/yinxingzhe.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/zhaozhejuren.jpg"]=true,
["res/ui/icons/yingxiongyuanhua/ziranchanrao.jpg"]=true,
}
}

+ 140
- 0
Editor/SceneEditor.lua Näytä tiedosto

@@ -0,0 +1,140 @@
local SceneEditor = class("SceneEditor" , require("NodeEditor"));

function SceneEditor:ctor()
SceneEditor.super.ctor(self);
end

function SceneEditor:activate()
SceneEditor.super.activate(self);
app.setting.OriginAnchor = cc.p(0,0);
app:refreshSetting();
end

function SceneEditor:unactivate()
SceneEditor.super.unactivate(self);
if self.MapEditor ~= nil then
self.MapEditor:close();
end
end

function SceneEditor:play()
if self.node then
self.node:playCurveAnimation();
local cameraSphericlNode = self.node:findNode("SphericalCameraNode")
if cameraSphericlNode then
cameraSphericlNode:setCollectAnimationClip(false)
local function curveAnimationEnd()
-- 编辑器里需要更新
if cameraSphericlNode:isSphericalActive() then
cameraSphericlNode:startUpdate()
end
end
cameraSphericlNode:playCurveAnimation(curveAnimationEnd)
end
-- 递归遍历下面的所有子节点
local function visit(node)
if node.stop then
node:stop();
end
if node.play then
node:play();
end
end
self.node:visitNode(visit);
end
end

function SceneEditor:stop()
if self.node then
self.node:stopCurveAnimation();
local cameraSphericlNode = self.node:findNode("SphericalCameraNode")
if cameraSphericlNode then
cameraSphericlNode:stopCurveAnimation()
-- 编辑器里需要更新
if cameraSphericlNode:isSphericalActive() then
cameraSphericlNode:startUpdate()
end
end
-- 递归遍历下面的所有子节点
local function visit(node)
if node.stop then
node:stop();
end
end
self.node:visitNode(visit);
end
end

-- 创建新的光效
function SceneEditor:newNode()
self:closeNode();
local node = self:createNode("Scene");
node:setName("Root");
self:initNode(node)
-- 创建一个新的地图
self.Map = require("Map"):new();
self.MapEditor = require("MapEditor"):new();
return node;
end

-- 设置地图的宽度和高度
function SceneEditor:initMap(mapWidth, mapHeight, tileWidth, tileHeight)
if self.Map == nil then
error("没有创建地图");
end
-- 初始化地图宽度和高度
self.Map:initWidthAndHeight(mapWidth, mapHeight, tileWidth, tileHeight);
self.Map:initObstacles();
self.MapEditor:init();
end

-- 从文件载入节点
function SceneEditor:loadNode(nodeFile)
local node = SceneEditor.super.loadNode(self, nodeFile);
-- 创建一个题图载入资源
self.Map = require("Map"):new();
local arr = string.split(nodeFile, ".");
self.Map:loadLua(arr[1] .. ".lmap");
self.MapEditor = require("MapEditor"):new();
self.MapEditor:init();

--[[-- 获取相机
local cameraNode = node:findNode("main_camera");
app.mainLayer:setActiveCamera(cameraNode:getCamera());
app.mainCamera = cameraNode:getCamera();
local winSize = cc.Director:getInstance():getWinSize();
app.mainCamera:setAspectRatio(winSize.width / winSize.height);
app.cameraController:refreshSetting();--]]
return node;
end

function SceneEditor:save(filename)
SceneEditor.super.save(self, filename);
local arr = string.split(filename, ".");
-- 保存地图
self.Map:saveLua(arr[1] .. ".lmap");
self.Map:saveXml(arr[1] .. ".map");
end

-- 关闭光效
function SceneEditor:closeNode()
SceneEditor.super.closeNode(self);

end

-- 初始化光效,添加到场景中
function SceneEditor:initNode(node)
SceneEditor.super.initNode(self , node);
end

function SceneEditor:createNode(nodeType)
local node = SceneEditor.super.createNode(self , nodeType);
if node.enableAutoPlay then
node:enableAutoPlay();
end
return node;
end

return SceneEditor;

+ 147
- 0
Editor/UIEditor.lua Näytä tiedosto

@@ -0,0 +1,147 @@
local UIEditor = class("UIEditor" , require("NodeEditor"));

function UIEditor:ctor()
UIEditor.super.ctor(self);
end

function UIEditor:activate()
UIEditor.super.activate(self);
app.setting.OriginAnchor = cc.p(0,0);
app.setting.SourceNodeNum = 0;
app.setting.TargetNodeNum = 0;
app:refreshSetting();

self.mBackgroundNode = self:createUIBackground();
app.mainLayer:addChild(self.mBackgroundNode , -100);
end

function UIEditor:unactivate()
UIEditor.super.unactivate(self);
if self.mBackgroundNode then
self.mBackgroundNode:removeFromParent();
self.mBackgroundNode = nil;
end
end

-- 创建UI底图
-- 创建UI底图
-- 创建UI底图
-- 创建UI底图
-- 创建UI底图
-- 创建UI底图
-- 创建UI底图
-- 创建UI底图
-- 创建UI底图
-- 创建UI底图
-- 创建UI底图
-- 创建UI底图
function UIEditor:createUIBackground()
local glNode = gl.glNodeCreate()
glNode:setAnchorPoint(cc.p(0, 0))
local function primitivesDraw(transform, transformUpdated)
local node = self.node;
if node then
-- 绑定相机、世界矩阵
cc.DrawPrimitives.setCamera(cc.Director:getInstance():getActiveCamera());
cc.DrawPrimitives.setWorldTransform(node:getNodeToWorldTransform());

-- 画矩形
local rect = cc.rect(0 , 0 , node:getContentSize().width , node:getContentSize().height);
cc.DrawPrimitives.drawSolidRect(cc.p(rect.x , rect.y), cc.p(rect.x + rect.width , rect.y + rect.height) , cc.c4f(0.6,0.6,0.6,1))

-- 状态恢复
gl.lineWidth(1)
cc.DrawPrimitives.drawColor4B(255,255,255,255)
cc.DrawPrimitives.setPointSize(1)
end
end

glNode:registerScriptDrawHandler(primitivesDraw)
return glNode;
end

function UIEditor:play()
UIEditor.super.play(self)
-- UIEffectNode需要重新播放下
local function visit(node)
if node.stop then
node:stop()
end
if node.play then
node:play()
end
end
self.node:visitNode(visit);
end

-- 创建新的光效
function UIEditor:newNode()
self:closeNode();
local node = self:createNode("Layout");
self:initNode(node)
node:ignoreContentAdaptWithSize(false);
node:setSizeType(1);
node:setSizePercent(cc.p(1,1));
node:setAnchorPoint(cc.p(0,0));
node:setBackGroundColorType(cc.LayoutBackGroundColorType.none);
return node;
end

-- 关闭光效
function UIEditor:closeNode()
UIEditor.super.closeNode(self);

end

-- 初始化光效,添加到场景中
function UIEditor:initNode(node)
UIEditor.super.initNode(self , node);
-- 默认播放更节点的动画
if app.setting.PlayUIAnimation then
self.node:playCurveAnimation()
end
end

function UIEditor:relayoutAll()
local function onNode(node)
if type(node.requestDoLayout) == "function" then
node:requestDoLayout();
end
return true;
end
-- 遍历所有子节点,把子UI取出来统一放在Items里
if self.node then
self.node:visitNode(onNode);
end
end

-- 属性改变通知
function UIEditor:onPropertyValueChanged(propName , newValue , oldValue)
self:relayoutAll();
end

function UIEditor:createNode(nodeType)
local node = UIEditor.super.createNode(self , nodeType);
if node.enableAutoPlay then
node:enableAutoPlay();
end
return node;
end

-- 各个派生类可以重写这个函数
function UIEditor:save(filename)

self.node:recalcAllPList();
UIEditor.super.save(self, filename);
local images = self.node:collectAllImage();
if images then
local msg = "保存UI" .. filename .. "成功,这个UI用到了这些图片:\r\n";
for i , v in pairs(images) do
msg = msg .. i .. " 用了 " .. v .. " 次\r\n";
end
alert(msg);
end
end

return UIEditor;

+ 172
- 0
Editor/UIPreviewEditor.lua Näytä tiedosto

@@ -0,0 +1,172 @@
local UIPreviewEditor = class("UIPreviewEditor" , require("Editor"));

function UIPreviewEditor:ctor()
UIPreviewEditor.super.ctor(self);
-- 挂接UI的根节点
self.node = nil
end

function UIPreviewEditor:activate()
UIPreviewEditor.super.activate(self);
-- 恢复场景的位置
app.mainScene:setPosition(cc.p(0,0));
-- 恢复下场景的缩放
app.setting.ScreenScale = 1;
app.mainScene:setScale(app.setting.ScreenScale);
app.setting.OriginAnchor = cc.p(0,0);
app.setting.SourceNodeNum = 0;
app.setting.TargetNodeNum = 0;
app:refreshSetting();

self.mBackgroundNode = self:createUIBackground();
app.mainLayer:addChild(self.mBackgroundNode , -100);
end

function UIPreviewEditor:unactivate()
UIPreviewEditor.super.unactivate(self);
self:closeNode()
if self.mBackgroundNode then
self.mBackgroundNode:removeFromParent();
self.mBackgroundNode = nil;
end
end

-- 关闭当前打开的UI
function UIPreviewEditor:closeNode()
if self.node then
self.node:removeFromParent();
self.node = nil;
end
end

-- 从文件载入节点
function UIPreviewEditor:loadNode(nodeFile)
self:closeNode();
self.node = tolua.cast(cc.StreamObject:loadFromFile(nodeFile) , "cc.Node3D");
self:initNode(self.node);
return self.node;
end

-- 创建UI底图
function UIPreviewEditor:createUIBackground()
local glNode = gl.glNodeCreate()
glNode:setAnchorPoint(cc.p(0, 0))
local function primitivesDraw(transform, transformUpdated)
local node = self.node;
if node then
-- 绑定相机、世界矩阵
cc.DrawPrimitives.setCamera(cc.Director:getInstance():getActiveCamera());
cc.DrawPrimitives.setWorldTransform(node:getNodeToWorldTransform());

-- 画矩形
local rect = cc.rect(0 , 0 , node:getContentSize().width , node:getContentSize().height);
cc.DrawPrimitives.drawSolidRect(cc.p(rect.x , rect.y), cc.p(rect.x + rect.width , rect.y + rect.height) , cc.c4f(0.6,0.6,0.6,1))

-- 状态恢复
gl.lineWidth(1)
cc.DrawPrimitives.drawColor4B(255,255,255,255)
cc.DrawPrimitives.setPointSize(1)
end
end

glNode:registerScriptDrawHandler(primitivesDraw)
return glNode;
end

function UIPreviewEditor:play()
UIPreviewEditor.super.play(self)
if self.node then
self.node:playCurveAnimation();
if self.node.stop then
self.node:stop();
end
if self.node.play then
self.node:play();
end
-- UIEffectNode需要重新播放下
local function visit(node)
if node.stop then
node:stop()
end
if node.play then
node:play()
end
end
self.node:visitNode(visit);
end
end

function UIPreviewEditor:stop()
if self.node then
self.node:stopCurveAnimation();
if self.node.stop then
self.node:stop();
end
end
end

-- 创建新的光效
function UIPreviewEditor:newNode()
local node = self:createNode("Layout");
self:initNode(node)
node:ignoreContentAdaptWithSize(false);
node:setSizeType(1);
node:setSizePercent(cc.p(1,1));
node:setAnchorPoint(cc.p(0,0));
node:setBackGroundColorType(cc.LayoutBackGroundColorType.none);
return node;
end

-- 初始化光效,添加到场景中
function UIPreviewEditor:initNode(node)
self.node = node
app.mainLayer:addChild(self.node)
-- 默认播放更节点的动画
if app.setting.PlayUIAnimation then
self.node:playCurveAnimation()
end
end

function UIPreviewEditor:relayoutAll()
local function onNode(node)
if type(node.requestDoLayout) == "function" then
node:requestDoLayout();
end
return true;
end
-- 遍历所有子节点,把子UI取出来统一放在Items里
if self.node then
self.node:visitNode(onNode);
end
end

-- 属性改变通知
function UIPreviewEditor:onPropertyValueChanged(propName , newValue , oldValue)
self:relayoutAll();
end

function UIPreviewEditor:createNode(nodeType)
local node = UIPreviewEditor.super.createNode(self , nodeType);
if node.enableAutoPlay then
node:enableAutoPlay();
end
return node;
end

-- 各个派生类可以重写这个函数
function UIPreviewEditor:save(filename)
self.node:recalcAllPList();
UIPreviewEditor.super.save(self, filename);
local images = self.node:collectAllImage();
if images then
local msg = "保存UI" .. filename .. "成功,这个UI用到了这些图片:\r\n";
for i , v in pairs(images) do
msg = msg .. i .. " 用了 " .. v .. " 次\r\n";
end
alert(msg);
end
end

return UIPreviewEditor;

+ 114
- 0
Editor/UndoRedoManager.lua Näytä tiedosto

@@ -0,0 +1,114 @@

require("Commands")

-- Undo redo管理器
-- 负责编辑器的撤销和恢复操作

local UndoRedoManager = class("UndoRedoManager")

function UndoRedoManager:ctor()
-- redo 列表
self.redoStack = {};
-- undo 列表
self.undoStack = {};
-- 最大的撤销步数
self.maxStack = 100;
end

-- 执行一个操作
function UndoRedoManager:doCommand(command)
if command:redo() then
self:addCommand(command);
else
if type(command.clear) == "function" then
command:clear();
end
end
end

-- 压入一个操作
function UndoRedoManager:addCommand(command)
-- 清空恢复操作列表
self:clearRedo();
-- 如果队列满了则需要踢出最久的那个操作
if #self.undoStack > self.maxStack then
local undoIt = self.undoStack[table.nums(self.undoStack)];
if type(undoIt.clear) == "function" then
undoIt.clear();
end
table.remove(self.undoStack, #self.undoStack);
end
table.insert(self.undoStack, command);
end

-- redo操作
function UndoRedoManager:redo()
if #self.redoStack <= 0 then
return
end
local redoT = self.redoStack[table.nums(self.redoStack)];
redoT:redo();
-- 加入到恢复列表里面去
table.insert(self.undoStack, redoT);
-- 从撤销列表里面去掉这个操作
table.remove(self.redoStack, #self.redoStack);
end

-- undo操作
function UndoRedoManager:undo()
if #self.undoStack <= 0 then
return
end
local undoT = self.undoStack[table.nums(self.undoStack)];
undoT:undo();
-- 加入到撤销列表里面去
table.insert(self.redoStack, undoT);
-- 从恢复列表里面去掉这个操作
table.remove(self.undoStack, #self.undoStack);
end

function UndoRedoManager:canRedo()
return #self.redoStack > 0;
end

function UndoRedoManager:canUndo()
return #self.undoStack > 0;
end

function UndoRedoManager:clearRedo()
-- 清空一些数据
for i, v in pairs(self.redoStack) do
if type(v.clear) == "function" then
v:clear();
end
end
-- 清空恢复列表
self.redoStack = {};
end

function UndoRedoManager:clearUndo()
-- 清空一些数据
for i, v in pairs(self.undoStack) do
if type(v.clear) == "function" then
v:clear();
end
end
-- 清空撤销列表
self.undoStack = {};
end

-- 清空所有的撤销、恢复操作
function UndoRedoManager:clear()
self:clearRedo();
self:clearUndo();
end

return UndoRedoManager

+ 126
- 0
Editor/VisibleRect.lua Näytä tiedosto

@@ -0,0 +1,126 @@
local VisibleRect = class("VisibleRect")

function VisibleRect:ctor()
self.s_visibleRect = cc.rect(0,0,0,0)
end

-- 初始化可见区域
function VisibleRect:lazyInit()
if (self.s_visibleRect.width == 0.0 and self.s_visibleRect.height == 0.0) then
self.s_visibleRect.x = 0
self.s_visibleRect.y = 0
local size = cc.Director:getInstance():getWinSize()
self.s_visibleRect.width = size.width
self.s_visibleRect.height = size.height
end
end

function VisibleRect:updateVisibleRect()
-- 这里只更新大小
local size = cc.Director:getInstance():getWinSize()
self.s_visibleRect.width = size.width
self.s_visibleRect.height = size.height
end

function VisibleRect:getVisibleRect()
self:lazyInit()
return cc.rect(self.s_visibleRect.x, self.s_visibleRect.y, self.s_visibleRect.width, self.s_visibleRect.height)
end

-- 将屏幕坐标转换成GLView坐标
function VisibleRect:convertScreenToGLView(x, y)
self:lazyInit()
return cc.p(x , self:getVisibleRect().height - y)
end

-- 将屏幕坐标转换成坐标系的坐标
function VisibleRect:convertScreenToCoordinate(x, y)
self:lazyInit()
local floorPlane = cc.Plane:new(cc.vec3(0,1,0) , 0);

-- 计算出mainlayer的世界位置
local ray = app.mainCamera:pickRay(x / self.s_visibleRect.width , y / self.s_visibleRect.height);
local distance = ray:intersectsPlane(floorPlane);
if distance >= 0 then
return ray:getPoint(distance);
else
return ray:getPoint(0);
end

end

-- 将屏幕坐标转换成坐标系的坐标
function VisibleRect:convertScreenToCoordinate2D(x, y)
self:lazyInit()
local floorPlane = cc.Plane:new(cc.vec3(0,0,1) , 0);

-- 计算出mainlayer的世界位置
local ray = app.mainCamera:pickRay(x / self.s_visibleRect.width , y / self.s_visibleRect.height);
local distance = ray:intersectsPlane(floorPlane);
if distance >= 0 then
return ray:getPoint(distance);
else
return ray:getPoint(0);
end

end

-- 鼠标位置转换成世界坐标
function VisibleRect:convertScreenToWorldPos(x , y)
local pos = self:convertScreenToCoordinate(x , y);
return app.mainLayer:convertToWorldSpace(pos);
end

-- 鼠标位置转换成世界坐标
function VisibleRect:convertScreenToWorldPos2D(x , y)
local pos = self:convertScreenToCoordinate2D(x , y);
return app.mainLayer:convertToWorldSpace(pos);
end

function VisibleRect:left()
self:lazyInit()
return cc.p(self.s_visibleRect.x, self.s_visibleRect.y+self.s_visibleRect.height/2)
end

function VisibleRect:right()
self:lazyInit()
return cc.p(self.s_visibleRect.x+self.s_visibleRect.width, self.s_visibleRect.y+self.s_visibleRect.height/2)
end

function VisibleRect:top()
self:lazyInit()
return cc.p(self.s_visibleRect.x+self.s_visibleRect.width/2, self.s_visibleRect.y+self.s_visibleRect.height)
end

function VisibleRect:bottom()
self:lazyInit()
return cc.p(self.s_visibleRect.x+self.s_visibleRect.width/2, self.s_visibleRect.y)
end

function VisibleRect:center()
self:lazyInit()
return cc.p(self.s_visibleRect.x+self.s_visibleRect.width/2, self.s_visibleRect.y+self.s_visibleRect.height/2)
end

function VisibleRect:leftTop()
self:lazyInit()
return cc.p(self.s_visibleRect.x, self.s_visibleRect.y+self.s_visibleRect.height)
end

function VisibleRect:rightTop()
self:lazyInit()
return cc.p(self.s_visibleRect.x+self.s_visibleRect.width, self.s_visibleRect.y+self.s_visibleRect.height)
end

function VisibleRect:leftBottom()
self:lazyInit()
return cc.p(self.s_visibleRect.x,self.s_visibleRect.y)
end

function VisibleRect:rightBottom()
self:lazyInit()
return cc.p(self.s_visibleRect.x+self.s_visibleRect.width, self.s_visibleRect.y)
end

return VisibleRect;

BIN
Editor/hero1.png Näytä tiedosto

Before After
Leveys: 149  |  Korkeus: 121  |  Koko: 39 KiB

BIN
Editor/hero2.png Näytä tiedosto

Before After
Leveys: 149  |  Korkeus: 121  |  Koko: 38 KiB

BIN
Editor/iphone5.png Näytä tiedosto

Before After
Leveys: 768  |  Korkeus: 1613  |  Koko: 1.2 MiB

+ 74
- 0
Editor/main.lua Näytä tiedosto

@@ -0,0 +1,74 @@

cc.FileUtils:getInstance():addSearchPath("core")

local writablePath = cc.FileUtils:getInstance():getWritablePath()
local paths = cc.FileUtils:getInstance():getSearchPaths()

--RomSetting 其他平台的对应的配置会在打包的时候覆盖core里面的 然后通过此文件加载对应平台的路径
local RomSetting = require("romFiles.RomSetting")
if #paths<=3 then
table.insert(paths,1,RomSetting.Platform)
-- table.insert(paths,1,writablePath..RomSetting.Platform.."/")
-- table.insert(paths,3,writablePath)
cc.FileUtils:getInstance():setSearchPaths(paths)
end

cc.FileUtils:getInstance():addSearchPath("core/preload")
cc.FileUtils:getInstance():addSearchPath("core/preload/tools")
cc.FileUtils:getInstance():addSearchPath("Editor")
cc.FileUtils:getInstance():addSearchPath("core/luaScript")
cc.FileUtils:getInstance():addSearchPath("core/dataconfig")
cc.FileUtils:getInstance():addSearchPath("core/romFiles")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/cc")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Other")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Nodes")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Widgets")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Tracks")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Effect")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Effect/ParticleSystem")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Effect/ParticleSystem/Affector")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Tools/Effect/ParticleSystem/Emitter")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Protocol")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Config")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Extension")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Map")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Views")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Config/Languages")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Config/ConfigDesc")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/User")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Plugins")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/PluginAdvertise")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Learning")
cc.FileUtils:getInstance():addSearchPath("core/luaScript/Learning/Script")

-- 开启调试器
--require("debugger")("127.0.0.1", 10000, "luaidekey")

-- 编辑器模式
EditorMode = true;
cc.BaseObject:setEditorMode(true);

-- avoid memory leak
collectgarbage("setpause", 100)
collectgarbage("setstepmul", 5000)

-- 调试信息
function __G__TRACKBACK__(msg)
print("----------------------------------------")
print("LUA ERROR: " .. tostring(msg) .. "\n")
print(debug.traceback())
print("----------------------------------------")
local err = "脚本出错,速度截图后找程序麻烦,错误信息:" .. msg .. "\r\n" .. debug.traceback();
CCMessageBox(err , "脚本出错");
end
local function main()
-- 初始化随机种子
math.randomseed(os.time());

require("all")
require("EditorApp"):new():run()
end

xpcall(main, __G__TRACKBACK__)

BIN
Editor/map.png Näytä tiedosto

Before After
Leveys: 563  |  Korkeus: 1000  |  Koko: 895 KiB

+ 59
- 0
Editor/preloadText.bmfc Näytä tiedosto

@@ -0,0 +1,59 @@
# AngelCode Bitmap Font Generator configuration file
fileVersion=1

# font settings
fontName=·½ÕýÀ¼Í¤×¼ºÚ_GBK
fontFile=
charSet=134
fontSize=30
aa=1
scaleH=100
useSmoothing=1
isBold=0
isItalic=0
useUnicode=1
disableBoxChars=1
outputInvalidCharGlyph=0
dontIncludeKerningPairs=0
useHinting=1
renderFromOutline=0
useClearType=1

# character alignment
paddingDown=0
paddingUp=0
paddingRight=0
paddingLeft=0
spacingHoriz=1
spacingVert=1
useFixedHeight=0
forceZero=0

# output file
outWidth=512
outHeight=256
outBitDepth=32
fontDescFormat=0
fourChnlPacked=0
textureFormat=png
textureCompression=0
alphaChnl=0
redChnl=4
greenChnl=4
blueChnl=4
invA=0
invR=0
invG=0
invB=0

# outline
outlineThickness=0

# selected chars
chars=32-126,12290,19979,20013,20102,20214,20449,20505,20687,20837,20986,21040,21151,21247,21387,21407
chars=21487-21488,21495,21518,21542,22240,22312,22833,22909,22987,23433,23436,24050,24320,24369,25103
chars=25104,25991,26032,26159,26356,26368,26412,26512,26597,26657,26816,27491,27605,27979,28216,28304
chars=28385,29256,30424,30913,31245,31957,31967,32476,32593,32622,33021,35013,35299,35831,36133,36164
chars=36733,36827,36864,37197,38169,39564,65281,65292,65306

# imported icon images

BIN
Editor/preloadText.txt Näytä tiedosto


BIN
EditorCS.exe Näytä tiedosto


BIN
EditorEngine.dll Näytä tiedosto


+ 2
- 0
README.md Näytä tiedosto

@@ -0,0 +1,2 @@
# Client_Src


BIN
TimeBeam.dll Näytä tiedosto


+ 8
- 0
_fetch.bat Näytä tiedosto

@@ -0,0 +1,8 @@

git fetch origin
git fetch upstream

git remote prune origin
git remote prune upstream

pause

+ 3
- 0
_rebaseToOriginMaster.bat Näytä tiedosto

@@ -0,0 +1,3 @@
git rebase remotes/origin/master

pause

+ 3
- 0
_rebaseToUpstreamMaster.bat Näytä tiedosto

@@ -0,0 +1,3 @@
git rebase remotes/upstream/master

pause

+ 7
- 0
_updateMaster.bat Näytä tiedosto

@@ -0,0 +1,7 @@
call _fetch.bat

git checkout master
git rebase upstream/master
git push

pause

BIN
_w3h.dll Näytä tiedosto


+ 1
- 0
changeProjcet.bat Näytä tiedosto

@@ -0,0 +1 @@
python changeProject.py

+ 225
- 0
changeProject.py Näytä tiedosto

@@ -0,0 +1,225 @@
# -*- coding: utf-8 -*

import sys
import os, os.path
import time
import zipfile
import difflib
import shutil
import json
import hashlib
import httplib
import urllib
from ctypes import *
from struct import *
import re
import base64
import math
import subprocess
import time

reload(sys)
sys.setdefaultencoding("utf-8")

_srcPath = "storage"

_platforms = {
"1": {"name": u"-欢乐debug", "devMode": "debug","mark":"hl","platform":"huanle"},
"2": {"name": u"-欢乐release", "devMode": "release","mark":"hl","platform":"huanle"},
"3": {"name": u"-川南debug", "devMode": "debug","mark":"cn","platform":"chuannan"},
"4": {"name": u"-川南release", "devMode": "release","mark":"cn","platform":"chuannan"},
"5": {"name": u"-悠闲跑胡子debug", "devMode": "debug","mark":"yx","platform":"youxianmj"},
"6": {"name": u"-悠闲跑胡子release", "devMode": "release","mark":"yx","platform":"youxianmj"},
"7": {"name": u"-悠闲重庆debug", "devMode": "debug","mark":"cq","platform":"chongqing"},
"8": {"name": u"-悠闲重庆release", "devMode": "release","mark":"cq","platform":"chongqing"},
"9": {"name": u"-蜀州麻将debug", "devMode": "debug","mark":"sz","platform":"shuzhou"},
"10": {"name": u"-蜀州麻将release", "devMode": "release","mark":"sz","platform":"shuzhou"},
"11": {"name": u"-天天麻将debug", "devMode": "debug","mark":"tt","platform":"tiantian"},
"12": {"name": u"-天天麻将release", "devMode": "release","mark":"tt","platform":"tiantian"},
}


def runCommand(cmd, isNeedLog = False):
print("[Command] " + cmd)
if cmd == None:
return

if isNeedLog:
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
p.wait()
return p.stdout.readlines()
else:
subprocess.call(cmd, shell=True)

def copyFile(source_path, target_path):
if os.path.exists(source_path):
global g_fileNumAll
g_fileNumAll += 1
open(target_path, "wb").write(open(source_path, "rb").read())


def copyFiles(sourceDir, targetDir):
if not os.path.isdir(sourceDir):
print ("不存在路径:").encode("gbk"), sourceDir
return
# copyFileCounts = 'copyFileCounts' in globals()
# print sourceDir
# print u"%s 当前处理文件夹%s已处理%s 个文件" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), sourceDir,copyFileCounts)
for f in os.listdir(sourceDir):
if f == ".git":
pass
else:
sourceF = os.path.join(sourceDir, f)
targetF = os.path.join(targetDir, f)
if os.path.isfile(sourceF):
if sourceF.find("README") > 0:
continue
# 创建目录
if not os.path.exists(targetDir):
os.makedirs(targetDir)
# copyFileCounts += 1

# 文件不存在,或者存在但是大小不同,覆盖
if not os.path.exists(targetF) or (
os.path.exists(targetF) and (os.path.getsize(targetF) != os.path.getsize(sourceF))):
# 2进制文件
open(targetF, "wb").write(open(sourceF, "rb").read())
global g_fileNumAll
g_fileNumAll += 1
# print u"%s %s 复制完毕" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), targetF)
else:
# print u"%s %s 已存在,不重复复制" % (
# time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), targetF)
pass
if os.path.isdir(sourceF):
copyFiles(sourceF, targetF)


def removeFiles(sourceDir, prefix):
for f in os.listdir(sourceDir):
sourceF = os.path.join(sourceDir, f)
if os.path.isfile(sourceF) and f.endswith(prefix):
os.remove(sourceF)
if os.path.isdir(sourceF):
removeFiles(sourceF, prefix)


def openFile(filename):
with open(filename, 'rb') as f: # , 'r', encoding='UTF-8'
str = f.read()
f.close()
return str


def writeFile(filename, content):
with open(filename, 'wb') as f: # , 'r', encoding='UTF-8'
f.write(content)
f.close()
# 更新RoomSetting.lua文件时面的platform字段和isDevMode字段
def updateRomSetting(platform, mode):
filePath = "romFiles/RomSetting.lua"
fileContent = openFile(filePath)
pattern = re.compile('Platform[\s]=[\s]\"[a-zA-Z]+\"')
fileContent = re.sub(pattern, "Platform = \"{0}\"".format(platform), fileContent)

pattern2 = re.compile('isDevMode[\s]=[\s][a-zA-Z]+')
strDevMode = "false" if (mode == "master" or mode == "release") else "true"
fileContent = re.sub(pattern2, "isDevMode = {0}".format(strDevMode), fileContent)

writeFile(filePath, fileContent)

# 更新RoomSetting.lua文件时面的platform字段和isDevMode字段
def getRomSettingData():
filePath = "romFiles/RomSetting.lua"
fileContent = openFile(filePath)
pattern = re.compile('Platform[\s]=[\s]\"[a-zA-Z]+\"')
platform = re.findall(pattern, fileContent)
#
str_value = str(platform)
str_value = str_value[:-3]
str_value = str_value[14:]
platform = str_value
#print(platform)

pattern2 = re.compile('isDevMode[\s]=[\s][a-zA-Z]+')
devMode = re.findall(pattern2, fileContent)
str_value = str(devMode)
str_value = str_value[:-2]
str_value = str_value[14:]
#print(str_value)

strDevMode = "debug" if (str_value == "true") else "release"

return platform,strDevMode

def yxPrint(str):
print("====================================")
print(str).encode('gbk')
print("====================================")

def main():
# 平台
inputStr = None
inputTargetStr = None

print ""

oriPlatform,devMode = getRomSettingData()

print("==============RomSetting Data:"+str(oriPlatform + devMode+"================="))
print ""

for i in sorted(_platforms):
if (_platforms[i]["platform"] + _platforms[i]["devMode"]) == str(oriPlatform + devMode):
inputStr = i
#print(i)
break

if not inputStr:
print ("读取romsetting失败").encode('gbk')
return


for i in sorted(_platforms):
print i, _platforms[i]["name"]
print ""

while True:
print ""
inputTargetStr = raw_input(unicode('输入要转到目标的平台:', 'utf-8').encode('gbk'))
if _platforms.has_key(inputTargetStr):
break
else:
yxPrint("【温馨提示:】未找到对应平台,请重新输入!")

platformConfig = _platforms[inputStr]

platformTargetConfig = _platforms[inputTargetStr]

_targetDir = _srcPath + platformConfig["mark"] + platformConfig["devMode"]
_secondDir = _srcPath + platformTargetConfig["mark"] + platformTargetConfig["devMode"]

if os.path.isdir(_targetDir) or not os.path.isdir(_srcPath):
yxPrint("【温馨提示:】源缓存"+_srcPath+"不存在或者源缓存重命名后的目标文件夹"+_targetDir + "已经存在")
return
elif not os.path.isdir(_secondDir):
yxPrint("【温馨提示:】原目标缓存存在,但是目标平台文件夹缓存不存在,无法改为"+_srcPath)
return
else:
os.rename(_srcPath,_targetDir)
os.rename(_secondDir,_srcPath)
yxPrint("切换到" + platformTargetConfig["name"] + "成功!! 奥力给!")
# 更新项目配置
updateRomSetting(platformTargetConfig["platform"], platformTargetConfig["devMode"])
yxPrint ("更新项目配置成功!!")

os.system("pause")
# -------------- main --------------

if __name__ == '__main__':
main()

+ 2
- 0
co_mini_games.bat Näytä tiedosto

@@ -0,0 +1,2 @@
cd tools
python git_update_minigames.py

+ 42
- 0
core/luaScript/Config/Configs.lua Näytä tiedosto

@@ -0,0 +1,42 @@
local Config = {}

--开启测试登入模式
Config.isDebugLogion = false

--关闭更新设置
Config.isCloseUpdate = false

-- Rom中固化的设置
Config.RomSetting = loadRomSettingScript()

-- 其他配置
Config.Setting = require("luaScript.Config.Setting")

-- 子游戏配置信息
Config.SubGameConfigs = {}

for _, gameId in pairs(GAME_IDS) do
local filePath = string.format("luaScript/Config/SubGame/GameConfig_%03d", gameId)
if isLuaFuleExist(filePath) then
local strFileName = string.format("luaScript.Config.SubGame.GameConfig_%03d", gameId)
local config = require(strFileName)
Config.SubGameConfigs[gameId] = config
end
end

local DefaultModuleConfig = require("luaScript.Config.DefaultModuleConfig")

--当前项目的配置(没有写默认用core的)
local moduleConfig = nil
if cc.FileUtils:getInstance():isFileExist("luaScript/Config/ModuleConfig.luac") or
cc.FileUtils:getInstance():isFileExist("luaScript/Config/ModuleConfig.lua") then
moduleConfig = require("luaScript.Config.ModuleConfig")
end

for k, v in pairs(moduleConfig or {}) do
DefaultModuleConfig[k] = v
end

Config.ModuleConfig = DefaultModuleConfig;

return Config;

+ 49
- 0
core/luaScript/Config/DefaultModuleConfig.lua Näytä tiedosto

@@ -0,0 +1,49 @@
-- ---------------------
-- 大厅功能模块开关配置
-- 该文件只是默认配置,需要修改其中个别配置,请在平台Config目录下新增ModuleConfig.lua
-- 并按下面格式,返回指定的开关配置即可,无需全部重写
-- ---------------------

local ModuleConfig = {}

-- 是否支持红包券功能
ModuleConfig.IsSupportHongBaoKa = true
-- 是否支持金币场功能
ModuleConfig.IsSupportCoin = true
-- 是否支持合伙人功能
ModuleConfig.IsSupportHeHuoRen = true
-- 是否支持邀请拉新功能
ModuleConfig.IsSupportInviteNewFriend = true
-- 是否支持金币场免费金币功能
ModuleConfig.IsSupportCoinFreeCoin = false
-- 大厅红点管理
ModuleConfig.IsSupportRedPoint = false
-- 是否支持比赛场功能
ModuleConfig.IsSupportMatch = false
-- 是否支持道具商城显示
ModuleConfig.IsSupportPropShop = false
-- 是否支持排位赛功能
ModuleConfig.IsSupportDaLianMeng = false
-- 是否支持网页战绩
ModuleConfig.IsSupportZhanJiUrl = true
-- 是否支持官方活动
ModuleConfig.IsSupportOfficeActivity = true
-- 是否支持地区选择
ModuleConfig.IsSupportAddressSelector = false

ModuleConfig.IsSupportMatchTuoGuan = false
--是否支持悠闲豆
ModuleConfig.IsSupportYouXianBean = false
---------------俱乐部---------------
-- 是否支持俱乐部桌子列表分页功能
ModuleConfig.IsSupportGetClubTableListWithPage = false
--是否支持排名赛
ModuleConfig.IsSupportRankMatch = true
--是否支持合盟
ModuleConfig.IsSupportUnion = false
--是否支持普通场排行榜/上报排名
ModuleConfig.IsSupportNormalRank = false
--是否支持三级合伙人(默认不支持,暂对重庆开启)
ModuleConfig.IsSupportThirdCopartner = false

return ModuleConfig

+ 28
- 0
core/luaScript/Config/MultiWechatConfig.lua Näytä tiedosto

@@ -0,0 +1,28 @@

-- ¶à΢ÐŲÎÊý
local config = {
--[[
{
appId = "wx9e0654fad4ac27c4",
appKey = "e820dfdd8b295e34d9ad79448d2ee2a4",
},
{
appId = "wxbe12c718df257ff0",
appKey = "1c5445ba52c397802194420962c2a30c",
},
{
appId = "wxa8a89f416bc9f968",
appKey = "cc43ae995b7971e4223096e07bc7cd77",
},
{
appId = "wxcc01cfef43acd4ee",
appKey = "976fbe75dc0eae0a7c4f1ebdb07ef54e",
},
{
appId = "wx1dafec29f245318b",
appKey = "8d3baaf38f6ace6d8da32d2cd8ebad8e",
}
--]]
};

return config;

+ 15
- 0
core/luaScript/Config/Setting.lua Näytä tiedosto

@@ -0,0 +1,15 @@

local setting = {
-- 资源版本号
ResourceVersion = "1000";
-- IpServer
IpServer = "http://shibaip.dingdingqipai.com/iplist.php",
-- 官方下载地址
-- app.config.Setting.appDownloadUrl
appDownloadUrl = "http://m.dingdingqipai.com/cnzp.php",

};

return setting;

+ 61
- 0
core/luaScript/Extension/CCExt.lua Näytä tiedosto

@@ -0,0 +1,61 @@

cc.Point = cc.Point or {}
cc.Color4F = cc.Color4F or {}
cc.Color3B = cc.Color3B or {}
cc.Size = cc.Size or {}
cc.Rect = cc.Rect or {}
cc.Margin = cc.Margin or {}

function cc.Point:toString()
return tostring(self.x) .. " " .. tostring(self.y);
end
function cc.Point.fromString(str)
local arr = string.split(str , " ");
return cc.p(arr[1] , arr[2]);
end

function cc.Color4F:toString()
return tostring(self.r) .. " " .. tostring(self.g) .. " " .. tostring(self.b) .. " " .. tostring(self.a);
end
function cc.Color4F.fromString(str)
local arr = string.split(str , " ");
return cc.c4f(arr[1] , arr[2] , arr[3] , arr[4])
end

function cc.Color3B:toString()
return tostring(self.r) .. " " .. tostring(self.g) .. " " .. tostring(self.b);
end
function cc.Color3B.fromString(str)
local arr = string.split(str , " ");
return cc.c3b(arr[1] , arr[2] , arr[3])
end

function cc.Size:toString()
return tostring(self.width) .. " " .. tostring(self.height);
end
function cc.Size.fromString(str)
local arr = string.split(str , " ");
return cc.size(arr[1] , arr[2]);
end

function cc.Rect:toString()
return tostring(self.x) .. " " .. tostring(self.y) .. " " ..tostring(self.width) .. " " .. tostring(self.height);
end
function cc.Rect.fromString(str)
local arr = string.split(str , " ");
return cc.rect(arr[1] , arr[2] , arr[3] , arr[4]);
end

function cc.margin(l,t,r,b)
return {left = l;top = t;right = r;bottom = b};
end

function cc.Margin:toString()
return tostring(self.left) .. " " .. tostring(self.top) .. " " .. tostring(self.right) .. " " .. tostring(self.bottom);
end
function cc.Margin.fromString(str)
local arr = string.split(str , " ");
return cc.margin(arr[1] , arr[2] , arr[3] , arr[4]);
end

require("luaScript.Tools.ObjectBinder")

+ 70
- 0
core/luaScript/Extension/IoExt.lua Näytä tiedosto

@@ -0,0 +1,70 @@
-- 扩展io一些功能

function io.exists(path)
local file = io.open(path, "r")
if file then
io.close(file)
return true
end
return false
end

function io.readfile(path)
local file = io.open(path, "r")
if file then
local content = file:read("*a")
io.close(file)
return content
end
return nil
end

function io.writefile(path, content, mode)
mode = mode or "w+b"
local file = io.open(path, mode)
if file then
if file:write(content) == nil then return false end
io.close(file)
return true
else
return false
end
end

function io.pathinfo(path)
local pos = string.len(path)
local extpos = pos + 1
while pos > 0 do
local b = string.byte(path, pos)
if b == 46 then -- 46 = char "."
extpos = pos
elseif b == 47 then -- 47 = char "/"
break
end
pos = pos - 1
end

local dirname = string.sub(path, 1, pos)
local filename = string.sub(path, pos + 1)
extpos = extpos - pos
local basename = string.sub(filename, 1, extpos - 1)
local extname = string.sub(filename, extpos)
return {
dirname = dirname,
filename = filename,
basename = basename,
extname = extname
}
end

function io.filesize(path)
local size = false
local file = io.open(path, "r")
if file then
local current = file:seek()
size = file:seek("end")
file:seek("set", current)
io.close(file)
end
return size
end

+ 64
- 0
core/luaScript/Extension/MathExt.lua Näytä tiedosto

@@ -0,0 +1,64 @@
Math = math

Math.E = 2.718281828459045 -- 自然数
Math.LN2 = 0.6931471805599453 -- 2的自然对数
Math.LN10 = 2.302585092994046 -- 10的自然对数
Math.LOG2E = 1.4426950408889634 -- log 2 为底的自然数
Math.LOG10E = 0.4342944819032518 -- log 10 为底的自然数
Math.PI = 3.141592653589793 -- π
Math.HALF_PI = 1.57079632679489661923 -- 1/2 π
Math.SQRT1_2 = 0.7071067811865476 -- 1/2的平方根
Math.SQRT2 = 1.4142135623730951 -- 2的平方根
-- p, q is on the same of line 1
function Math.isSame(line1, p, q)
local dx = line1.endPoint.x - line1.startPoint.x;
local dy = line1.endPoint.y - line1.startPoint.y;
local dx1 = p.x - line1.startPoint.x;
local dy1 = p.y - line1.startPoint.y;
local dx2 = q.x - line1.endPoint.x;
local dy2 = q.y - line1.endPoint.y;
return (dx*dy1-dy*dx1)*(dx*dy2-dy*dx2) > 0;
end

-- 2 line segments (s1, s2) are intersect?
function Math.isIntersect(line1, line2)
local b1 = Math.isSame(line1, line2.startPoint, line2.endPoint);
local b2 = Math.isSame(line2, line1.startPoint, line1.endPoint);
return not b1 and not b2;
end

function Math.round(num)
return math.floor(num + 0.5)
end

function Math.angle2Radian(angle)
return angle*math.pi/180
end

function Math.radian2Angle(radian)
return radian/math.pi*180
end

-- 从球面坐标系(半径,经度,纬度)转换到笛卡尔坐标系(XYZ)
-- 半径,离原点的距离,一般是一个正数
-- 经度,0~2PI,0代表正前方,PI代表正后方
-- 纬度,HALF_PI代表水平位置,+PI代表底,0代表顶
function Math.SphericalToCartesian(sphericalPos)
return {
x = sphericalPos.x * math.cos(sphericalPos.y) * math.sin(sphericalPos.z);
z = sphericalPos.x * math.sin(sphericalPos.y) * math.sin(sphericalPos.z);
y = sphericalPos.x * math.cos(sphericalPos.z);
}
end

-- 从笛卡尔坐标系(XYZ)转换到球面坐标系(半径,经度,纬度)
function Math.CartesianToSpherical(cartesianPos)
local r = math.sqrt(cartesianPos.x * cartesianPos.x + cartesianPos.y * cartesianPos.y + cartesianPos.z * cartesianPos.z)
local lon = math.atan2(cartesianPos.z, cartesianPos.x)
local lat = math.acos(cartesianPos.y / r)
return cc.vec3(r, lon, lat)
end

+ 144
- 0
core/luaScript/Extension/StringExt.lua Näytä tiedosto

@@ -0,0 +1,144 @@
-- 扩展string的一些功能

function string.htmlspecialchars(input)
for k, v in pairs(string._htmlspecialchars_set) do
input = string.gsub(input, k, v)
end
return input
end

string._htmlspecialchars_set = {}
string._htmlspecialchars_set["&"] = "&amp;"
string._htmlspecialchars_set["\""] = "&quot;"
string._htmlspecialchars_set["'"] = "&#039;"
string._htmlspecialchars_set["<"] = "&lt;"
string._htmlspecialchars_set[">"] = "&gt;"

function string.htmlspecialcharsDecode(input)
for k, v in pairs(string._htmlspecialchars_set) do
input = string.gsub(input, v, k)
end
return input
end

function string.nl2br(input)
return string.gsub(input, "\n", "<br />")
end

function string.text2html(input)
input = string.gsub(input, "\t", " ")
input = string.htmlspecialchars(input)
input = string.gsub(input, " ", "&nbsp;")
input = string.nl2br(input)
return input
end

function string.split(str, delimiter)
str = tostring(str)
delimiter = tostring(delimiter)
if (delimiter=='') then return false end
local pos,arr = 0, {}
-- for each divider found
for st,sp in function() return string.find(str, delimiter, pos, true) end do
table.insert(arr, string.sub(str, pos, st - 1))
pos = sp + 1
end
table.insert(arr, string.sub(str, pos))
return arr
end

function string.ltrim(str)
return string.gsub(str, "^[ \t\n\r]+", "")
end

function string.rtrim(str)
return string.gsub(str, "[ \t\n\r]+$", "")
end

function string.trim(str)
str = string.gsub(str, "^[ \t\n\r]+", "")
return string.gsub(str, "[ \t\n\r]+$", "")
end

function string.ucfirst(str)
return string.upper(string.sub(str, 1, 1)) .. string.sub(str, 2)
end

local function urlencodeChar(char)
return "%" .. string.format("%02X", string.byte(char))
end

function string.urlencode(str)
-- convert line endings
str = string.gsub(tostring(str), "\n", "\r\n")
-- escape all characters but alphanumeric, '.' and '-'
str = string.gsub(str, "([^%w%.%- ])", urlencodeChar)
-- convert spaces to "+" symbols
return string.gsub(str, " ", "+")
end

function string.urldecode(str)
str = string.gsub (str, "+", " ")
str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonum(h,16)) end)
str = string.gsub (str, "\r\n", "\n")
return str
end

function string.utf8len(str)
local len = #str
local left = len
local cnt = 0
local arr = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}
while left ~= 0 do
local tmp = string.byte(str, -left)
local i = #arr
while arr[i] do
if tmp >= arr[i] then
left = left - i
break
end
i = i - 1
end
cnt = cnt + 1
end
return cnt
end

function string.formatNumberThousands(num)
local formatted = tostring(tonum(num))
local k
while true do
formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
if k == 0 then break end
end
return formatted
end

-- 把文件名分割成目录名和文件名
-- 返回pathName , baseName , ext
function string.splitFilename(filename)
local reverseFile = string.reverse(filename);
local pos = string.find(reverseFile , "[/\\]");
local dotPos = string.find(reverseFile , "%.");
return string.sub(filename , 1 , #filename - pos) , string.sub(filename , #filename - pos + 2) , string.sub(filename , #filename - dotPos + 2);
end

-- 是否是某字符串结束
function string.endsWith(filename , ends)
return string.sub(filename , - #ends) == ends;
end

-- 是否是以字符串开头
function string.startsWith(filename , starts)
return string.sub(filename , 1 , #starts) == starts;
end

-- 转换到lua源码格式的字符串
function string.toLuaString(str)
local buffer = {"\""};
for i = 1 , string.len(str) do
table.insert(buffer , [[\]] .. string.byte(str , i));
end
table.insert(buffer , "\"");
return table.concat(buffer);
end;

+ 354
- 0
core/luaScript/Extension/TableExt.lua Näytä tiedosto

@@ -0,0 +1,354 @@
-- 这里是扩充table的一些功能

function table.nums(t)
local count = 0
for k, v in pairs(t) do
count = count + 1
end
return count
end

function table.empty(t)
for k, v in pairs(t) do
return false;
end
return true;
end

function table.keys(t)
local keys = {}
for k, v in pairs(t) do
keys[#keys + 1] = k
end
return keys
end

function table.values(t)
local values = {}
for k, v in pairs(t) do
values[#values + 1] = v
end
return values
end

function table.merge(dest, src)
for k, v in pairs(src) do
dest[k] = v
end
end

function table.mergeAll(src , dest)
for k, v in pairs(src) do
if type(v) == "table" then
if not dest[k] then
dest[k] = v;
else
table.mergeAll(v , dest[k]);
end
else
dest[k] = v
end
end
end

function table.imerge(dest, src)
for k, v in ipairs(src) do
table.insert(dest , v)
end
end

--[[--

insert list.

**Usage:**

local dest = {1, 2, 3}
local src = {4, 5, 6}
table.insertTo(dest, src)
-- dest = {1, 2, 3, 4, 5, 6}
dest = {1, 2, 3}
table.insertTo(dest, src, 5)
-- dest = {1, 2, 3, nil, 4, 5, 6}


@param table dest
@param table src
@param table begin insert position for dest
]]
function table.insertTo(dest, src, begin)
begin = tonumber(begin)
if begin == nil then
begin = #dest + 1
end

local len = #src
for i = 0, len - 1 do
dest[i + begin] = src[i + 1]
end
end

--[[
search target index at list.

@param table list
@param * target
@param int from idx, default 1
@param bool useNaxN, the len use table.maxn(true) or #(false) default:false
@param return index of target at list, if not return -1
]]
function table.indexOf(list, target, from, useMaxN)
local len = (useMaxN and #list) or table.maxn(list)
if from == nil then
from = 1
end
for i = from, len do
if list[i] == target then
return i
end
end
return -1
end

function table.indexOfKey(list, key, value, from, useMaxN)
local len = (useMaxN and #list) or table.maxn(list)
if from == nil then
from = 1
end
local item = nil
for i = from, len do
item = list[i]
if item ~= nil and item[key] == value then
return i
end
end
return -1
end

function table.removeItem(t, item, removeAll)
for i = #t, 1, -1 do
if t[i] == item then
table.remove(t, i)
if not removeAll then break end
end
end
end

function table.map(t, fun)
for k,v in pairs(t) do
t[k] = fun(v, k)
end
end

function table.walk(t, fun)
for k,v in pairs(t) do
fun(v, k)
end
end

function table.filter(t, fun)
for k,v in pairs(t) do
if not fun(v, k) then
t[k] = nil
end
end
end

function table.find(t, item)
return table.keyOfItem(t, item) ~= nil
end

function table.unique(t)
local r = {}
local n = {}
for i = #t, 1, -1 do
local v = t[i]
if not r[v] then
r[v] = true
n[#n + 1] = v
end
end
return n
end

function table.keyOfItem(t, item)
for k,v in pairs(t) do
if v == item then return k end
end
return nil
end

function table.valueOfItem(t, item)
for k,v in pairs(t) do
if v == item then return v end
end
return nil
end

-- 把表转换成类似这种格式的字符串{a='b';};,字符串用二进制格式表示"\01\02"之类
function table.toString(t)
local tableString = vardump(t , "");
return tableString:sub(8);
end


-- 把表转换成类似这种格式的字符串{a='b';};,字符串用可见文本形式表示
function table.tostring(t)
if not t then
return "nil"
end
local oldFunc = string.toLuaString;
string.toLuaString = tostring;
local tableString = vardump(t , "");
string.toLuaString = oldFunc
return tableString:sub(8);
end

-- 把表转换成类似这种格式的字符串return {a='b';};
function table.saveString(t)
return "return " .. table.toString(t);
end

-- 从字符串中载入一个表
function table.loadString(tableString)
local data , err = loadstring(tableString);
if data == nil then
print("table.loadString()", tostring(tableString))
--error(err);
uploadLogs(GAME_ERROR_TYPE.TABLELOADSTRING)
return nil
else
return data();
end
end

-- 将一个table数据保存到本地文件
function table.saveToLocFile(t, filename)
if not t or not filename then
return
end
local tableString = table.saveString(t)
saveStringToFile(tableString, filename)
end

-- 从本地文件读取一个table数据
function table.loadFromLocFile(filename)
if not filename then
return
end
local tableString = loadStringFromFile(filename)
if not tableString then
return nil
end
return table.loadString(tableString)
end

-- 把表保存到文件中
function table.saveFile(t , filename)
local file , err = io.open(filename , "w");
if file == nil then
error(err);
return;
end
file:write("return ")
file:write(table.toString(t));
file:close();
end

if EditorMode then
-- 从文件中载入一个表
function table.loadFile(filename)
local n,r = loadLuaFile(filename);
if n == nil then
--error("载入文件" .. tostring(filename) .. "时出错" .. r);
return nil
end
return n();
end
else
-- 从文件中载入一个表
local tableCache = {};
function table.loadFile(filename)
local cache = tableCache[filename];
if cache then
return cache;
end
print("table.loadFile:" .. filename);
TimeSpan:enterSpan("table.loadFile:" .. filename);
local n,r = loadLuaFile(filename);
if n == nil then
--error("载入文件" .. tostring(filename) .. "时出错" .. r);
return nil
end
TimeSpan:enterSpan("runTable");
cache = n();
TimeSpan:leaveSpan();
tableCache[filename] = cache;
TimeSpan:leaveSpan();
return cache;
end
end



-- 兼容版本
if not table.getn then
function table.getn(t)
return #t;
end
end

local rawpairs = pairs
-------------------------------------------
-- 可以按指定顺序遍历的map迭代器
-- @param tbl 要迭代的表
-- @param func 比较函数
-- @example
-- for k,v in pairs(tbl,defaultComp) do print(k,v) end
function table.sortPairs(tbl, func)
if func == nil then
return rawpairs(tbl)
end

-- 为tbl创建一个对key排序的数组
-- 自己实现插入排序,table.sort遇到nil时会失效
local ary = {}
for key in rawpairs(tbl) do
ary[#ary+1] = key
end

table.sort(ary,func);

-- 定义并返回迭代器
local i = 0
local iter = function ()
i = i + 1
if ary[i] == nil then
return nil
else
return ary[i], tbl[ary[i]]
end
end
return iter
end

--------------------------------
-- 通用比较器(Comparator)
-- @return 对比结果
function table.defaultSort( op1, op2 )
local type1, type2 = type(op1), type(op2)
local num1, num2 = tonumber(op1), tonumber(op2)

if ( num1 ~= nil) and (num2 ~= nil) then
return num1 < num2
elseif type1 ~= type2 then
return type1 < type2
elseif type1 == "string" then
return op1 < op2
elseif type1 == "boolean" then
return op1
-- 以上处理: number, string, boolean
else -- 处理剩下的: function, table, thread, userdata
return tostring(op1) < tostring(op2) -- tostring后比较字符串
end
end

+ 53
- 0
core/luaScript/GameChatDefine.lua Näytä tiedosto

@@ -0,0 +1,53 @@
-- 所有聊天相关的配置
local ChatDef = {}

-- 聊天类型
-- //类型 1: 表情 2: 语音 3:聊天
ChatDef.MessageType =
{
Face = 1, -- 表情
Voice = 2, -- 录音
Message = 3, -- 快捷语
Prop = 4, -- 道具
Chat = 5, -- 聊天 服务器类型还是3
}

ChatDef.TimeInterval =
{
[ChatDef.MessageType.Face] = 3, -- 表情
[ChatDef.MessageType.Voice] = 5, -- 录音
[ChatDef.MessageType.Message] = 5, -- 快捷语
[ChatDef.MessageType.Prop] = 10, -- 道具
[ChatDef.MessageType.Chat] = 3, -- 聊天
}

-- 录音动画/快捷语的方向
ChatDef.Direction =
{
Left = 1, -- 头像在左,动画在右
Right = 2, -- 头像在右,动画在左
}

-- 表情相关的文件
ChatDef.FaceBtnFile = "res/ui/zy_tongyong/zy_face/Face.plist"
ChatDef.FaceConfigs =
{
[1] = {oggLocal="res/sound/%s/common_%s_emoj_1.ogg",oggStandard="res/sound/%s/common_%s_emoj_1.ogg", btnPng = "face_j_1001.png", aniFile = "res/ui/zy_tongyong/zy_face/face1_anims_i6p.plist", aniString = "face1_%d.png", frameNum = 10},
[2] = {oggLocal="res/sound/%s/common_%s_emoj_2.ogg",oggStandard="res/sound/%s/common_%s_emoj_2.ogg", btnPng = "face_j_1002.png", aniFile = "res/ui/zy_tongyong/zy_face/face2_anims_i6p.plist", aniString = "face2_%d.png", frameNum = 10},
[3] = {oggLocal="res/sound/%s/common_%s_emoj_3.ogg",oggStandard="res/sound/%s/common_%s_emoj_3.ogg", btnPng = "face_j_1003.png", aniFile = "res/ui/zy_tongyong/zy_face/face3_anims_i6p.plist", aniString = "face3_%d.png", frameNum = 10},
[4] = {oggLocal="res/sound/%s/common_%s_emoj_4.ogg",oggStandard="res/sound/%s/common_%s_emoj_4.ogg", btnPng = "face_j_1004.png", aniFile = "res/ui/zy_tongyong/zy_face/face4_anims_i6p.plist", aniString = "face4_%d.png", frameNum = 10},
[5] = {oggLocal="res/sound/%s/common_%s_emoj_5.ogg",oggStandard="res/sound/%s/common_%s_emoj_5.ogg", btnPng = "face_j_1005.png", aniFile = "res/ui/zy_tongyong/zy_face/face5_anims_i6p.plist", aniString = "face5_%d.png", frameNum = 10},
[6] = {oggLocal="res/sound/%s/common_%s_emoj_6.ogg",oggStandard="res/sound/%s/common_%s_emoj_6.ogg", btnPng = "face_j_1006.png", aniFile = "res/ui/zy_tongyong/zy_face/face6_anims_i6p.plist", aniString = "face6_%d.png", frameNum = 10},
[7] = {oggLocal="res/sound/%s/common_%s_emoj_7.ogg",oggStandard="res/sound/%s/common_%s_emoj_7.ogg", btnPng = "face_j_1007.png", aniFile = "res/ui/zy_tongyong/zy_face/face7_anims_i6p.plist", aniString = "face7_%d.png", frameNum = 10},
[8] = {oggLocal="res/sound/%s/common_%s_emoj_8.ogg",oggStandard="res/sound/%s/common_%s_emoj_8.ogg", btnPng = "face_j_1008.png", aniFile = "res/ui/zy_tongyong/zy_face/face8_anims_i6p.plist", aniString = "face8_%d.png", frameNum = 10},
[9] = {oggLocal="res/sound/%s/common_%s_emoj_9.ogg",oggStandard="res/sound/%s/common_%s_emoj_9.ogg", btnPng = "face_j_1009.png", aniFile = "res/ui/zy_tongyong/zy_face/face9_anims_i6p.plist", aniString = "face9_%d.png", frameNum = 10},
[10] = {oggLocal="res/sound/%s/common_%s_emoj_10.ogg",oggStandard="res/sound/%s/common_%s_emoj_10.ogg", btnPng = "face_j_1010.png", aniFile = "res/ui/zy_tongyong/zy_face/face10_anims_i6p.plist", aniString = "face10_%d.png", frameNum = 10},
[11] = {oggLocal="res/sound/%s/common_%s_emoj_11.ogg",oggStandard="res/sound/%s/common_%s_emoj_11.ogg", btnPng = "face_j_1011.png", aniFile = "res/ui/zy_tongyong/zy_face/face11_anims_i6p.plist", aniString = "face11_%d.png", frameNum = 10},
[12] = {oggLocal="res/sound/%s/common_%s_emoj_12.ogg",oggStandard="res/sound/%s/common_%s_emoj_12.ogg", btnPng = "face_j_1012.png", aniFile = "res/ui/zy_tongyong/zy_face/face12_anims_i6p.plist", aniString = "face12_%d.png", frameNum = 10},
}

return ChatDef





+ 1368
- 0
core/luaScript/GameGlobalFunction.lua
File diff suppressed because it is too large
Näytä tiedosto


+ 214
- 0
core/luaScript/GameGlobalSound.lua Näytä tiedosto

@@ -0,0 +1,214 @@
-- 游戏逻辑相关的全局函数

local BGMusicPlayer = require("luaScript.Tools.MusicPlayer")();

--背景音乐的通用接口
function playBGMusic(key, musicFileName)
playConfig =
{
-- 唯一的名字,如果正在播的是这个名字,就忽略
Name = key;
-- 需要播放的声音列表,会从中随机一首
Files = {musicFileName};
-- 播放几率,[0-100]
Rate = 100;
-- 每批的间隔
IntervalMin = 0;
IntervalMax = 0;
-- 一批播放多少次
PlayCountMin = 1;
PlayCountMax = 1;
-- 循环多少批,0表示无限循环
LoopCount = 0;
-- 延迟几秒才开始播放
DelayTime = 0;
-- 声音停止时的淡出时间(秒)
FadeOut = 0;
}
BGMusicPlayer.playBGMusic(playConfig);
end

function stopBGMusic()
return BGMusicPlayer.stopBGMusic();
end

--音效的通用接口
function playVoice(voiceFileName)
local soundVolume = app.systemSetting.info.soundVolume
local sound = cc.AudioController:getInstance():playSound(voiceFileName, false);
if sound then
sound:setGain(soundVolume)
end
return sound
end

function stopVoice(sound)
if sound then
cc.AudioController:getInstance():stopSound(sound)
end
end


-------------------- MUSIC ---------------------------

function playMusicLogin()
playBGMusic("BG_Login", "res/sound/bg_login.ogg")
end

function playMusicHall()
playBGMusic("BG_Hall", "res/sound/bg_hall.ogg")
end

function playMusicRoom(index)
if index == 0 then
playBGMusic("BG_Room", "res/sound/room/bgmusic.ogg")
else
playBGMusic("BG_Room", "res/sound/room/bgm.ogg")
end
end


-------------------- SOUND ---------------------------

-- 播放发牌的音效
function playVoiceGiveCard()
playVoice("res/sound/g_flop.ogg")
end

--播放行为操作音效
function playVoiceNiuX(NiuX,nUserId)
if not NiuX then
return
end
local memberInfo = app.room.roomInfo.memberList[nUserId]
if memberInfo then
local userInfo = json.decode(memberInfo.userInfo)
if not userInfo then
return
end
--男1女2,默认是男生
local sexNum = userInfo.sex or 1
--因为女生用的资源是0
if tonumber(sexNum) == 2 then
sexNum = 0
end
local sex = tostring(sexNum)
local voiceName = ""
if tonumber(sexNum) == 1 then
voiceName = string.format("res/sound/room/gg_ogg/f0_nn%d.ogg", NiuX)
else
--女生或者人妖(可能性别保密)进这里播放
voiceName = string.format("res/sound/room/mm_ogg/f1_nn%d.ogg", NiuX)
end
playVoice(voiceName)
end
end

--播放不抢庄操作音效
function playVoiceBuQiang(nUserId)
local memberInfo = app.room.roomInfo.memberList[nUserId]
if memberInfo then
local userInfo = json.decode(memberInfo.userInfo)
if not userInfo then
return
end
--男1女2,默认是男生
local sexNum = userInfo.sex or 1
--因为女生用的资源是0
if tonumber(sexNum) == 2 then
sexNum = 0
end
local sex = tostring(sexNum)
local voiceName = ""
if tonumber(sexNum) == 1 then
voiceName = "res/sound/room/buqiang_0.ogg"
else
--女生或者其他
voiceName = "res/sound/room/buqiang_1.ogg"
end
playVoice(voiceName)
end
end

--播放抢庄操作音效
function playVoiceQiang(nUserId)
local memberInfo = app.room.roomInfo.memberList[nUserId]
if memberInfo then
local userInfo = json.decode(memberInfo.userInfo)
if not userInfo then
return
end
--男1女2,默认是男生
local sexNum = userInfo.sex or 1
--因为女生用的资源是0
if tonumber(sexNum) == 2 then
sexNum = 0
end
local sex = tostring(sexNum)
local voiceName = ""
if tonumber(sexNum) == 1 then
voiceName = "res/sound/room/qiangzhuang_0.ogg"
else
--女生或者其他
voiceName = "res/sound/room/qiangzhuang_1.ogg"
end
playVoice(voiceName)
end
end

--播放按钮点击音效
function playBtnEffect()
playVoice("res/sound/click.ogg")
end

--播放按钮关闭音效
function playBtnCloseEffect()
playVoice("res/sound/effect_return.ogg")
end

--播放标签页点击音效
function playBtnTagEffect()
playVoice("res/sound/effect_biaoqian.ogg")
end

--播放金币飞
function playOneCoinEffect()
playVoice("res/sound/room/coin_big.ogg")
end

--播放下注
function playCoinsEffect()
playVoice("res/sound/room/chips_to_table.ogg")
end

--播放下注
function playCoinsFlyEffect()
playVoice("res/sound/room/coins_fly.ogg")
end

--播放抢庄家音效
function playVoiceRootBanker()
playVoice("res/sound/room/random_banker_lianxu.ogg")
end

--播放成功失败音效
function playEndVoice(cardFileName)
local voiceName = string.format("res/sound/room/%s.ogg", cardFileName)
playVoice(voiceName)
end

--播放闹钟
function playClockVoice()
local voiceName = "res/sound/time_over.ogg"
playVoice(voiceName)
end

+ 421
- 0
core/luaScript/GameTypeDef.lua Näytä tiedosto

@@ -0,0 +1,421 @@
-- 全局的游戏数据类型定义
-- UI显示顺序的Order

UIZOrder =
{
-- showTooltip
TipsOrder = 20000,
-- 重启或退出对话框
ExitOrder = 15000,
-- 最上面是网络等待蒙版
NetWaitOrder = 10000,
-- 系统通知
SystemNotify = 7000,
-- 横幅
DropNotify = 6000,
-- 每日签到
SignOrder = 5500,
-- 其次是新手引导蒙版
GuideOrder = 5000,
-- 再下面是通用界面淡入淡出蒙版
FadeOrder= 2000,
-- 充值界面
Recharge = 1000,
-- 主界面
MainLayer = -1,
}

-- 表情相关的文件
Face_Btn_File = "res/ui/zy_tongyong/zy_face/Face.plist"
Face_Def =
{
[1] = { btnPng = "face_j_1001.png", aniFile = "res/ui/zy_tongyong/zy_face/face1_anims_i6p.plist", aniString = "face1_%d.png", frameNum = 10},
[2] = { btnPng = "face_j_1002.png", aniFile = "res/ui/zy_tongyong/zy_face/face2_anims_i6p.plist", aniString = "face2_%d.png", frameNum = 10},
[3] = { btnPng = "face_j_1003.png", aniFile = "res/ui/zy_tongyong/zy_face/face3_anims_i6p.plist", aniString = "face3_%d.png", frameNum = 10},
[4] = { btnPng = "face_j_1004.png", aniFile = "res/ui/zy_tongyong/zy_face/face4_anims_i6p.plist", aniString = "face4_%d.png", frameNum = 10},
[5] = { btnPng = "face_j_1005.png", aniFile = "res/ui/zy_tongyong/zy_face/face5_anims_i6p.plist", aniString = "face5_%d.png", frameNum = 10},
[6] = { btnPng = "face_j_1006.png", aniFile = "res/ui/zy_tongyong/zy_face/face6_anims_i6p.plist", aniString = "face6_%d.png", frameNum = 10},
[7] = { btnPng = "face_j_1007.png", aniFile = "res/ui/zy_tongyong/zy_face/face7_anims_i6p.plist", aniString = "face7_%d.png", frameNum = 10},
[8] = { btnPng = "face_j_1008.png", aniFile = "res/ui/zy_tongyong/zy_face/face8_anims_i6p.plist", aniString = "face8_%d.png", frameNum = 10},
[9] = { btnPng = "face_j_1009.png", aniFile = "res/ui/zy_tongyong/zy_face/face9_anims_i6p.plist", aniString = "face9_%d.png", frameNum = 10},
[10] = { btnPng = "face_j_1010.png", aniFile = "res/ui/zy_tongyong/zy_face/face10_anims_i6p.plist", aniString = "face10_%d.png", frameNum = 10},
[11] = { btnPng = "face_j_1011.png", aniFile = "res/ui/zy_tongyong/zy_face/face11_anims_i6p.plist", aniString = "face11_%d.png", frameNum = 10},
[12] = { btnPng = "face_j_1012.png", aniFile = "res/ui/zy_tongyong/zy_face/face12_anims_i6p.plist", aniString = "face12_%d.png", frameNum = 10},
}

-- 游戏道具
Prop_Btn_File = "res/ui/zy_tongyong/zy_prop/zy_prop.plist"
GameProp =
{
[1] = {icon = "userInfo_prop1.png", image = "res/ui/zy_tongyong/zy_prop/item1/item1_fly-i6p.png", plistFile = "res/ui/zy_tongyong/zy_prop/item1/item1_anims_i6p.plist", frameName = "item1_%d.png", frameNum = 19},
[2] = {icon = "userInfo_prop2.png", image = "res/ui/zy_tongyong/zy_prop/item2/item2_fly-i6p.png", plistFile = "res/ui/zy_tongyong/zy_prop/item2/item2_anims_i6p.plist", frameName = "item2_%d.png", frameNum = 28},
[3] = {icon = "userInfo_prop3.png", image = "res/ui/zy_tongyong/zy_prop/item3/item3_fly-i6p.png", plistFile = "res/ui/zy_tongyong/zy_prop/item3/item3_anims_i6p.plist", frameName = "item3_%d.png", frameNum = 21},
[4] = {icon = "userInfo_prop4.png", image = "res/ui/zy_tongyong/zy_prop/item4/item4_fly-i6p.png", plistFile = "res/ui/zy_tongyong/zy_prop/item4/item4_anims_i6p.plist", frameName = "item4_%d.png", frameNum = 29},
[5] = {icon = "userInfo_prop5.png", image = "res/ui/zy_tongyong/zy_prop/item5/item5_fly-i6p.png", plistFile = "res/ui/zy_tongyong/zy_prop/item5/item5_anims_i6p.plist", frameName = "item5_%d.png", frameNum = 19},
[6] = {icon = "userInfo_prop6.png", image = "res/ui/zy_tongyong/zy_prop/item6/item6_fly-i6p.png", plistFile = "res/ui/zy_tongyong/zy_prop/item6/item6_anims_i6p.plist", frameName = "item6_%d.png", frameNum = 28},
[7] = {icon = "userInfo_prop7.png", image = "res/ui/zy_tongyong/zy_prop/item7/item7_fly-i6p.png", plistFile = "res/ui/zy_tongyong/zy_prop/item7/item7_anims_i6p.plist", frameName = "item7_%d.png", frameNum = 30},
[8] = {icon = "userInfo_prop8.png", image = "res/ui/zy_tongyong/zy_prop/item8/item8_fly-i6p.png", plistFile = "res/ui/zy_tongyong/zy_prop/item8/item8_anims_i6p.plist", frameName = "item8_%d.png", frameNum = 13},
[9] = {icon = "userInfo_prop9.png", image = "res/ui/zy_tongyong/zy_prop/item9/item9_fly-i6p.png", plistFile = "res/ui/zy_tongyong/zy_prop/item9/item9_anims_i6p.plist", frameName = "item9_%d.png", frameNum = 33},
[10] = {icon = "userInfo_prop10.png", image = "res/ui/zy_tongyong/zy_prop/item10/item10_fly-i6p.png", plistFile = "res/ui/zy_tongyong/zy_prop/item10/item10_anims_i6p.plist", frameName = "item10_%d.png", frameNum = 4},
}
-- 道具顺序
GamePropSort = {10,9,4,2,3,5,8,6,1,7}


--支付方式
PayType =
{
Apple = 1, -- 苹果支付
PAY_TYPE_WEXIN = 2, -- 微信支付
PAY_TYPE_H5 = 3, -- h5支付
PAY_TYPE_WEXIN_SHARE = 10, -- 微信分享支付
PAY_TYPE_HYB = 11, -- 汇元宝
PAY_TYPE_ALIPAY = 16, -- 支付宝
}
-- 玩家的 GPS 状态
GpsStatus =
{
close = 0, --// 未开启
undeal = 1, --// 未处理
enable = 2, --// 允许
disEnable = 3, --// 拒绝的
unkown = 99, --// 未知的
}

GpsStatusString =
{
[GpsStatus.close] = "GPS未开启", --// 未开启
[GpsStatus.undeal] = "GPS未授权", --// 未处理
[GpsStatus.enable] = "GPS已开启", --// 允许
[GpsStatus.disEnable] = "GPS已拒绝", --// 拒绝的
[GpsStatus.unkown] = "GPS状态未知", --// 未知的
}

-- GPS状态的提示颜色
GpsStatusColor =
{
[GpsStatus.close] = cc.c3b(219,56,35), --// 未开启
[GpsStatus.undeal] = cc.c3b(233, 089, 083), --// 未处理
[GpsStatus.enable] = cc.c3b(113, 184, 109), --// 允许
[GpsStatus.disEnable] = cc.c3b(233, 089, 083), --// 拒绝的
[GpsStatus.unkown] = cc.c3b(255, 255, 255), --// 拒绝的
}

-- GPS距离的提示颜色
GpsDistanceColor =
{
["safe"] = cc.c3b(040, 255, 082), --大于安全距离
["danger"] = cc.c3b(255, 032, 042), --小于安全距离
}

-- GPS界面的默认颜色
GpsDefaultColor = cc.c3b(255, 255, 255)

-- 大厅需要预加载的ui文件
UI_IN_HALL =
{
-- "res/ui/ui_dating/ui_activity_main.ui",
-- "res/ui/ui_dating/ui_bangzhu.ui",
-- "res/ui/ui_dating/ui_chongzhi.ui",
-- "res/ui/ui_dating/ui_chongzhi_xuanze.ui",
-- "res/ui/ui_dating/ui_chuangjian.ui",
-- "res/ui/ui_dating/ui_dailizhaomu.ui",
-- "res/ui/ui_dating/ui_dating.ui",
-- "res/ui/ui_dating/ui_dating_icon.ui",
-- "res/ui/ui_dating/ui_duihuan.ui",
-- "res/ui/ui_dating/ui_duihuan_tiao.ui",
-- "res/ui/ui_dating/ui_gonggao_tiao.ui",
-- "res/ui/ui_dating/ui_huodong.ui",
-- "res/ui/ui_dating/ui_InviteCode.ui",
-- "res/ui/ui_dating/ui_jiarufangjian.ui",
-- "res/ui/ui_dating/ui_shezhi.ui",
-- "res/ui/ui_dating/ui_shiming.ui",
-- "res/ui/ui_dating/ui_shuzijianpan.ui",
-- "res/ui/ui_dating/ui_xiazai.ui",
-- "res/ui/ui_club/ui_club_main.ui",
}

--茶馆需要预加载的ui文件
UI_IN_CLUB =
{
-- "res/ui/ui_club/ui_club_zhanji.ui",
-- "res/ui/ui_club/ui_club_player_list.ui",
-- "res/ui/ui_club/ui_club_baojian.ui",
-- "res/ui/ui_club/ui_club_message.ui",
}

--游戏对应人数
GAME_CONST =
{
CHENZHOU_GAME_CONST_PLAYER = 3,--郴州字牌玩家数量
LIUHUQIANG_GAME_CONST_PLAYER = 4,--六胡抢玩家数量
}

--茶馆设置状态操作
GAME_CLUB_SET_STATE =
{
Club_status = 1, --状态操作茶馆(管理员专属)
Join_set = 2, --加入设置(管理员专属)
Change_club_name= 3, --修改昵称(管理员专属)
Change_privacy = 4, --隐私昵称(管理员专属)
Forbid_share = 6, --屏蔽微信分享(管理员专属)
Change_Mode = 7, --房间模式修改room_mode $value 1多玩法模式, 0包间模式;
Set_win_socre = 8, --大家赢分数统计
Quit_set = 9, --退群申请设置 (创始人)is_exitapply $value 1需要申请, 0无需申请; 无广播
Math_Switch = 13, --比赛场开关
}

--茶馆战绩类型
ClUB_ZHANJI_TYPE =
{
Club = 1, -- 茶馆战绩
Mine = 2, -- 我的战绩
ZhanjiTongji = 3,-- 茶馆战绩统计
}


--茶馆默认桌子数量
GAME_CLUB_TABLE_NUM =
{
club_normal_num = 20,
}

GAME_EVENT = {
DISSMISS_UPDATE_STATUS = "DISSMISS_UPDATE_STATUS",
DISSMISS_CLOSE = "DISSMISS_CLOSE",
RECHARGE_RESULT = "RECHARGE_RESULT",
RECHARGE_CLOSE = "RECHARGE_CLOSE",
UPDATE_WEB_GAME = "UPDATE_WEB_GAME",
EXCHANGE_RESULT = "EXCHANGE_RESULT",

ACTIVITY_CLOSE = "ACTIVITY_CLOSE",

--更新GPS用户数据
GPS_UPDATE_USER_INFO = "GPS_UPDATE_USER_INFO",

--聊天界面
CHAT_PRSPONSE = "CHAT_PRSPONSE", --收到聊天数据
CHAT_GET_RECORED = "CHAT_GET_RECORED", --获取聊天记录
CHAT_GET_RECORED_RESP = "CHAT_GET_RECORED_RESP", --获取聊天记录回调
CHAT_VOICE_RESP = "CHAT_VOICE_RESP", --收到语音消息
CHAT_PLAY_VOICE = "CHAT_PLAY_VOICE",--播放语音播放
CHAT_STOP_VOICE = "CHAT_STOP_VOICE",--停止语音播放
CHAT_REPLAY_VOICE = "CHAT_REPLAY_VOICE",--重复语音播放

--俱乐部
CLUB_MAIN_CLOSE = "CLUB_MAIN_CLOSE",
CLUB_LIST = "CLUB_LIST",
CLUB_TABLE = "CLUB_TABLE",
CLUB_UPDATE_TABLE = "CLUB_UPDATE_TABLE", --刷新单个桌子
CLUB_TABLE_NUM = "CLUB_TABLE_NUM", --刷新桌子数量
CLUB_GAME_RULE = "CLUB_GAME_RULE",
CLUB_CHANGE_RULE = "CLUB_CHANGE_RULE", --修改玩法
CLUB_CHANGE_RULE_PUSH = "CLUB_CHANGE_RULE_PUSH", --玩法修改推送
CLUB_CHANGE_BAO_JIAN = "CLUB_CHANGE_BAO_JIAN", --切换包间
CLUB_CHANGE_BAO_JIAN_NAME = "CLUB_CHANGE_BAO_JIAN_NAME", --切换包间
CLUB_JIE_SAN = "CLUB_JIE_SAN", --茶馆解散
CLUB_JOIN = "CLUB_JOIN", --茶馆加入
CLUB_SET = "CLUB_SET", --茶馆设置
CLUB_CHANGE_PUSH = "CLUB_CHANGE_PUSH", --茶馆修改推送 (除去桌子外的数据)
CLUB_MESSAGE = "CLUB_MESSAGE",
CLUB_MESSAGE_C0PARTNER = "CLUB_MESSAGE_C0PARTNER",--合伙人申请
CLUB_MESSAGE_REAWRD = "CLUB_MESSAGE_REAWRD", --领取奖励
CLUB_MESSAGE_CHANGED = "CLUB_MESSAGE_CHANGED", -- 消息有变动
CLUB_PLAYER_LIST = "CLUB_PLAYER_LIST",
CLUB_PLAYER_SEARCH = "CLUB_PLAYER_SEARCH",
CLUB_INVITE_PLAYER_LIST = "CLUB_INVITE_PLAYER_LIST", --邀请的成员列表
CLUB_PLAYER_BAN_LIST = "CLUB_PLAYER_BAN_LIST", --禁止同桌列表
CLUB_PLAYER_BAN_SET = "CLUB_PLAYER_BAN_SET", --设置禁止同桌
CLUB_PLAYER_ADD = "CLUB_PLAYER_ADD",
CLUB_PLAYER_BAN_ALL_LIST = "CLUB_PLAYER_BAN_ALL_LIST", --查看禁止列表
-- 禁止同队
CLUB_PLAYER_JZ_TABLE_LIST = "CLUB_PLAYER_JZ_TABLE_LIST", --战队列表
CLUB_PLAYER_JZ_YJ_TABLE_LIST = "CLUB_PLAYER_JZ_YJ_TABLE_LIST", -- 已经(YZ)战队列表
CLUB_PLAYER_BAN_ALL_BAN = "CLUB_PLAYER_BAN_ALL_BAN", -- 禁止同队,全部禁止/禁止
CLUB_PLAYER_CANCEL_ALL_CANCEL = "CLUB_PLAYER_CANCEL_ALL_CANCEL", -- 禁止同队,全部取消/取消
CLUB_BACK_ROOM = "CLUB_BACK_ROOM", --茶馆回到房间界面
CLUB_NOTICE = "CLUB_NOTICE", --茶馆公告
CLUB_ACTIVITY_LIST = "CLUB_ACTIVITY_LIST", --活动列表
CLUB_CREATE_ERR = "CLUB_CREATE_ERR",--创建错误
CLUB_CREATE_SUCCESS = "CLUB_CREATE_SUCCESS", -- 创建亲友圈成功
CLUB_INVITE = "CLUB_INVITE", --邀请成员
CLUB_CHANGE_ROLE = "CLUB_CHANGE_ROLE", --成员列表权限改变
CLUB_MEMBER_SET_SUCCESS = "MemberSetSuccess", -- 成员属性修改成功
GetCopartnerSub = "GetCopartnerSub",--获取所有合伙人对应的下线
CopartnerSetup = "CopartnerSetup",--给合伙人设置下线
GetCopartnerStat = "GetCopartnerStat",--合伙人(所有合伙人&统计)
GetCopartnerDetail = "GetCopartnerDetail",--合伙人贡献详情
CLUB_CHANGE_BG = "CLUB_CHANGE_BG", --亲友圈更换背景
CLUB_SET_MATCH = "CLUB_SET_MATCH", --俱乐部设置比赛
CLUB_SET_TABLE_STYLE = "CLUB_SET_TABLE_STYLE", -- 更换亲友圈桌子颜色
CLUB_RED_FLOWER_RECORD = "CLUB_RED_FLOWER_RECORD", --俱乐部红花记录
CLUB_UPDATE_RED_FLOWER = "CLUB_UPDATE_RED_FLOWER", --俱乐部红花更新

EVENT_CHANGE_ADDRESS = "EVENT_CHANGE_ADDRESS", -- 大厅修改自己所在地区
CLUB_CANCEL_COPARTNER_NOTICE = "CLUB_CANCEL_COPARTNER_NOTICE", --取消合伙人通知
CLUB_CANCEL_COPARTNER = "CLUB_CANCEL_COPARTNER", --取消合伙人操作
CLUB_CANCEL_COPARTNER_TIP = "CLUB_CANCEL_COPARTNER_TIP", --取消合伙人操作后的提示
NOTICE_REQUEST_PLAYER_LIST = "NOTICE_REQUEST_PLAYER_LIST", --分布式请求成员列表数据
UPDATE_COPARTNER_RATDIO = "UPDATE_COPARTNER_RATDIO", --更新一二级合伙人比例
CLUB_IMPORT_MBMBER = "CLUB_IMPORT_MBMBER", --俱乐部导入
CLUB_ACTIVE_GAME = "CLUB_ACTIVE_GAME", --俱乐部激活游戏
CLUB_ACTIVE_RULE = "CLUB_ACTIVE_RULECLUB_ACTIVE_RULE", --俱乐部激活玩法
CLUB_ROOM_LIST_UPDATE = "CLUB_ROOM_LIST_UPDATE", --俱乐部房间刷新
CLUB_GPS_DISTANCE = "CLUB_GPS_DISTANCE", --俱乐部俱乐部距离刷新
--
CLUB_SET_COPARTNER_ONE_FAILE = "CLUB_SET_COPARTNER_ONE_FAILE", --设置一级合伙人失败
CLUB_CHANGE_BAO_JIAN_NAME = "CLUB_CHANGE_BAO_JIAN_NAME",--修改包间名
CLUB_CALUATE_ACTIVE_GAME = "CLUB_CALUATE_ACTIVE_GAME",--激活游戏列表更新
UPDATE_SCOREVIEW_SIZE = "UPDATE_SCOREVIEW_SIZE",--更新滑动区域
--排名赛事件分发
CLUB_ALL_PEOPLE_MATCH = "CLUB_ALL_PEOPLE_MATCH",--排名赛管理
CLUB_MATCH_LEVEL_LOG = "CLUB_MATCH_LEVEL_LOG",--升级记录
CLUB_MATCH_TEAM_LEVEL = "CLUB_MATCH_TEAM_LEVEL",--战队升级
CLUB_MATCH_LEVEL_UPGRADE = "CLUB_MATCH_LEVEL_UPGRADE",--战队升级
CLUB_MATCH_JUDGE = "CLUB_MATCH_JUDGE", --裁判
CLUB_TEAM_VIEW = "CLUB_TEAM_VIEW", --打开下级界面
-- CEST海选赛事件分发
CLUB_CEST_GET_GAMESET = "CLUB_CEST_GET_GAMESET", --CEST获取初始参数信息
CLUB_CEST_ALL_PEOPLE_MATCH = "CLUB_CEST_ALL_PEOPLE_MATCH", --CEST海选赛管理
CLUB_CEST_DRAW_TEAM = "CLUB_CEST_DRAW_TEAM", --CEST认领比赛
CLUB_CEST_END_TEAM = "CLUB_CEST_DRAW_TEAM", --CEST结束比赛
CLUB_CEST_GAMEINFO = "CLUB_CEST_GAMEINFO", --CEST报名开始
CLUB_CEST_NO_GAMEINFO = "CLUB_CEST_NO_GAMEINFO", --CEST报名开始,还没有设置报名场的参数
CLUB_CEST_START_APPLY = "CLUB_CEST_START_APPLY", --CEST报名参加
CLUB_CEST_APPLY_LIST = "CLUB_CEST_APPLY_LIST", --CEST海选赛申请列表
CLUB_CEST_APPLY_BTN = "CLUB_CEST_APPLY_BTN", --CEST海选赛申请列表更新按钮
CLUB_CEST_APPLY_STATUS = "CLUB_CEST_APPLY_STATUS", --CEST海选赛报名审核
CLUB_CEST_END_GAME = "CLUB_CEST_END_GAME", --CEST海选赛申请退赛
CLUB_CEST_USER_INFO = "CLUB_CEST_USER_INFO", --CEST海选赛申请退赛
CLUB_CEST_APPLY_LOG = "CLUB_CEST_APPLY_LOG", --CEST海选赛申请记录日志
CLUB_CEST_CANSAI_MINGE = "CLUB_CEST_CANSAI_MINGE", --CEST海选赛申请参赛名额
CLUB_CEST_REQUEST_MINGE_INFO = "CLUB_CEST_REQUEST_MINGE_INFO", --CEST海选赛去请求参赛名额信息
CLUB_CEST_UPDATE_APPLY_LIST = "CLUB_CEST_UPDATE_APPLY_LIST", --CEST拉取海选赛申请消息
-- tianti
CLUB_TIANTI_BAOMING_REG = "CLUB_TIANTI_BAOMING_REG", --TIANTI 报名

--UNION
CLUB_UNION_CHECK_MASTER = "CLUB_UNION_CHECK_MASTER", -- 查询主盟(已加入)
CLUB_UNION_HITS = "CLUB_UNION_HITS", -- 主盟红点
CLUB_UNION_JOIN_MASTER_LIST = "CLUB_UNION_JOIN_MASTER_LIST", --申请加入主盟的列表
CLUB_UNION_MESSAGE = "CLUB_UNION_MESSAGE", --主盟的消息列表
CLUB_UNION_SLAVE_UPDATE = "CLUB_UNION_SLAVE_UPDATE", --刷新fu盟的列表
CLUB_UNION_SLAVE_UPDATE_LEVEL = "CLUB_UNION_SLAVE_UPDATE_LEVEL", --副盟的个人信息
CLUB_UNION_CLUB_BELONG = "CLUB_UNION_CLUB_BELONG", --亲友圈归属
CLUB_UNION_CLUB_BELONG_LIST = "CLUB_UNION_CLUB_BELONG_LIST", --亲友圈归属list
--连打功能
GAME_LIAN_DA = "GAME_LIAN_DA", --连打功能
}

STORE_TYPE = {
BUY_ZUANSHI = 0, --购买钻石
BUY_HUANLEDOU = 1, --购买欢乐豆
CHECK_HISTORY = 2, --购买记录
CHANGE_COIN = 4, --兑换金币
CHANGE_LIQUAN = 5, --礼券兑换实物
CHANGE_QYQBG = 81, --亲友圈背景兑换
CHANGE_DTBG = 82, --大厅背景兑换
CHANGE_LTQP = 83, --聊天气泡兑换
CHANGE_YYQP = 84, --语音气泡兑换
}

INVITE_NEW_FRIEND = {
NOENOUGH_ADDITION = 0,--不满足条件
ENOUGH_ADDITION = 1, --满足条件
HAVED_PRIZED =2,
OLD_PLAYER =3,--老玩家不可領取
}

PROTOCOL_TYPE = {
COMMON = 1,
COIN = 2,
MATCH = 3,
}

COIN_LEVEL = {
INIT = 10, -- 初级金币场
MIDDLE = 20, -- 中级金币场
HIGH = 30, -- 高级金币场
}

COIN_TEXT_NAME = {
[COIN_LEVEL.INIT] = "初级场",
[COIN_LEVEL.MIDDLE] = "中级场",
[COIN_LEVEL.HIGH] = "高级场",
}

COIN_SERVER_LEVEL = {
[0] = "钻石模式";
[1] = "初级场";
[2] = "中级场";
[3] = "高级场";
}

--是否启用新俱乐部代码
IS_USER_NEW_CLUB = true

NOTICE_REDPOINT = {
--公告里面
[1] = "notice_security",--超强防护
[2] = "tasks_groupTasks",--亲友圈活动
[3] = "notice_brand",--品牌力量
[4] = "notice_greenNotice",--绿色公告
[5] = "tasks_newGame",--新游上线(最新)
--[6] = "notice_gameUpdate",--游戏更新
[7] = "notice_goldMatch",--金币场
[8] = "tasks_newGamePuYu",--网页游戏
[9] = "tasks_newGameXiYou",--网页游戏
[10] = "tasks_newGameDDH",--新游(倒倒胡)
[11] = "notice_greenWelfare",--绿色公益
[12] = "notice_coBranding",--合作品牌
[13] = "tasks_xianyouji",--合作品牌
[14] = "tasks_meilixiushan",--美丽秀山
[15] = "tasks_hongbaoquan",--红包券
}

ACTIVITY_REDPOINT = {
--金币场
COIN_GAME_FULI = "everyWelfare",--金币场每日福利
COIN_GAME_FREE_GOLD = "freeGold",--金币场免费金币
--大厅
SYSTEM_MESSAGE = "message",--邮件消息
SYSTEM_IDENTIFY = "identify",--实名认证
AGENT = "agent",
}

LoginType = {
LOGIN_TYPE_WEIXIN = 0, --微信登录
LOGIN_TYPE_PHONE = 1, --手机密码登录
LOGIN_TYPE_PHONE_CHECKCODE = 2, --手机验证码登陆
LOGIN_TYPE_ID = 3, --ID登录
LOGIN_TYPE_PHONE_REGISTER = 5, --手机注册
}

ChangePlayerInfo = {
PHONE_RESET = 1, --手机密码重置
REPLCACE_PHONE = 2, --手机替换
}

BIND_TYPE = {
PHONE = 0, --绑定手机
WEIXIN = 3, --绑定微信
WEIXIN_TWICE_BIND = 4, --二次授权绑定
BIND_TYPE_PASSWORD = 5, --密码强制设置
}

BIND_TYPE_RESULT = {
PHONE = 0, --绑定手机成功
CHECKCODE_FAILED = 1, --验证码错误
PHONE_BIND_FAILED = 2, --已绑定过手机号,无需再次绑定
PHONE_BINDED_OTHER_FAILED = 5, --该手机号已经被其他游戏ID绑定,请更换手机号再次绑定
WEIXIN = 6, --绑定微信成功
WEIXINBINDED_OTHER_FAILED = 7, --该微信号已绑定过其他游戏账号
WEIXIN_TWICE_BIND = 8, --二次授权绑定成功
USER_SET_PASSWORD = 9, --用户设置密码成功
}

+ 322
- 0
core/luaScript/GlobalEvent.lua Näytä tiedosto

@@ -0,0 +1,322 @@

local isLoginData = false
local isUpdateData = false

local function gotoRoom()
local loginInfo = app.user.loginInfo
if loginInfo.gameId > 0 and loginInfo.tid > 0 then

if not isLoginData or not isUpdateData then
app.waitDialogManager:closeWaitNetworkDialog()
return
end

app.waitDialogManager:closeWaitNetworkDialog()

-- 进入房间
local function enterRoom()
app.hall:requestEnterRoom(loginInfo.gameId, loginInfo.tid, app.protocolType)
end
-- 尝试进入房间
local function tryEnterRoom()
local result, subGameId, missingFiles = app.subGameManager:checkGameFiles(loginInfo.gameId)
if not result then
logD("GlobalEvent::gotoRoom() 发现子游戏文件缺失,gameId = "..subGameId)
for k,v in pairs(missingFiles) do
logD(v);
end
local function onOk()
app.subGameManager:clearGame(subGameId, function()
downloadSubGame(subGameId, tryEnterRoom);
end);
end
showConfirmDialog("发现文件缺失,点击确定开始修复", onOk);
else
enterRoom();
end
end
local isInstall = app.subGameManager:isInstaller(loginInfo.gameId)
local isNeedUpdate = app.subGameManager:isNeedUpdate(loginInfo.gameId)
if not isInstall or isNeedUpdate then
downloadSubGame(loginInfo.gameId, tryEnterRoom)
return
end
tryEnterRoom()
end
end

-- 侦听全局的socket重连成功消息
function netConnectSucceed()
-- 清空之前通过Protocol:sendResponse所有的消息注册函数
local function clearAllRegMsg()
for i, v in pairs(g_regMsgCallBackFuncs) do
v()
end
print("连接成功,清空所有之前通过Protocol:sendResponse注册的网络回调函数, 回到函数个数:" .. table.nums(g_regMsgCallBackFuncs))
g_regMsgCallBackFuncs = { }
end

app:addEventListener("socketConnectSucceed", clearAllRegMsg)
end

-- 绑定角色登陆成功的全局事件
local function actorLoginSucceed()
-- 角色登陆成功后拉取消息全部返回完毕后拉取战斗
local function onLoginSuccessed()

local LoginConfig = require("luaScript.Views.Login.LoginConfig")
if LoginConfig.EapSDK and (not isWin32Platform()) and G_EapSdkMgr then
local userInfo = json.decode(app.user.userInfo);
G_EapSdkMgr:login(tostring(app.user.loginInfo.uid), userInfo.nickname, userInfo.headimgurl, app.user.phonenum or "", app.user.sex)
end

app.waitDialogManager:closeTransparencyMask();
local loginInfo = app.user.loginInfo
print("GlobalEvent onLoginSuccessed :"..table.tostring(loginInfo))
local currentView = app:getCurrentView();
-- 参数不正确的情况下直接进入到大厅界面,省事
if not loginInfo or not currentView then
--app:gotoView(import("luaScript.Views.Main.MainView"):new());
gotoMainView()
app.user:dispatchEvent({name = "onMainViewLoginSuccessed"})
return
end
--在比赛中
if loginInfo and loginInfo.matchFlag == 1 then
local function gotoMatch()
local MatchEvents = require("luaScript.Views.Match.Constant.MatchEvents")
local ProtocolMatchMessage = require("luaScript.Protocol.Match.ProtocolMatchMessage")
local request=ProtocolMatchMessage.MatchEnter:new()
request.uid = loginInfo.uid
request.userInfo = app.user.userInfo
dump(request)
app.waitDialogManager:showWaitNetworkDialog("获取比赛信息...");
app.mainScene:sendMsg(app.match, MatchEvents.ENTER_MATCH, request, function(status, response)
-- print(table.tostring(response))
end)
end
local isInstall = app.subGameManager:isInstaller(loginInfo.gameId)
local isNeedUpdate = app.subGameManager:isNeedUpdate(loginInfo.gameId)
if not isInstall or isNeedUpdate then
downloadSubGame(loginInfo.gameId, gotoMatch)
return
end
gotoMatch()
return
end
-- 看玩家数据是不是在房间中
if loginInfo.gameId > 0 and loginInfo.tid > 0 then
-- 如果没有配置信息,只能进大厅
local gameConfig = getSubGameConfig(loginInfo.gameId)
if not gameConfig then
--app:gotoView(import("luaScript.Views.Main.MainView"):new());
gotoMainView()
app.user:dispatchEvent({name = "onMainViewLoginSuccessed"})
return
end

if loginInfo.serverLevel >= COIN_LEVEL.INIT and loginInfo.serverLevel <= COIN_LEVEL.HIGH + 10 then --金币场区间为10~40
app.protocolType = PROTOCOL_TYPE.COIN
end

isLoginData=true
app.waitDialogManager:showWaitNetworkDialog()
gotoRoom()
-- -- 请求进入房间
-- local function enterRoom()
-- app.hall:requestEnterRoom(loginInfo.gameId, loginInfo.tid)
-- end
-- local isInstall = app.subGameManager:isInstaller(loginInfo.gameId)
-- local isNeedUpdate = app.subGameManager:isNeedUpdate(loginInfo.gameId)
-- if not isInstall or isNeedUpdate then
-- downloadSubGame(loginInfo.gameId, enterRoom)
-- return;
-- end
-- enterRoom()
else
-- 若果正在显示总结算,则不理
if isShowCountAll() then
return
end
-- 如果玩家不在房间中,分两种情况
-- 一种是现在的界面就是在大厅中。则什么都不用做,保持当前状态
-- 另一种是现在的界面不在大厅中,则需要重新进入大厅界面
if "MainView" ~= currentView.__cname then
--app:gotoView(import("luaScript.Views.Main.MainView"):new());
gotoMainView()
end
app.user:dispatchEvent({name = "onMainViewLoginSuccessed"})
end
end

app.user:addEventListener("onLoginSuccessed", onLoginSuccessed)
end

local function actorLoginFailed()
local function OnActorLoginFailed(event)
local errCode = event.errCode
if errCode then
-- 1: 电话号码未绑定微信 2: 密码错误
local errString =
{
[1] = "您的账号还没有绑定,请先使用【微信登陆】并在玩家信息中绑定【手机】账号",
[2] = "密码错误",
[3] = "账号已经禁止使用",
[4] = "验证码错误",
[7] = "该手机号已绑定过其他游戏账号",
[8] = "该手机号还未注册",
[9] = "没有此用户",
}
local message = errString[errCode] or "手机号登录失败 "..tostring(errCode);
if tonumber(errCode) == 1 then
showConfirmDialog(message,nil,nil,25);
else
showConfirmDialog(message);
end
end
end
app.user:addEventListener("onPhoneLoginErrResponse", OnActorLoginFailed)
end

function registerEnterRoomEvent()
local function onEnterRoomSuccess(event)
--EAPSDK 进入房间自动隐藏
if G_LayerMain then
G_LayerMain:setVisible(false);
end
local gameId = event.gameId or 0;
local gameType = event.gameType or 0;
--目前只有金币场用到,用于区分是进入房间成功还是断线重连(金币场的gameStatus无法使用)
local param = event.param;
runInNextFrame(function()
local roomViewName = getSubGameRoomView(gameId, gameType, app.protocolType)
logD("onEnterRoomSuccess() roomViewName = " .. roomViewName)
if roomViewName then
local arr = string.split(roomViewName, ".")
local len = table.nums(arr)
local currentView = app:getCurrentView();
if currentView then
logD("onEnterRoomSuccess() currentName = " .. currentView.__cname)
else
logD("onEnterRoomSuccess() currentView is nil")
end
if currentView and currentView.__cname == arr[len] then
-- 当前正是在我想去的房间里面
logD("onEnterRoomSuccess() do nothing")
else
logD("onEnterRoomSuccess() goto view " .. roomViewName)
app:gotoView(import(roomViewName):new(param));
end
end
end)
end
app.hall:addEventListener("onEnterRoomSuccess", onEnterRoomSuccess)
end

function registerKickoutEvent()
local function onServerKickout()
local function onClickOk()
app.plugin:logout();
end
app.net.isNeedReconnect = false
app.net:close();
showConfirmDialog("数据异常,请重新登录", onClickOk)--"您的账号在其他地方登陆,您被强制下线"
end
app.user:addEventListener("onServerKickOutResponse", onServerKickout)
end

--子游戏更新获取完成事件
function registerSubGameListEvent()
local function getSubGameListSuccessed()
if not isUpdateData then
isUpdateData=true
gotoRoom()
end
end
app.serverConfigs:addEventListener("getSubGameListSuccessed", getSubGameListSuccessed)
end

--绑定手机结果/绑定微信/二次授权
function registerBindAppEvent()
local function onBindResponse(event)
if not event or not event.response then
return
end
local ret = tonumber(event.response.ret);
if ret == 7 then
uploadLogs("WEIXIN_TWICE_BIND")
end

local tips =
{
[0] = "绑定成功",
[1] = "验证码错误",
[2] = "已绑定过手机号,无需再次绑定",
[5] = "该手机号已经被其他游戏ID绑定,请更换手机号再次绑定",
[6] = "绑定成功",
[7] = "该微信号已绑定过其他游戏账号",
[8] = "绑定成功",
[9] = "设置成功",
}
local msg = tips[ret] or "未知错误:"..tostring(ret)
showConfirmDialog(msg, function() end)
end
app.user:addEventListener("onBindResponse", onBindResponse)
end

--修改手机号/修改密码
function registerChangeAppEvent()
local function onChangePlayerInfo(event)
if not event or not event.response then
return
end
local ret = tonumber(event.response.ret);
local tips =
{
[0] = "修改成功",
[1] = "您的账号还没有绑定,请先使用【微信登陆】并在玩家信息中绑定【手机】账号",
[2] = "密码错误",
[3] = "账号已经禁止使用",
[4] = "验证码错误",
[7] = "该手机号已绑定过其他游戏账号",
[8] = "该手机号还未注册",
}
local msg = tips[ret] or "未知错误:"..tostring(ret)
showConfirmDialog(msg, function() end)
end
app.user:addEventListener("onChangePlayerInfo", onChangePlayerInfo)
end

-- 开始侦听所有全局事件
function startGlobalEvent()
if isReviewWithMiniGame() then
return
end
netConnectSucceed()
actorLoginSucceed()
actorLoginFailed()
registerEnterRoomEvent()
registerKickoutEvent()
registerSubGameListEvent()
registerBindAppEvent()
registerChangeAppEvent()
end

+ 577
- 0
core/luaScript/GlobalPlugin.lua Näytä tiedosto

@@ -0,0 +1,577 @@
local PluginAndroidLocation = require("luaScript.Plugins.PluginAndroidLocation");
local PluginAndroidGVoice = require("luaScript.Plugins.PluginAndroidGVoice");
local PluginAndroidDowloadManager = require("luaScript.Plugins.PluginAndroidDowloadManager");
local PluginAndroidPing = require("luaScript.Plugins.PluginAndroidPing");

local PluginIosPay = require("luaScript.Plugins.PluginIosPay");
local PluginIosLocation = require("luaScript.Plugins.PluginIosLocation");
local PluginIosGVoice = require("luaScript.Plugins.PluginIosGVoice");
local PluginIosDowloadManager = require("luaScript.Plugins.PluginIosDowloadManager");

local PluginWechat = require("luaScript.Plugins.PluginWechat");
local PluginWechatShare = require("luaScript.Plugins.PluginWechatShare");
local PluginYaya = require("luaScript.Plugins.PluginYaya");
local PluginGVoice = require("luaScript.Plugins.PluginGVoice");
local PluginZhuCheng = require("luaScript.Plugins.PluginZhuCheng");

local GlobalPlugin = class("GlobalPlugin");

function GlobalPlugin:ctor()
-- 苹果支付插件
self.pluginIosPay = nil

-- 微信
self.pluginWechat = nil;

-- 微信分享
self.pluginWxShare = nil

--yaya语音
self.pluginVoice = nil;

--腾讯语音插件
self.pluginGVoice = nil

-- GPS 定位插件
self.pluginGps = nil

-- 初始化
self:init();
end

function GlobalPlugin:init()
-- 载入平台信息

local channelId = app.config.RomSetting.ChannelId;

-- PC 版本强制设为100,防止配置错误导致的报错
if isWin32Platform() then
channelId = 100
end

if isAndroidPlatform() then
self.pluginWechat = PluginWechat:new();
self.pluginVoice = PluginYaya:new();
self.pluginGps = PluginAndroidLocation:new()
self.pluginDownloader = PluginAndroidDowloadManager:new()
self.pluginPing = PluginAndroidPing:new()
--self.pluginWxShare = PluginWechatShare:new()
self.pluginGVoice = PluginGVoice:new()
elseif isIOSPlatform() then
self.pluginWechat = PluginWechat:new();
self.pluginVoice = PluginYaya:new();
self.pluginGps = PluginIosLocation:new();
self.pluginDownloader = PluginIosDowloadManager:new()
--self.pluginWxShare = PluginWechatShare:new()
self.pluginGVoice = PluginGVoice:new()

if channelId == 105 then
self.pluginIosPay = PluginIosPay:new();
end
end

-- 启动插件
self:start();
end

-- 开启插件
function GlobalPlugin:start()

-- 启动登陆插件
if self.pluginWechat then
self.pluginWechat:start()
end

-- 下载SDK
if self.pluginDownloader then
self.pluginDownloader:start()
end

-- 网络监测
if self.pluginPing then
self.pluginPing:start()
end

-- 定位
if self.pluginGps then
local versionCode = getAppVersionName()
log("versionCode:",versionCode)
self.pluginGps:start()
end
end

-- 注销账号
function GlobalPlugin:logout(tt)
if not isWin32Platform() then
app.userManager:clearUserList();
end
cc.Application:getInstance():restart();
end

-- 跳转网页
function GlobalPlugin:callUrl(url)
logD("GlobalPlugin:callUrl(), url = ", url);
if PluginDevice then
PluginDevice:callVoid("openUrl", url);
else
logD("GlobalPlugin:callUrl(), PluginDevice is nil");
end
end

function GlobalPlugin:isShowThirdLogin()
return self:isSupportWeiXin()
end

function GlobalPlugin:shareGame(tt, shareCallback)
logD("GlobalPlugin:shareGame(), tt = ", table.tostring(tt))
if self.pluginWxShare then
self:shareWxShare(tt, shareCallback)
else
self:shareWeiXin(tt, shareCallback)
end
end
------------------------------------------- IosPay -------------------------------------------

function GlobalPlugin:startIosPay()
logD("GlobalPlugin:startIosPay()")
if self.pluginIosPay then
self.pluginIosPay:start()
else
logD("GlobalPlugin:startIosPay(), self.pluginIosPay is nil")
end
end

function GlobalPlugin:payIosPay(itemInfo)
logD("GlobalPlugin:payIosPay(), tt = ", table.tostring(itemInfo))
if self.pluginIosPay then
self.pluginIosPay:pay(itemInfo)
else
logD("GlobalPlugin:payIosPay(), self.pluginIosPay is nil")
end
end

------------------------------------------- WeiXin -------------------------------------------
function GlobalPlugin:isSupportWeiXin()
logD("GlobalPlugin:isSupportWeiXin()")
if self.pluginWechat then
local result = self.pluginWechat:isSupport()
logD("GlobalPlugin:isSupportWeiXin(), result = ", tostring(result))
return result
else
logD("GlobalPlugin:isSupportWeiXin(), self.pluginWechat is nil")
return false
end
end

function GlobalPlugin:gotoWeiXin()
logD("GlobalPlugin:gotoWeiXin()")
if self.pluginWechat then
self.pluginWechat:gotoWeiXin();
else
logD("GlobalPlugin:gotoWeiXin(), self.pluginWechat is nil")
end
end

function GlobalPlugin:loginWeiXin(tt)
logD("GlobalPlugin:loginWeiXin(), tt = ", table.tostring(tt))
if self.pluginWechat then
self.pluginWechat:login(tt);
else
logD("GlobalPlugin:loginWeiXin(), self.pluginWechat is nil")
end
end

function GlobalPlugin:payWeiXin(tt)
logD("GlobalPlugin:payWeiXin(), tt = ", table.tostring(tt))
if self.pluginWechat then
self.pluginWechat:pay(tt);
else
logD("GlobalPlugin:payWeiXin(), self.pluginWechat is nil")
end
end

function GlobalPlugin:shareWeiXin(tt, callback)
logD("GlobalPlugin:shareWeiXin(), tt = ", table.tostring(tt))
if self.pluginWechat then
self.pluginWechat:shareGame(tt, callback)
else
logD("GlobalPlugin:shareWeiXin(), self.pluginWechat is nil")
end
end

-- 显示微信下载的对话框
function GlobalPlugin:showWeiXinDownloadDialog()
local text = "未安装【微信】,是否前往下载【微信】?"
local okBtnImage = "res/ui/zy_tongyong/zy_button/btn_like_xiazai.png"
local okCallBack = function()
app.plugin:callUrl("http://weixin.qq.com/");
end
local cancelCallBack = function()
end
showConfirmDialog(text, okCallBack, cancelCallBack, 26, okBtnImage)
return;
end

------------------------------------------- wxshare -------------------------------------------

-- 初始化微信分享
function GlobalPlugin:initWxShare( appid, secret )
logD("GlobalPlugin:initWxShare(), appid = "..appid..", secret = "..secret)
if isWin32Platform() then
logD("GlobalPlugin:initWxShare(), win32")
return
end

if isReviewVersion() then
logD("GlobalPlugin:initWxShare(), review version")
return
end
local PluginConfig = require("preload.PluginConfig")
if PluginConfig and PluginConfig.isAppStoreVersion then
-- 苹果商城的版本因为包名发生了变化,是不能使用多微信分享的。
return
end

if not self.pluginWxShare then
self.pluginWxShare = PluginWechatShare:new()
end

if self.pluginWxShare then
self.pluginWxShare:start(appid, secret);
end
end

function GlobalPlugin:shareWxShare(tt, callback)
logD("GlobalPlugin:shareWxShare(), tt = ", table.tostring(tt))
if self.pluginWxShare then
self.pluginWxShare:shareGame(tt, callback)
else
logD("GlobalPlugin:shareWxShare(), self.pluginWxShare is nil")
end
end


------------------------------------------- voice -------------------------------------------

-- 成功登陆到游戏
function GlobalPlugin:startVoice()
logD("GlobalPlugin:startVoice()")
if self.pluginVoice then
self.pluginVoice:start()
else
logD("GlobalPlugin:startVoice(), self.pluginVoice is nil")
end
end

-- 开始录音
function GlobalPlugin:startRecord()
logD("GlobalPlugin:startRecord()")
if self.pluginVoice then
self.pluginVoice:startRecord()
else
logD("GlobalPlugin:startRecord(), self.pluginVoice is nil")
end
end

-- 结束录音
function GlobalPlugin:stopRecord()
logD("GlobalPlugin:stopRecord()")
if self.pluginVoice then
self.pluginVoice:stopRecord()
else
logD("GlobalPlugin:stopRecord(), self.pluginVoice is nil")
end
end

-- 取消录音
function GlobalPlugin:cancelRecord()
logD("GlobalPlugin:cancelRecord()")
if self.pluginVoice then
self.pluginVoice:cancelRecord()
else
logD("GlobalPlugin:cancelRecord(), self.pluginVoice is nil")
end
end

-- 播放录音
function GlobalPlugin:playRecord(filePath)
log("GlobalPlugin:playRecord(), filePath = ", filePath);
if self.pluginVoice then
self.pluginVoice:playRecord(filePath)
else
logD("GlobalPlugin:playRecord(), self.pluginVoice is nil")
end
end

-- 停止播放录音
function GlobalPlugin:stopPlayRecord()
log("GlobalPlugin:stopPlayRecord() ");
if self.pluginVoice then
self.pluginVoice:stopPlayRecord()
else
logD("GlobalPlugin:stopPlayRecord(), self.pluginVoice is nil")
end
end


-- 下载录音
function GlobalPlugin:downloadRecord(nUserId, recordUrl, downloadCallback)
log("GlobalPlugin:downloadRecord(), nUserId = " .. nUserId .. ", recordUrl = " .. recordUrl);
if self.pluginVoice then
self.pluginVoice:downloadRecord(nUserId, recordUrl, downloadCallback);
else
logD("GlobalPlugin:downloadRecord(), self.pluginVoice is nil")
end
end

------------------------------------------- gvoice -------------------------------------------
-- 成功登陆到游戏
function GlobalPlugin:startGVoice()
logD("GlobalPlugin:startGVoice()")
if self.pluginGVoice then
self.pluginGVoice:start()
else
logD("GlobalPlugin:startGVoice(), self.pluginGVoice is nil")
end
end


function GlobalPlugin:ApplyMessageKey()
logD("GlobalPlugin:ApplyMessageKey()")
if self.pluginGVoice then
self.pluginGVoice:ApplyMessageKey()
else
logD("GlobalPlugin:ApplyMessageKey(), self.pluginGVoice is nil")
end
end

-- 开始录音
function GlobalPlugin:startGRecord()
logD("GlobalPlugin:startGRecord()")
if self.pluginGVoice then
self.pluginGVoice:startRecord()
else
logD("GlobalPlugin:startGRecord(), self.pluginGVoice is nil")
end
end

-- 结束录音
function GlobalPlugin:stopGRecord()
logD("GlobalPlugin:stopGRecord()")
if self.pluginGVoice then
self.pluginGVoice:stopRecord()
else
logD("GlobalPlugin:stopGRecord(), self.pluginGVoice is nil")
end
end

-- 取消录音
function GlobalPlugin:cancelGRecord()
logD("GlobalPlugin:cancelGRecord()")
if self.pluginGVoice then
self.pluginGVoice:cancelRecord()
else
logD("GlobalPlugin:cancelGRecord(), self.pluginGVoice is nil")
end
end


-- 播放录音
function GlobalPlugin:playGRecord(fileId)
log("GlobalPlugin:playGRecord(), fileId = ", fileId);
if self.pluginGVoice then
self.pluginGVoice:playRecord(fileId)
else
logD("GlobalPlugin:playGRecord(), self.pluginGVoice is nil")
end
end

-- 停止播放录音
function GlobalPlugin:stopGPlayRecord()
log("GlobalPlugin:stopGPlayRecord() ");
if self.pluginGVoice then
self.pluginGVoice:stopPlayRecord()
else
logD("GlobalPlugin:stopGPlayRecord(), self.pluginGVoice is nil")
end
end

-- 下载录音
-- function GlobalPlugin:downloadGRecord(nfileID, nUserId, filePath, downloadCallback)
-- log("GlobalPlugin:downloadGRecord(), nfileID = " .. nfileID .. ", nUserId = " .. nUserId .. ", filePath = " .. filePath);
function GlobalPlugin:downloadGRecord(nUserId, nfileID, downloadCallback)
log("GlobalPlugin:downloadGRecord(), nUserId = " .. nUserId .. ", nfileID = " .. nfileID);
if self.pluginGVoice then
-- self.pluginGVoice:downloadRecord(nfileID, nUserId, filePath, downloadCallback);
self.pluginGVoice:downloadRecord(nUserId, nfileID, downloadCallback);
else
logD("GlobalPlugin:downloadGRecord(), self.pluginGVoice is nil")
end
end


-- 加入房间
function GlobalPlugin:JoinRoom(room)
log("GlobalPlugin:JoinRoom(), room = ", room);
if self.pluginGVoice then
self.pluginGVoice:JoinRoom(room)
else
logD("GlobalPlugin:JoinRoom(), self.pluginGVoice is nil")
end
end
-- 退出房间
function GlobalPlugin:QuitRoom(room)
log("GlobalPlugin:QuitRoom(), room = ", room);
if self.pluginGVoice then
self.pluginGVoice:QuitRoom(room)
else
logD("GlobalPlugin:QuitRoom(), self.pluginGVoice is nil")
end
end
-- 开启麦克风
function GlobalPlugin:OpenMic()
log("GlobalPlugin:OpenMic() ");
if self.pluginGVoice then
self.pluginGVoice:OpenMic()
else
logD("GlobalPlugin:OpenMic(), self.pluginGVoice is nil")
end
end

-- 关闭麦克风
function GlobalPlugin:CloseMic()
log("GlobalPlugin:CloseMic() ");
if self.pluginGVoice then
self.pluginGVoice:CloseMic()
else
logD("GlobalPlugin:CloseMic(), self.pluginGVoice is nil")
end
end
-- 开启扬声器
function GlobalPlugin:OpenSpeaker()
log("GlobalPlugin:OpenSpeaker() ");
if self.pluginGVoice then
self.pluginGVoice:OpenSpeaker()
else
logD("GlobalPlugin:OpenSpeaker(), self.pluginGVoice is nil")
end
end
-- 关闭扬声器
function GlobalPlugin:CloseSpeaker()
log("GlobalPlugin:CloseSpeaker() ");
if self.pluginGVoice then
self.pluginGVoice:CloseSpeaker()
else
logD("GlobalPlugin:CloseSpeaker(), self.pluginGVoice is nil")
end
end

function GlobalPlugin:OnApplicationPause()
log("GlobalPlugin:OnApplicationPause() ");
if self.pluginGVoice then
self.pluginGVoice:OnApplicationPause()
else
logD("GlobalPlugin:OnApplicationPause(), self.pluginGVoice is nil")
end
end

function GlobalPlugin:Update()
-- log("GlobalPlugin:Update() ");
if self.pluginGVoice then
self.pluginGVoice:Update()
else
-- logD("GlobalPlugin:Update(), self.pluginGVoice is nil")
end
end


------------------------------------------- gps -------------------------------------------

-- 更新GPS位置信息
function GlobalPlugin:updateLocation()
logD("GlobalPlugin:updateLocation()")
if self.pluginGps then
self.pluginGps:updateLocation()
else
logD("GlobalPlugin:updateLocation() self.pluginGps is nil")
end
end

-- 获取当前的GPS位置信息
function GlobalPlugin:getLocationInfo()
logD("GlobalPlugin:getLocationInfo()")
if self.pluginGps then
return self.pluginGps:getLocationInfo()
else
logD("GlobalPlugin:getLocationInfo() self.pluginGps is nil")
end
end

-- 获取定位服务开启状态
function GlobalPlugin:getLocationEnable()
logD("GlobalPlugin:getLocationEnable()")
if self.pluginGps then
local status = self.pluginGps:getLocationEnable()
logD("GlobalPlugin:getLocationEnable(), status = ", tostring(status))
return status
else
logD("GlobalPlugin:getLocationEnable() self.pluginGps is nil")
return false
end
end

-- 前往打开GPS
function GlobalPlugin:openGPS()
logD("GlobalPlugin:openGPS()");
if self.pluginGps then
self.pluginGps:openGPS();
else
logD("GlobalPlugin:openGPS() self.pluginGps is nil")
end
end

------------------------------------------- ping -------------------------------------------
function GlobalPlugin:startPing()
logD("GlobalPlugin:startPing()")
if self.pluginPing then
return self.pluginPing:startPing()
else
logD("GlobalPlugin:startPing(), self.pluginPing is nil")
end
end

function GlobalPlugin:stopPing()
logD("GlobalPlugin:stopPing()")
if self.pluginPing then
return self.pluginPing:stopPing()
else
logD("GlobalPlugin:stopPing(), self.pluginPing is nil")
end
end

function GlobalPlugin:getPing()
logD("GlobalPlugin:getPing()")
if self.pluginPing then
local result = self.pluginPing:getPing()
logD("GlobalPlugin:getPing(), result = ", result)
return result
else
logD("GlobalPlugin:getPing(), self.pluginPing is nil")
return 0
end
end

------------------------------------------- downloader -------------------------------------------
function GlobalPlugin:createTask(url,path,onFinish,onProgress)
logD("GlobalPlugin:createTask(), url = " .. url .. ", path = " .. path)
if self.pluginDownloader then
self.pluginDownloader:createTask(url,path,onFinish,onProgress)
else
logD("GlobalPlugin:createTask(), self.pluginDownloader is nil")
end
end

return GlobalPlugin

+ 4
- 0
core/luaScript/GoToMainView.lua Näytä tiedosto

@@ -0,0 +1,4 @@

function gotoMainView(gameid,clubid)
app:gotoView(import("luaScript.Views.Main.MainView"):new(gameid))
end

+ 85
- 0
core/luaScript/Interface/IClub.lua Näytä tiedosto

@@ -0,0 +1,85 @@
---
-- ================================================================
-- 文件名: IClub.lua
-- 描述: 亲友圈相关接口
-- 版权: Copyright © 2016-2019 公司名称 版权所有
-- 作者: Administrator
-- 创建日期: 2019-10-22
-- 更新日期: 2019-10-22
-- 备注:
-- ================================================================
--
local IClub = {}
function IClub.getClubPhp ()
return app.club_php
end
---
-- 获取当前亲友圈id
-- @return
--
function IClub.getCurrentClubId ()
return app.club_php.clubID and tonumber(app.club_php.clubID) or 0
end
---
-- 获取当前亲友圈数据
-- @return
--
function IClub.getCurrentClubInfo()
local clubId = IClub.getCurrentClubId()
return IClub.getClubInfo(clubId)
end
---
-- 获取指定亲友圈数据
-- @param clubId
-- @return
--
function IClub.getClubInfo(clubId)
local clubInfo = app.club_php:getClubInfo(clubId)
return clubInfo
end
---
-- 当前是否在亲友圈里
-- @return
--
function IClub.isInClub ()
return app.club_php.clubID and app.club_php.clubID ~= 0
end
---
-- 是否可以解散房间
-- @return
--
function IClub.getCanDismiss (callBack)
if not IClub.isInClub() then
return 1
end

local clubInfo = IClub.getCurrentClubInfo()
if not clubInfo then
local clubId = IClub.getCurrentClubId()
app.club_php:requestClubHomeInGame(clubId, function ( res )
local groupext = res.groupext or {}
local playext = groupext.playext or {}
logD("IClub.getCanDismiss", res.groupext)
if type(callBack) == "function" then
callBack({canDismiss = playext.can_dismiss})
end
end)
return
end

local groupext = clubInfo.groupext or {}
local playext = groupext.playext or {}
return playext.can_dismiss or 1
end

function IClub.isAdmin()
local clubInfo = IClub.getCurrentClubInfo()
if not clubInfo then
return false
end
local role = clubInfo.role
local isAdmin = role == 2 or role == 3
return isAdmin
end

return IClub

+ 51
- 0
core/luaScript/Interface/IGameCommon.lua Näytä tiedosto

@@ -0,0 +1,51 @@
---
-- ================================================================
-- 文件名: IGameCommon.lua
-- 描述: 子游戏引用大厅接口
-- 作者: Administrator
-- 创建日期: 2020-2-18
-- 更新日期: 2020-2-18
-- 备注:
-- ================================================================
--
local IGameCommon = {};

--[[
获取分享的二维码图片
]]
function IGameCommon.getShareCRCodeTexture(callback)
local clientConfig = app.serverConfigs.clientConfig
local crCodeUrl = clientConfig and clientConfig.qrcode or ""
if crCodeUrl == "" then
showTooltip("未配置二维码地址")
return
end
--download
local urlfile = convertIconUrl(crCodeUrl)
local fileName = getImageNameFromUrl(urlfile)
local fullPath = cc.FileUtils:getInstance():getWritablePath()..fileName;
local isExist = cc.FileSystem:fileExists(fullPath)
if not isExist then
getImageFromUrlWithTime(crCodeUrl, fileName, nil, function()
local texture = loadTextureFromFile(fileName)
if not texture then
logD("IGameCommon getShareCRCodeTexture not found")
return
end
if callback then
callback(texture)
end
end)
else
local texture = loadTextureFromFile(fileName)
if not texture then
logD("IGameCommon getShareCRCodeTexture not found")
return
end
if callback then
callback(texture)
end
end
end

return IGameCommon;

+ 30
- 0
core/luaScript/Interface/IGameOverAward.lua Näytä tiedosto

@@ -0,0 +1,30 @@
---
-- ================================================================
-- 文件名: IGameOverAward.lua
-- 描述: 排名赛抽奖接口
-- 版权: Copyright © 2016-2019 公司名称 版权所有
-- 作者: Administrator
-- 创建日期: 2019-10-22
-- 更新日期: 2019-10-22
-- 备注:
-- ================================================================
--
local IGameOverAward = {}

IGameOverAward.chouJiangData = nil

function IGameOverAward.setAwardData(data)
IGameOverAward.chouJiangData = data
end

function IGameOverAward.showAwardView()
if not IGameOverAward.chouJiangData then
return
end
local view = import("luaScript.Views.Club.Match.ClubMatchChouJiang"):new(IGameOverAward.chouJiangData)
view:setAnchorPoint(cc.p(0.5, 0.5))
app:showWaitDialog(view)
end


return IGameOverAward

+ 245
- 0
core/luaScript/Interface/IPlayGameAgain.lua Näytä tiedosto

@@ -0,0 +1,245 @@
---
-- ================================================================
-- 文件名: IPlayGameAgain.lua
-- 描述: 子游戏结算再来一局功能接口
-- 版权: Copyright © 2016-2019 公司名称 版权所有
-- 作者: Administrator
-- 创建日期: 2019-10-22
-- 更新日期: 2019-10-22
-- 备注:
-- ================================================================
--
local IPlayGameAgain = {};

IPlayGameAgain.isAgainGameBol = false -- 是否再来一局
IPlayGameAgain.wanfa = "" -- 子游戏玩法
IPlayGameAgain.uidList = {} -- 待邀请玩家列表

IPlayGameAgain.isAgainGameBaoJianId = -1 -- 再来一局包间ID
IPlayGameAgain.isAgainGameData = nil -- 再来一局接受邀请数据
IPlayGameAgain.isGameRuleChange = false -- 再来一局包间玩法是否被修改
IPlayGameAgain.gameRoomId = 0 -- 再来一局包间id
IPlayGameAgain.myGameCreateStatus = false -- 玩家是否创建过房间

IPlayGameAgain.inviteView = nil -- 邀请框

function IPlayGameAgain.bindPlayAgainButton (btnPlayAgain, gameId, inviteInfo, inviteList, initCallback)
local clubId = app.club_php.clubID or 0
local isInClub = clubId and clubId ~= 0
if not isInClub then
logD("IPlayGameAgain.initPlayGameAgain", "当前玩家不在亲友圈内,不能再来一局");
btnPlayAgain:setVisible(false)
return
end

if tolua.isnull(btnPlayAgain) then
logD("IPlayGameAgain.bindPlayAgainButton", "再来一局按钮已经被释放")
return
end


local isClosePlayAgain = IPlayGameAgain.isClosePlayAgain(gameId)
btnPlayAgain:setVisible(not isClosePlayAgain)

if isClosePlayAgain then
if type(initCallback) == "function" then
initCallback()
end
return
end

btnPlayAgain:registerClick(function ()
logD("===================inviteList==================:",table.tostring(inviteList))
IPlayGameAgain.setIsAgainGamebol(true, inviteInfo, inviteList)
gotoMainView()
end)

local clubInfo = app.club_php:getClubInfo(clubId)
if not clubInfo then
logD("IPlayGameAgain.bindPlayAgainButton", "亲友圈信息不存在", "clubId:", clubId)
if type(initCallback) == "function" then
initCallback()
end
return
end

local baoJianId = IPlayGameAgain.getAgainGameBaoJianId()
if baoJianId ~= -1 and clubInfo.settings and tonumber(clubInfo.settings.baoJianId) ~= tonumber(baoJianId) and clubInfo.mode == 0 then
app.club_php:requestRuleSet(app.club_php.clubID, baoJianId, 1, 1)
end

if type(initCallback) == "function" then
initCallback()
end
end
---
-- 收到再来一局邀请信息时,弹出邀请弹框
-- @param data
-- @return
--
function IPlayGameAgain.showClubInviteDialog (data, agreeCallback, closeCallback)
--房间邀请通知
local content = data.content
local clubId = data.clubId
local inviteView = IPlayGameAgain.inviteView
local viewType = type(inviteView)
if inviteView and viewType == "userdata" then
--提示框已存在
return
end

local function removeInviteView()
if not tolua.isnull(IPlayGameAgain.inviteView) then
-- IPlayGameAgain.inviteView:removeFromParent()
IPlayGameAgain.inviteView = nil
end
end

local function onBtnCloseClicked()
--关闭提示框时清空数据,用于下次弹出
removeInviteView()
if type(closeCallback) == "function" then
closeCallback()
end
end

local function onBtnAgreeClicked()
removeInviteView()
gotoMainView()
if type(agreeCallback) == "function" then
agreeCallback()
end
end

inviteView = import("luaScript.Views.Club.ClubInviteRoomNew"):new(clubId, content, onBtnCloseClicked, onBtnAgreeClicked)
inviteView:setAnchorPoint(cc.p(0.5, 0.5))
app:showWaitDialog(inviteView,0)

IPlayGameAgain.inviteView = inviteView
end
---
-- 是否关闭再来一局功能
-- 默认关闭
-- @return
--
function IPlayGameAgain.isClosePlayAgain (gameId)
local isClosePlayAgain = true
local config = getSubGameConfig(gameId)
if not config then
logD("IPlayGameAgain.isClosePlayAgain", "读取子游戏配置为空")
return isClosePlayAgain
end

if config.gameDataConfig and config.gameDataConfig.isClosePlayAgain ~= nil then
logD("IPlayGameAgain.isClosePlayAgain", "子游戏再来一局功能已打开")
isClosePlayAgain = config.gameDataConfig.isClosePlayAgain == true
end

return isClosePlayAgain
end

---
-- 设置是否再来一局
-- @param bol 是否再来一局
-- @param wanfadata 子游戏玩法
-- @param uidList 待邀请玩家列表
-- @return
--
function IPlayGameAgain.setIsAgainGamebol(bol, wanfadata, uidList)
logD("IPlayGameAgain.setIsAgainGamebol")
IPlayGameAgain.isAgainGameBol = bol

if wanfadata then
IPlayGameAgain.wanfa = wanfadata
end
if uidList then
IPlayGameAgain.uidList = uidList or {}
end
end
---
-- 是否再来一局
-- @return
--
function IPlayGameAgain.getIsAgainGamebol()
return IPlayGameAgain.isAgainGameBol, IPlayGameAgain.wanfa, IPlayGameAgain.uidList;
end
---
-- 再来一局包间id
-- @param idx
-- @return
--
function IPlayGameAgain.setAgainGameBaoJianId(idx)
IPlayGameAgain.isAgainGameBaoJianId = idx
end
---
-- 获取再来一局包间id
-- @return
--
function IPlayGameAgain.getAgainGameBaoJianId()
return IPlayGameAgain.isAgainGameBaoJianId;
end
---
-- 保存再来一局接受邀请数据
-- @param data
-- @return
--
function IPlayGameAgain.setAgainGameInvitedata(data)
IPlayGameAgain.isAgainGameData = data
end
---
-- 获取再来一局接受邀请数据
-- @return
--
function IPlayGameAgain.getAgainGameInvitedata()
return IPlayGameAgain.isAgainGameData;
end
---
-- 保存再来一局玩法状态
-- 检测点再来一局的时候,玩法是否被修改。如果是修改那么提示创建失败。
-- @param bol
-- @return
--
function IPlayGameAgain.setRuleChangeStatus(bol)
IPlayGameAgain.isGameRuleChange = bol
end
---
-- 获取再来一局玩法状态
-- 检测点再来一局的时候,玩法是否被修改。如果是修改那么提示创建失败。
-- @return
--
function IPlayGameAgain.getRuleChangeStatus()
return IPlayGameAgain.isGameRuleChange
end
---
-- 保存房间id
-- 邀请的时候需要用到数据
-- @param idx
-- @return
--
function IPlayGameAgain.setGameRoomId(idx)
IPlayGameAgain.gameRoomId = idx
end
---
-- 获取房间id
-- @return
--
function IPlayGameAgain.getGameRoomId()
return IPlayGameAgain.gameRoomId;
end
---
-- 保存玩家是否创建过房间
-- @param bol
-- @return
--
function IPlayGameAgain.setMyGameCreateStatus(bol)
IPlayGameAgain.myGameCreateStatus = bol
end
---
-- 获取玩家是否创建过房间
-- @return
--
function IPlayGameAgain.getMyGameCreateStatus()
return IPlayGameAgain.myGameCreateStatus;
end

return IPlayGameAgain;

+ 7
- 0
core/luaScript/Interface/init.lua Näytä tiedosto

@@ -0,0 +1,7 @@

dd = dd or {}

dd.IClub = require("luaScript.Interface.IClub")
dd.IPlayGameAgain = require("luaScript.Interface.IPlayGameAgain");
dd.IGameOverAward = require("luaScript.Interface.IGameOverAward");
dd.IGameCommon = require("luaScript.Interface.IGameCommon");

+ 92
- 0
core/luaScript/MJFramework.lua Näytä tiedosto

@@ -0,0 +1,92 @@
MJFramework={}

local paths={}

local files={}

function MJFramework.MJImport(name,gameId)
local fileName=string.gsub(name, "%.", "/")
local gameConfig = getSubGameConfig(gameId or app.gameId)
local rootName=gameConfig.rootName
local findMjHsb = string.find(name, 'mj_hsb')

-- 判断是否有旧mj_hsb路径
if not findMjHsb then
local newFileName=string.gsub(fileName, "MJ", gameConfig.fileName)
newFileName=string.gsub(newFileName, "mj", rootName)
local newName=string.gsub(name, "MJ", gameConfig.fileName)
newName=string.gsub(newName, "mj", rootName)
local luaFile = newFileName..".lua"
local luacFile = newFileName..".luac"
local isFileExist = cc.FileUtils:getInstance():isFileExist(luacFile)
if not isFileExist then
isFileExist = cc.FileUtils:getInstance():isFileExist(luaFile)
end

if isFileExist then
name=newName
end
else
local newFileName=string.gsub(fileName, "MJ", gameConfig.fileName)
newFileName=string.gsub(newFileName, "mj_hsb", rootName)
local newName=string.gsub(name, "MJ", gameConfig.fileName)
newName=string.gsub(newName, "mj_hsb", rootName)
local luaFile = newFileName..".lua"
local luacFile = newFileName..".luac"
local isFileExist = cc.FileUtils:getInstance():isFileExist(luacFile)
if not isFileExist then
isFileExist = cc.FileUtils:getInstance():isFileExist(luaFile)
end

if isFileExist then
name=newName
end
end

files[name]=true
print("MJImport:"..name)
return require(name)
end

function MJFramework.ImportWanFa(name,gameId)
local fileName=string.gsub(name, "%.", "/")

local gameConfig = getSubGameConfig(gameId or app.gameId)
local rootName=gameConfig.rootName
local newFileName=string.gsub(fileName, "MJ", gameConfig.fileName)
local newName=string.gsub(name, "MJ", gameConfig.fileName)
local luaFile = newFileName..".lua"
local luacFile = newFileName..".luac"
local isFileExist = cc.FileUtils:getInstance():isFileExist(luacFile)
if not isFileExist then
isFileExist = cc.FileUtils:getInstance():isFileExist(luaFile)
end
if isFileExist then
name=newName
end

print("ImportWanFa:"..name)
files[name]=true
return require(name)
end

function MJFramework.Clean()
for fileName,v in pairs(files) do
print("Clean:"..fileName)
package.loaded[fileName] = nil
end
files={}
end

function MJFramework.MJFrameworkClassImprot(name)
print("MJFrameworkClassImprot:"..name)
files[name]=true
return require(name)
end

+ 299
- 0
core/luaScript/Map/Map.lua Näytä tiedosto

@@ -0,0 +1,299 @@
local Map = class("Map");
require("luaScript.Map.MapDrawer")(Map);

Map.ObstacleType =
{
-- 不是障碍块
ObstacleNone = 1,
-- 是障碍块
ObstacleNormal = 0,
}

-- TileWidth
Map.TileWidth = 60
-- tileHeight
Map.TileHeight = 30

-- 构造函数
function Map:ctor()
-- 默认构造一个1136 X 640的地图
-- self:initWidthAndHeight(1136, 640, 60, 30);
-- 障碍信息
self.obstacles = cc.CAStar:new();

-- 当障碍块改变时回调
self.ObstacleChanged = nil;
end

-- 重新计算地图
function Map:recalculate()
self.TileHalfWidth = self.TileWidth / 2;
self.TileHalfHeight = self.TileHeight / 2;
-- 根据地图大小和tile的大小,计算tile的个数以及tile的偏移
local widthLen = math.ceil(self.MapWidth / self.TileWidth);
local heightLen = math.ceil(self.MapHeight / self.TileHeight);
self.TileCountX = widthLen + heightLen;
self.TileCountY = widthLen + heightLen;
-- X轴不需要偏移,只偏移Y轴
self.OffsetX = 0;
self.OffsetY = heightLen;
end

-- 初始化地图的宽度和高度
function Map:initWidthAndHeight(width, height, tileWidth, tileHeight)
self.MapWidth = width;
self.MapHeight = height;
self.TileWidth = tileWidth;
self.TileHeight = tileHeight;
-- 重新计算地图
self:recalculate();
end

-- 初始化障碍块
function Map:initObstacles()
self.obstacles:resize(self.TileCountX , self.TileCountY);
end

-- 增加一个障碍块
-- x y 为逻辑坐标
function Map:addObstacle(x, y)
-- 如果不在地图内则添加不成功
if self:isInMap(x, y) == false or self:isObstacle(x, y) then
return
end
self.obstacles:setBlock(x , y , Map.ObstacleType.ObstacleNormal);
if self.ObstacleChanged then
self.ObstacleChanged(x , y , Map.ObstacleType.ObstacleNormal);
end
end

-- 删除一个障碍块
-- x y 为逻辑坐标
function Map:removeObstacle(x, y)
if self:isInMap(x, y) then
self.obstacles:setBlock(x , y , Map.ObstacleType.ObstacleNone);
if self.ObstacleChanged then
self.ObstacleChanged(x , y , Map.ObstacleType.ObstacleNone);
end
end
end

-- 判断一个点是否是障碍点
-- x y 为逻辑坐标
function Map:isObstacle(x, y)
if self:isInMap(x, y) then
return self.obstacles:isBlock(x,y);
end
return false;
end

-- 根据点的坐标或者障碍数据
function Map:getObstacle(x, y)
if self:isInMap(x, y) == false then
return 0;
end
return self.obstacles:getBlock(x,y);
end

-- 判断一个坐标点是否在地图内
function Map:isInMap(x, y)
if x < 0 or y < 0 then
print("x or y is less 0", "current x is", x, "current y is", y);
return false;
end
if x >= self.TileCountX or y >= self.TileCountY then
print("Map:TileCountX is", self.TileCountX, " current x is", x);
print("Map:TileCountY is", self.TileCountY, " current y is", y);
return false;
end
return true;
end

function Map:loadFromLuaNode(luaNode)
-- 初始化地图数据
self:initWidthAndHeight(tonumber(luaNode.width), tonumber(luaNode.height), tonumber(luaNode.tileWidth), tonumber(luaNode.tileHeight));
if luaNode.mapdata then
-- 兼容老格式
self.obstacles:resize(self.TileCountX , self.TileCountY);
for i , v in pairs(luaNode.mapdata) do
local x = math.floor((i - 1) / self.TileCountY);
local y = (i - 1) % self.TileCountY;
if v == 0 then
self.obstacles:setBlock(x , y , 1);
else
self.obstacles:setBlock(x , y , 0);
end
end
end
end

function Map:saveToXmlNode(xmlNode)
-- 保存tile的偏移
xmlNode.offsetX = self.OffsetX;
xmlNode.offsetY = self.OffsetY;
xmlNode.col = self.TileCountX;
xmlNode.row = self.TileCountY;
-- 保存地图宽高和Tile宽高
xmlNode.width = self.MapWidth;
xmlNode.height = self.MapHeight;
xmlNode.tileWidth = self.TileWidth;
xmlNode.tileHeight = self.TileHeight;
-- 保存障碍块
local obstaclesStr;
local singleObstacleStr;
-- 将障碍信息压成一个字符串
for x = 0, self.TileCountX - 1 do
for y = 0, self.TileCountY - 1 do
local obstacle = self:getObstacle(x, y);
-- 障碍信息
if obstacle == 0 then
singleObstacleStr = "1";
else
singleObstacleStr = "0";
end
-- 开始直接赋值,否则叠加
if obstaclesStr == nil then
obstaclesStr = {singleObstacleStr};
else
table.insert(obstaclesStr , "," .. singleObstacleStr);
end
end
end
xmlNode.mapdata = table.concat(obstaclesStr);
end

function Map:createXmlNode()
local xmlNode = xml.new("map");
self:saveToXmlNode(xmlNode);
return xmlNode;
end

-- 保存一个地图到XML文件
function Map:saveXml(fullFilePath)
local xmlNode = self:createXmlNode();
xmlNode:save(fullFilePath);
end

-- 保存一个地图到lua文件
function Map:saveLua(fullFilePath)

local luaNode = {}
-- 保存tile的偏移
luaNode.offsetX = self.OffsetX;
luaNode.offsetY = self.OffsetY;
luaNode.col = self.TileCountX;
luaNode.row = self.TileCountY;
-- 保存地图宽高和Tile宽高
luaNode.width = self.MapWidth;
luaNode.height = self.MapHeight;
luaNode.tileWidth = self.TileWidth;
luaNode.tileHeight = self.TileHeight;
self.obstacles:saveToFile(fullFilePath .. ".blocks");

table.saveFile(luaNode , fullFilePath);
end

-- 载入一个地图文件
function Map:loadLua(luaFile)
print("加载map:" , luaFile);
local xmlFile = table.loadFile(luaFile);
if xmlFile then
self:loadFromLuaNode(xmlFile);
if not xmlFile.mapdata then
self.obstacles:loadFromFile(luaFile .. ".blocks");
end

end
print("map 加载完成");
end

-- 载入一个地图文件
function Map:loadXml(nodeFile)
local xmlFile = loadXmlFileWithCache(nodeFile);
if xmlFile then
self:loadFromXmlNode(xmlFile:find("map"));
end
end
--
-- 获取45度A*单元格矩阵坐标
-- @param px 目标点X坐标
-- @param py 目标点Y坐标
-- @return {@link Position} 矩阵点坐标
function Map:getTilePosition(px, py)
-- 界面坐标 计算以屏幕左上为原点的世界坐标
local logicalx = px / (2 * self.TileHalfWidth) + (-py) / (2 * self.TileHalfHeight) + self.OffsetX;
local logicaly = px / (2 * self.TileHalfWidth) - (-py) / (2 * self.TileHalfHeight) + self.OffsetY;
return cc.p(math.floor(logicalx), math.floor(logicaly));
end

--
-- 获取45度A*单元格矩阵坐标(不对齐到网格)
-- @param px 目标点X坐标
-- @param py 目标点Y坐标
-- @return {@link Position} 矩阵点坐标
function Map:_getTilePosition(px, py)
-- 界面坐标 计算以屏幕左上为原点的世界坐标
local logicalx = px / (2 * self.TileHalfWidth) + (-py) / (2 * self.TileHalfHeight) + self.OffsetX;
local logicaly = px / (2 * self.TileHalfWidth) - (-py) / (2 * self.TileHalfHeight) + self.OffsetY;
return cc.p(logicalx, logicaly);
end

--
-- 获取45度A*单元格矩阵坐标转舞台从标(获得的是格子的中心点坐标)
-- @param px 舞台X坐标
-- @param py 舞台Y坐标
-- @return {@link Position} 矩阵点坐标
function Map:getPixelPosition(tileX, tileY)
local nOffX = tileX - self.OffsetX;
local nOffY = tileY - self.OffsetY;
local positionX = nOffX * self.TileHalfWidth + nOffY * self.TileHalfWidth; -- 斜坐标 x每加1 竖坐标x+1/2 y+1/2
local positionY = nOffX * self.TileHalfHeight - nOffY * self.TileHalfHeight; -- 斜坐标 y每加1 竖坐标x+1/2 y-1/2
return cc.p(positionX, -positionY);
end

-- 载入场景文件
function loadScene(nodeFile)
print("加载场景" , nodeFile);
TimeSpan:enterSpan("loadScene" .. nodeFile);

TimeSpan:enterSpan("createNodeFromFile");
print("加载模型");
LoadingScene = true;
local node = cc.StreamObject:loadFromFile(nodeFile);
LoadingScene = false;
node:setCollectAnimationClip(false);
TimeSpan:leaveSpan();
if not EditorMode then
-- 普通模式,屏蔽掉HD内容
local hd = node:findNode("HD");
if hd then
local function onQualityChanged(key , value)
-- 高质量
hd:setVisible(value == 1);
end
hd:bind(app.systemSetting.info , "graphicQuality" , onQualityChanged);
end
end

-- 创建一个题图载入资源
TimeSpan:enterSpan("requireMap");
print("加载障碍块");
local map = require("luaScript.Map.Map"):new();
local arr = string.split(nodeFile, ".");
map:loadLua(arr[1] .. ".lmap");
TimeSpan:leaveSpan();

TimeSpan:leaveSpan();
return node , map;
end

return Map;

+ 133
- 0
core/luaScript/Map/MapDrawer.lua Näytä tiedosto

@@ -0,0 +1,133 @@
return function(Map)
-- 创建地图菱形网格
function Map:createGridNode()
local vertexFormat = {};
table.insert(vertexFormat , {size = 3 , usage = cc.VertexFormatUsage.POSITION});
table.insert(vertexFormat , {size = 4 , usage = cc.VertexFormatUsage.COLOR});
local vertices = ManualVertices:new(vertexFormat);
vertices:setColor(cc.c4f(0,0,1,0.5));
-- 画菱形

-- 画横轴
for x = 0, self.TileCountX do
local begin_ = self:getPixelPosition(x,0);
local end_ = self:getPixelPosition(x,self.TileCountY);
vertices:drawLine(cc.vec3(begin_.x , 0 , begin_.y) , cc.vec3(end_.x , 0 , end_.y))
end
-- 画纵轴
for y = 0, self.TileCountY do
local begin_ = self:getPixelPosition(0,y);
local end_ = self:getPixelPosition(self.TileCountX,y);
vertices:drawLine(cc.vec3(begin_.x , 0 , begin_.y) , cc.vec3(end_.x , 0 , end_.y))
end

-- 画一个矩形
vertices:drawLine(cc.vec3(0,0,0), cc.vec3(self.MapWidth,0,0));
vertices:drawLine(cc.vec3(self.MapWidth,0,0), cc.vec3(self.MapWidth,0, -self.MapHeight));
vertices:drawLine(cc.vec3(self.MapWidth,0, -self.MapHeight), cc.vec3(0,0,-self.MapHeight));
vertices:drawLine(cc.vec3(0,0,0), cc.vec3(0,0,-self.MapHeight));

local mesh = cc.Mesh:createMesh(vertexFormat , vertices:getVertexCount());
mesh:setPrimitiveType(cc.PrimitiveType.LINES);
mesh:setVertexData(vertices:getVertices() , 0 , vertices:getVertexCount());
mesh:setBoundingBox(vertices:getBoundingBox());

local model = cc.Model:create(mesh);
local material = cc.Material:create("preload/shaders/ccDefault.material#ShaderPositionColor3D");
material:setParameterAutoBinding("CC_MVPMatrix" , "WORLD_VIEW_PROJECTION_MATRIX");
model:setMaterialPointer(material);
local node = cc.Node3D:create();
node:addComponent(model);

return node;
end

-- 创建网格上的文本
function Map:createTextNode()
local node = cc.Node:create();
-- 横轴
for x = 0, self.TileCountX do
-- 纵轴
for y = 0, self.TileCountY do
local pos = self:getPixelPosition(x,y);
local debugLabel = cc.Text:createNode();
debugLabel:setDefaults();
local config = debugLabel:getFontConfig();
config.fontSize = 12;
debugLabel:setFontConfig(config);

debugLabel:setAnchorPoint(cc.p(0.5,0.5));
debugLabel:setTranslation(pos.x , 0 , pos.y);
debugLabel:setEulerRotation(-90,0,0);
debugLabel:setScale(0.03);
-- TODO这里需要显示逻辑坐标就可以了
debugLabel:setText(tostring(x) .. "," .. tostring(y));
node:addChild(debugLabel);
end
end
return node;
end

-- 创建障碍块和可见区域
function Map:createObstacleNode()
local node = cc.Node3D:create();
-- 画障碍块
local vertexFormat = {};
table.insert(vertexFormat , {size = 3 , usage = cc.VertexFormatUsage.POSITION});
table.insert(vertexFormat , {size = 4 , usage = cc.VertexFormatUsage.COLOR});

local material = cc.Material:create("preload/shaders/ccDefault.material#ShaderPositionColor3D");
material:setParameterAutoBinding("CC_MVPMatrix" , "WORLD_VIEW_PROJECTION_MATRIX");
local mesh = cc.MeshBatch:create(vertexFormat , cc.PrimitiveType.TRIANGLES , material , false);
node:addComponent(mesh);

local function drawOb(vertices , x , y)
local leftTop = self:getPixelPosition(x,y);
local rightTop = self:getPixelPosition(x + 1,y);
local leftBottom = self:getPixelPosition(x,y + 1);
local rightBottom = self:getPixelPosition(x + 1,y + 1);
vertices:drawRect(cc.vec3(leftTop.x , 0 , leftTop.y)
, cc.vec3(rightTop.x , 0 , rightTop.y)
, cc.vec3(leftBottom.x , 0 , leftBottom.y)
, cc.vec3(rightBottom.x , 0 , rightBottom.y));
end

-- 更新障碍块的顶点信息
local function updateObstacle()
local vertices = ManualVertices:new(vertexFormat);
local x , y;
-- 画障碍块
for y = 0 , self.TileCountY - 1 do
for x = 0 , self.TileCountX - 1 do
if self.obstacles:isBlock(x,y) then
vertices:setColor(cc.c4f(1,1,0,1));
else
vertices:setColor(cc.c4f(0,0,0,0));
end
drawOb(vertices , x , y);
end
end
mesh:start();
mesh:add(vertices:getVertices() , vertices:getVertexCount());
mesh:finish();
end

-- 更新一个障碍块
local function updateOne(x , y , val)
local vertices = ManualVertices:new(vertexFormat);
if val ~= Map.ObstacleType.ObstacleNone then
vertices:setColor(cc.c4f(1,1,0,1));
else
vertices:setColor(cc.c4f(0,0,0,0));
end
drawOb(vertices , x , y);
mesh:updateVertex((self.TileCountX * y + x) * vertices:getVertexCount() , vertices:getVertexCount() , vertices:getVertices());
end

self.ObstacleChanged = updateOne;

updateObstacle();
return node;
end
end

+ 22
- 0
core/luaScript/ModuleEapSdk/AdapterEapSdk.lua Näytä tiedosto

@@ -0,0 +1,22 @@

-- 获取设备唯一ID
cc.exports.F_EapGetDeviceID = function()
-- return G_DeviceData.getMacAddress()
if isWin32Platform() then
return "F_EapGetMacAddress_" .. app.user.loginInfo.uid
--return "F_EapGetMacAddress_" .. Math.random(1000, 9999)
end
return getDeviceID()
end
-- 打印
cc.exports.F_EapPrint = function(...)
print(...)
end
-- 跳转网页
cc.exports.F_EapOpenUrl = function(url)
-- G_DeviceData.goToUrl(url)
app.plugin:callUrl(url)
print("F_EapOpenUrl = ", url)
end
-- 初始化json库 require("cjson") or require("JSON") or require("json")
cc.exports.G_EapSdkJson = require("json")

+ 58
- 0
core/luaScript/ModuleEapSdk/BaseCommon/BaseCommon.lua Näytä tiedosto

@@ -0,0 +1,58 @@
local BaseCommon = BaseCommon or {}

-- event
function BaseCommon.DispatchCustomEvent(__name, __data, __cmd)
if (not __name) then
assert(false, "BaseCommon.DispatchCustomEvent __name is null")
end
local event = cc.EventCustom:new(__name)
event._usedata = __data
event._cmd = __cmd
cc.Director:getInstance():getEventDispatcher():dispatchEvent(event)
end

function BaseCommon.AddCustomEvent(__node, __eventName, __handler)
if (not __eventName) then
assert(false, "BaseCommon.AddCustomEvent __eventName is null")
end
local listener = cc.EventListenerCustom:create(__eventName, __handler)
cc.Director:getInstance():getEventDispatcher():addEventListenerWithSceneGraphPriority(listener, __node)
return listener
end

function BaseCommon.AddFixedCustomEvent(__eventName, __handler)
local listener = cc.EventListenerCustom:create(__eventName, __handler)
cc.Director:getInstance():getEventDispatcher():addEventListenerWithFixedPriority(listener, 1)
return listener
end

function BaseCommon.RemoveFixedCustomEvent(__listener)
cc.Director:getInstance():getEventDispatcher():removeEventListener(__listener)
end

-- const table
function BaseCommon.NewConst( const_table )
local function Const( const_table )
local mt =
{
__index = function (t,k)
if type(const_table[k])=="table" then
const_table[k] = BaseCommon.NewConst(const_table[k])
end
return const_table[k]
end,
__newindex = function (t,k,v)
error("can't update " .. tostring(t) .."[" .. tostring(k) .."] = " .. tostring(v))
-- dump(t)
end
}
return mt
end

local t = {}
setmetatable(t, Const(const_table))
return t
end


return BaseCommon

+ 12
- 0
core/luaScript/ModuleEapSdk/BaseCommon/BaseEvent.lua Näytä tiedosto

@@ -0,0 +1,12 @@
--
-- Author: songge
-- Date: 2016-03-29 14:47:07
-- define event name


local BaseEvent = BaseEvent or {}

BaseEvent.APP_CPP_EVENT_NETWORK_STATE = "APP_CPP_EVENT_NETWORK_STATE" --获取网络连接状态,勿修改
BaseEvent.EVENT_LOADING_CLOSE = "EVENT_LOADING_CLOSE"

return BaseEvent

+ 84
- 0
core/luaScript/ModuleEapSdk/BaseLayers/BaseLayer.lua Näytä tiedosto

@@ -0,0 +1,84 @@
--
-- Author: songge
-- Date: 2016-03-29 14:05:47
-- 整个layer的基类,所有的layer都需要继承这个类。

local BaseLayer = EapClass("BaseLayer", function ()
return cc.Layer:create() -- 继承layer
end)

function BaseLayer:ctor(...)
self:enableNodeEvents()
self:onShow(...)
end

function BaseLayer:onShow(...)
print("baselayer is inited")
self:myShow(...)
end
function BaseLayer:onExit()
print("baselayer is onExit")
if (not self._cleanBaseOver) then
self._cleanBaseOver = true
self:myClose()
end
end
function BaseLayer:closeShowLayer()
self._cleanBaseOver = true
self:myClose()
self:removeFromParent()
end
function BaseLayer:myShow(...)
assert(false, "myShow this method must be inherited") --这个方法必须被重写
end
function BaseLayer:myClose()
assert(false, "myClose this method must be inherited") --这个方法必须被重写
end
-- listener
function BaseLayer:addListener(__noswallow)
print("BaseLayer:addListener successed")
self._listener = cc.EventListenerTouchOneByOne:create()
if (__noswallow) then
self._listener:setSwallowTouches(false)
else
self._listener:setSwallowTouches(true)
end
self._listener:registerScriptHandler(handler(self,self.onTouchBegin),cc.Handler.EVENT_TOUCH_BEGAN);
self._listener:registerScriptHandler(handler(self,self.onTouchMove),cc.Handler.EVENT_TOUCH_MOVED);
self._listener:registerScriptHandler(handler(self,self.onTouchEnd),cc.Handler.EVENT_TOUCH_ENDED);
self._listener:registerScriptHandler(handler(self,self.onTouchCancel),cc.Handler.EVENT_TOUCH_CANCELLED);
cc.Director:getInstance():getEventDispatcher():addEventListenerWithSceneGraphPriority(self._listener,self);
end
function BaseLayer:removeListener()
if self._listener then
cc.Director:getInstance():getEventDispatcher():removeEventListener(self._listener);
self._listener = nil
end
end

--touch
function BaseLayer:onTouchBegin(__touch,__event)
--local _p = __touch:getLocation();
--print("BaseLayer:onTouchBegin",_p.x,_p.y)
return true;
end

function BaseLayer:onTouchMove(__touch,__event)
end

function BaseLayer:onTouchEnd(__touch,__event)
end
function BaseLayer:onTouchCancel(__touch,__eventt)
end
function BaseLayer:onCleanup()
print("BaseLayer:onCleanup ")
self:removeListener()
end

function BaseLayer:setListenerEnable(__state)
if self._listener then
self._listener:setEnabled(__state)
end
end

return BaseLayer--BaseLayer_lua--BaseLayer.lua

+ 1053
- 0
core/luaScript/ModuleEapSdk/EapFunc/EapJson.lua
File diff suppressed because it is too large
Näytä tiedosto


+ 28
- 0
core/luaScript/ModuleEapSdk/EapFunc/config.lua Näytä tiedosto

@@ -0,0 +1,28 @@

-- 0 - disable debug info, 1 - less debug info, 2 - verbose debug info
DEBUG = 2

-- use framework, will disable all deprecated API, false - use legacy API
CC_USE_FRAMEWORK = true

-- show FPS on screen
CC_SHOW_FPS = true

-- disable create unexpected global variable
CC_DISABLE_GLOBAL = false

-- for module display
CC_DESIGN_RESOLUTION = {
width = 1280,
height = 720,
autoscale = "FIXED_WIDTH",
callback = function(framesize)
local ratio = framesize.width / framesize.height
if ratio <= 1.34 then
-- iPad 768*1024(1536*2048) is 4:3 screen
return {autoscale = "FIXED_WIDTH"}
elseif ratio > 1.775 then
return {autoscale = "FIXED_HEIGHT"}
end
end
}--config_lua--config.lua

+ 207
- 0
core/luaScript/ModuleEapSdk/EapFunc/framework/audio.lua Näytä tiedosto

@@ -0,0 +1,207 @@
--[[

Copyright (c) 2011-2014 chukong-inc.com

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.

]]

local audio = {}

local engine = cc.SimpleAudioEngine:getInstance()

function audio.getMusicVolume()
local volume = engine:getMusicVolume()
if DEBUG > 1 then
printf("[audio] getMusicVolume() - volume: %0.2f", volume)
end
return volume
end

function audio.setMusicVolume(volume)
volume = checknumber(volume)
if DEBUG > 1 then
printf("[audio] setMusicVolume() - volume: %0.2f", volume)
end
engine:setMusicVolume(volume)
end

function audio.preloadMusic(filename)
assert(filename, "audio.preloadMusic() - invalid filename")
if DEBUG > 1 then
printf("[audio] preloadMusic() - filename: %s", tostring(filename))
end
engine:preloadMusic(filename)
end

function audio.playMusic(filename, isLoop)
assert(filename, "audio.playMusic() - invalid filename")
if type(isLoop) ~= "boolean" then isLoop = true end

audio.stopMusic()
if DEBUG > 1 then
printf("[audio] playMusic() - filename: %s, isLoop: %s", tostring(filename), tostring(isLoop))
end
engine:playMusic(filename, isLoop)
end

function audio.stopMusic(isReleaseData)
isReleaseData = checkbool(isReleaseData)
if DEBUG > 1 then
printf("[audio] stopMusic() - isReleaseData: %s", tostring(isReleaseData))
end
engine:stopMusic(isReleaseData)
end

function audio.pauseMusic()
if DEBUG > 1 then
printf("[audio] pauseMusic()")
end
engine:pauseMusic()
end

function audio.resumeMusic()
if DEBUG > 1 then
printf("[audio] resumeMusic()")
end
engine:resumeMusic()
end

function audio.rewindMusic()
if DEBUG > 1 then
printf("[audio] rewindMusic()")
end
engine:rewindMusic()
end

function audio.isMusicPlaying()
local ret = engine:isMusicPlaying()
if DEBUG > 1 then
printf("[audio] isMusicPlaying() - ret: %s", tostring(ret))
end
return ret
end

function audio.getSoundsVolume()
local volume = engine:getEffectsVolume()
if DEBUG > 1 then
printf("[audio] getSoundsVolume() - volume: %0.1f", volume)
end
return volume
end

function audio.setSoundsVolume(volume)
volume = checknumber(volume)
if DEBUG > 1 then
printf("[audio] setSoundsVolume() - volume: %0.1f", volume)
end
engine:setEffectsVolume(volume)
end

function audio.playSound(filename, isLoop)
if not filename then
printError("audio.playSound() - invalid filename")
return
end
if type(isLoop) ~= "boolean" then isLoop = false end
if DEBUG > 1 then
--printf("[audio] playSound() - filename: %s, isLoop: %s", tostring(filename), tostring(isLoop))
end
return engine:playEffect(filename, isLoop)
end

function audio.pauseSound(handle)
if not handle then
printError("audio.pauseSound() - invalid handle")
return
end
if DEBUG > 1 then
printf("[audio] pauseSound() - handle: %s", tostring(handle))
end
engine:pauseEffect(handle)
end

function audio.pauseAllSounds()
if DEBUG > 1 then
printf("[audio] pauseAllSounds()")
end
engine:pauseAllEffects()
end

function audio.resumeSound(handle)
if not handle then
printError("audio.resumeSound() - invalid handle")
return
end
if DEBUG > 1 then
printf("[audio] resumeSound() - handle: %s", tostring(handle))
end
engine:resumeEffect(handle)
end

function audio.resumeAllSounds()
if DEBUG > 1 then
printf("[audio] resumeAllSounds()")
end
engine:resumeAllEffects()
end

function audio.stopSound(handle)
if not handle then
printError("audio.stopSound() - invalid handle")
return
end
if DEBUG > 1 then
printf("[audio] stopSound() - handle: %s", tostring(handle))
end
engine:stopEffect(handle)
end

function audio.stopAllSounds()
if DEBUG > 1 then
printf("[audio] stopAllSounds()")
end
engine:stopAllEffects()
end
audio.stopAllEffects = audio.stopAllSounds

function audio.preloadSound(filename)
if not filename then
printError("audio.preloadSound() - invalid filename")
return
end
if DEBUG > 1 then
printf("[audio] preloadSound() - filename: %s", tostring(filename))
end
engine:preloadEffect(filename)
end

function audio.unloadSound(filename)
if not filename then
printError("audio.unloadSound() - invalid filename")
return
end
if DEBUG > 1 then
printf("[audio] unloadSound() - filename: %s", tostring(filename))
end
engine:unloadEffect(filename)
end

return audio
--audio_lua--audio.lua

+ 158
- 0
core/luaScript/ModuleEapSdk/EapFunc/framework/components/event.lua Näytä tiedosto

@@ -0,0 +1,158 @@

local Event = EapClass("Event")

local EXPORTED_METHODS = {
"addEventListener",
"dispatchEvent",
"removeEventListener",
"removeEventListenersByTag",
"removeEventListenersByEvent",
"removeAllEventListeners",
"hasEventListener",
"dumpAllEventListeners",
}

function Event:init_()
self.target_ = nil
self.listeners_ = {}
self.nextListenerHandleIndex_ = 0
end

function Event:bind(target)
self:init_()
cc.setmethods(target, self, EXPORTED_METHODS)
self.target_ = target
end

function Event:unbind(target)
cc.unsetmethods(target, EXPORTED_METHODS)
self:init_()
end

function Event:on(eventName, listener, tag)
assert(type(eventName) == "string" and eventName ~= "",
"Event:addEventListener() - invalid eventName")
eventName = string.upper(eventName)
if self.listeners_[eventName] == nil then
self.listeners_[eventName] = {}
end

self.nextListenerHandleIndex_ = self.nextListenerHandleIndex_ + 1
local handle = tostring(self.nextListenerHandleIndex_)
tag = tag or ""
self.listeners_[eventName][handle] = {listener, tag}

if DEBUG > 1 then
printInfo("%s [Event] addEventListener() - event: %s, handle: %s, tag: \"%s\"",
tostring(self.target_), eventName, handle, tostring(tag))
end

return self.target_, handle
end

Event.addEventListener = Event.on

function Event:dispatchEvent(event)
event.name = string.upper(tostring(event.name))
local eventName = event.name
if DEBUG > 1 then
printInfo("%s [Event] dispatchEvent() - event %s", tostring(self.target_), eventName)
end

if self.listeners_[eventName] == nil then return end
event.target = self.target_
event.stop_ = false
event.stop = function(self)
self.stop_ = true
end

for handle, listener in pairs(self.listeners_[eventName]) do
if DEBUG > 1 then
printInfo("%s [Event] dispatchEvent() - dispatching event %s to listener %s", tostring(self.target_), eventName, handle)
end
-- listener[1] = listener
-- listener[2] = tag
event.tag = listener[2]
listener[1](event)
if event.stop_ then
if DEBUG > 1 then
printInfo("%s [Event] dispatchEvent() - break dispatching for event %s", tostring(self.target_), eventName)
end
break
end
end

return self.target_
end

function Event:removeEventListener(handleToRemove)
for eventName, listenersForEvent in pairs(self.listeners_) do
for handle, _ in pairs(listenersForEvent) do
if handle == handleToRemove then
listenersForEvent[handle] = nil
if DEBUG > 1 then
printInfo("%s [Event] removeEventListener() - remove listener [%s] for event %s", tostring(self.target_), handle, eventName)
end
return self.target_
end
end
end

return self.target_
end

function Event:removeEventListenersByTag(tagToRemove)
for eventName, listenersForEvent in pairs(self.listeners_) do
for handle, listener in pairs(listenersForEvent) do
-- listener[1] = listener
-- listener[2] = tag
if listener[2] == tagToRemove then
listenersForEvent[handle] = nil
if DEBUG > 1 then
printInfo("%s [Event] removeEventListener() - remove listener [%s] for event %s", tostring(self.target_), handle, eventName)
end
end
end
end

return self.target_
end

function Event:removeEventListenersByEvent(eventName)
self.listeners_[string.upper(eventName)] = nil
if DEBUG > 1 then
printInfo("%s [Event] removeAllEventListenersForEvent() - remove all listeners for event %s", tostring(self.target_), eventName)
end
return self.target_
end

function Event:removeAllEventListeners()
self.listeners_ = {}
if DEBUG > 1 then
printInfo("%s [Event] removeAllEventListeners() - remove all listeners", tostring(self.target_))
end
return self.target_
end

function Event:hasEventListener(eventName)
eventName = string.upper(tostring(eventName))
local t = self.listeners_[eventName]
for _, __ in pairs(t) do
return true
end
return false
end

function Event:dumpAllEventListeners()
print("---- Event:dumpAllEventListeners() ----")
for name, listeners in pairs(self.listeners_) do
printf("-- event: %s", name)
for handle, listener in pairs(listeners) do
printf("-- listener: %s, handle: %s", tostring(listener[1]), tostring(handle))
end
end
return self.target_
end

return Event
--event_lua--event.lua

+ 108
- 0
core/luaScript/ModuleEapSdk/EapFunc/framework/device.lua Näytä tiedosto

@@ -0,0 +1,108 @@
--[[

Copyright (c) 2011-2014 chukong-inc.com

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.

]]

local device = {}

device.platform = "unknown"
device.model = "unknown"

local app = cc.Application:getInstance()
local target = app:getTargetPlatform()
if target == cc.PLATFORM_OS_WINDOWS then
device.platform = "windows"
elseif target == cc.PLATFORM_OS_MAC then
device.platform = "mac"
elseif target == cc.PLATFORM_OS_ANDROID then
device.platform = "android"
elseif target == cc.PLATFORM_OS_IPHONE or target == cc.PLATFORM_OS_IPAD then
device.platform = "ios"
local director = cc.Director:getInstance()
local view = director:getOpenGLView()
local framesize = view:getFrameSize()
local w, h = framesize.width, framesize.height
if w == 640 and h == 960 then
device.model = "iphone 4"
elseif w == 640 and h == 1136 then
device.model = "iphone 5"
elseif w == 750 and h == 1334 then
device.model = "iphone 6"
elseif w == 1242 and h == 2208 then
device.model = "iphone 6 plus"
elseif w == 768 and h == 1024 then
device.model = "ipad"
elseif w == 1536 and h == 2048 then
device.model = "ipad retina"
end
elseif target == cc.PLATFORM_OS_WINRT then
device.platform = "winrt"
elseif target == cc.PLATFORM_OS_WP8 then
device.platform = "wp8"
end

local language_ = app:getCurrentLanguage()
if language_ == cc.LANGUAGE_CHINESE then
language_ = "cn"
elseif language_ == cc.LANGUAGE_FRENCH then
language_ = "fr"
elseif language_ == cc.LANGUAGE_ITALIAN then
language_ = "it"
elseif language_ == cc.LANGUAGE_GERMAN then
language_ = "gr"
elseif language_ == cc.LANGUAGE_SPANISH then
language_ = "sp"
elseif language_ == cc.LANGUAGE_RUSSIAN then
language_ = "ru"
elseif language_ == cc.LANGUAGE_KOREAN then
language_ = "kr"
elseif language_ == cc.LANGUAGE_JAPANESE then
language_ = "jp"
elseif language_ == cc.LANGUAGE_HUNGARIAN then
language_ = "hu"
elseif language_ == cc.LANGUAGE_PORTUGUESE then
language_ = "pt"
elseif language_ == cc.LANGUAGE_ARABIC then
language_ = "ar"
else
language_ = "en"
end

device.language = language_
device.writablePath = cc.FileUtils:getInstance():getWritablePath()
device.directorySeparator = "/"
device.pathSeparator = ":"
if device.platform == "windows" then
device.directorySeparator = "\\"
device.pathSeparator = ";"
end

printInfo("# device.platform = " .. device.platform)
printInfo("# device.model = " .. device.model)
printInfo("# device.language = " .. device.language)
printInfo("# device.writablePath = " .. device.writablePath)
printInfo("# device.directorySeparator = " .. device.directorySeparator)
printInfo("# device.pathSeparator = " .. device.pathSeparator)
printInfo("#")

return device
--device_lua--device.lua

+ 547
- 0
core/luaScript/ModuleEapSdk/EapFunc/framework/display.lua Näytä tiedosto

@@ -0,0 +1,547 @@
--[[

Copyright (c) 2011-2014 chukong-inc.com

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.

]]

local display = {}

local director = cc.Director:getInstance()
local view = director:getOpenGLView()

if not view then
local width = 960
local height = 640
if CC_DESIGN_RESOLUTION then
if CC_DESIGN_RESOLUTION.width then
width = CC_DESIGN_RESOLUTION.width
end
if CC_DESIGN_RESOLUTION.height then
height = CC_DESIGN_RESOLUTION.height
end
end
view = cc.GLViewImpl:createWithRect("Cocos2d-Lua", cc.rect(0, 0, width, height))
director:setOpenGLView(view)
end

local framesize = view:getFrameSize()
local textureCache = director:getTextureCache()
local spriteFrameCache = cc.SpriteFrameCache:getInstance()
local animationCache = cc.AnimationCache:getInstance()

-- auto scale
local function checkResolution(r)
r.width = checknumber(r.width)
r.height = checknumber(r.height)
r.autoscale = string.upper(r.autoscale)
assert(r.width > 0 and r.height > 0,
string.format("display - invalid design resolution size %d, %d", r.width, r.height))
end

local function setDesignResolution(r, framesize)
if r.autoscale == "FILL_ALL" then
view:setDesignResolutionSize(framesize.width, framesize.height, cc.ResolutionPolicy.FILL_ALL)
else
local scaleX, scaleY = framesize.width / r.width, framesize.height / r.height
local width, height = framesize.width, framesize.height
if r.autoscale == "FIXED_WIDTH" then
width = framesize.width / scaleX
height = framesize.height / scaleX
view:setDesignResolutionSize(width, height, cc.ResolutionPolicy.NO_BORDER)
elseif r.autoscale == "FIXED_HEIGHT" then
width = framesize.width / scaleY
height = framesize.height / scaleY
view:setDesignResolutionSize(width, height, cc.ResolutionPolicy.NO_BORDER)
elseif r.autoscale == "EXACT_FIT" then
view:setDesignResolutionSize(r.width, r.height, cc.ResolutionPolicy.EXACT_FIT)
elseif r.autoscale == "NO_BORDER" then
view:setDesignResolutionSize(r.width, r.height, cc.ResolutionPolicy.NO_BORDER)
elseif r.autoscale == "SHOW_ALL" then
view:setDesignResolutionSize(r.width, r.height, cc.ResolutionPolicy.SHOW_ALL)
else
printError(string.format("display - invalid r.autoscale \"%s\"", r.autoscale))
end
end
end

local function setConstants()
local sizeInPixels = view:getFrameSize()
display.sizeInPixels = {width = sizeInPixels.width, height = sizeInPixels.height}

local viewsize = director:getWinSize()
display.contentScaleFactor = director:getContentScaleFactor()
display.size = {width = viewsize.width, height = viewsize.height}
display.width = display.size.width
display.height = display.size.height
display.cx = display.width / 2
display.cy = display.height / 2
display.c_left = -display.width / 2
display.c_right = display.width / 2
display.c_top = display.height / 2
display.c_bottom = -display.height / 2
display.left = 0
display.right = display.width
display.top = display.height
display.bottom = 0
display.center = cc.p(display.cx, display.cy)
display.left_top = cc.p(display.left, display.top)
display.left_bottom = cc.p(display.left, display.bottom)
display.left_center = cc.p(display.left, display.cy)
display.right_top = cc.p(display.right, display.top)
display.right_bottom = cc.p(display.right, display.bottom)
display.right_center = cc.p(display.right, display.cy)
display.top_center = cc.p(display.cx, display.top)
display.top_bottom = cc.p(display.cx, display.bottom)

printInfo(string.format("# display.sizeInPixels = {width = %0.2f, height = %0.2f}", display.sizeInPixels.width, display.sizeInPixels.height))
printInfo(string.format("# display.size = {width = %0.2f, height = %0.2f}", display.size.width, display.size.height))
printInfo(string.format("# display.contentScaleFactor = %0.2f", display.contentScaleFactor))
printInfo(string.format("# display.width = %0.2f", display.width))
printInfo(string.format("# display.height = %0.2f", display.height))
printInfo(string.format("# display.cx = %0.2f", display.cx))
printInfo(string.format("# display.cy = %0.2f", display.cy))
printInfo(string.format("# display.left = %0.2f", display.left))
printInfo(string.format("# display.right = %0.2f", display.right))
printInfo(string.format("# display.top = %0.2f", display.top))
printInfo(string.format("# display.bottom = %0.2f", display.bottom))
printInfo(string.format("# display.c_left = %0.2f", display.c_left))
printInfo(string.format("# display.c_right = %0.2f", display.c_right))
printInfo(string.format("# display.c_top = %0.2f", display.c_top))
printInfo(string.format("# display.c_bottom = %0.2f", display.c_bottom))
printInfo(string.format("# display.center = {x = %0.2f, y = %0.2f}", display.center.x, display.center.y))
printInfo(string.format("# display.left_top = {x = %0.2f, y = %0.2f}", display.left_top.x, display.left_top.y))
printInfo(string.format("# display.left_bottom = {x = %0.2f, y = %0.2f}", display.left_bottom.x, display.left_bottom.y))
printInfo(string.format("# display.left_center = {x = %0.2f, y = %0.2f}", display.left_center.x, display.left_center.y))
printInfo(string.format("# display.right_top = {x = %0.2f, y = %0.2f}", display.right_top.x, display.right_top.y))
printInfo(string.format("# display.right_bottom = {x = %0.2f, y = %0.2f}", display.right_bottom.x, display.right_bottom.y))
printInfo(string.format("# display.right_center = {x = %0.2f, y = %0.2f}", display.right_center.x, display.right_center.y))
printInfo(string.format("# display.top_center = {x = %0.2f, y = %0.2f}", display.top_center.x, display.top_center.y))
printInfo(string.format("# display.top_bottom = {x = %0.2f, y = %0.2f}", display.top_bottom.x, display.top_bottom.y))
printInfo("#")
end

function display.setAutoScale(configs)
if type(configs) ~= "table" then return end

checkResolution(configs)
if type(configs.callback) == "function" then
local c = configs.callback(framesize)
for k, v in pairs(c or {}) do
configs[k] = v
end
checkResolution(configs)
end

setDesignResolution(configs, framesize)

printInfo(string.format("# design resolution size = {width = %0.2f, height = %0.2f}", configs.width, configs.height))
printInfo(string.format("# design resolution autoscale = %s", configs.autoscale))
setConstants()
end

if type(CC_DESIGN_RESOLUTION) == "table" then
display.setAutoScale(CC_DESIGN_RESOLUTION)
end

display.COLOR_WHITE = cc.c3b(255, 255, 255)
display.COLOR_BLACK = cc.c3b(0, 0, 0)
display.COLOR_RED = cc.c3b(255, 0, 0)
display.COLOR_GREEN = cc.c3b(0, 255, 0)
display.COLOR_BLUE = cc.c3b(0, 0, 255)

display.AUTO_SIZE = 0
display.FIXED_SIZE = 1
display.LEFT_TO_RIGHT = 0
display.RIGHT_TO_LEFT = 1
display.TOP_TO_BOTTOM = 2
display.BOTTOM_TO_TOP = 3

display.CENTER = cc.p(0.5, 0.5)
display.LEFT_TOP = cc.p(0, 1)
display.LEFT_BOTTOM = cc.p(0, 0)
display.LEFT_CENTER = cc.p(0, 0.5)
display.RIGHT_TOP = cc.p(1, 1)
display.RIGHT_BOTTOM = cc.p(1, 0)
display.RIGHT_CENTER = cc.p(1, 0.5)
display.CENTER_TOP = cc.p(0.5, 1)
display.CENTER_BOTTOM = cc.p(0.5, 0)

display.SCENE_TRANSITIONS = {
CROSSFADE = cc.TransitionCrossFade,
FADE = {cc.TransitionFade, cc.c3b(0, 0, 0)},
FADEBL = cc.TransitionFadeBL,
FADEDOWN = cc.TransitionFadeDown,
FADETR = cc.TransitionFadeTR,
FADEUP = cc.TransitionFadeUp,
FLIPANGULAR = {cc.TransitionFlipAngular, cc.TRANSITION_ORIENTATION_LEFT_OVER},
FLIPX = {cc.TransitionFlipX, cc.TRANSITION_ORIENTATION_LEFT_OVER},
FLIPY = {cc.TransitionFlipY, cc.TRANSITION_ORIENTATION_UP_OVER},
JUMPZOOM = cc.TransitionJumpZoom,
MOVEINB = cc.TransitionMoveInB,
MOVEINL = cc.TransitionMoveInL,
MOVEINR = cc.TransitionMoveInR,
MOVEINT = cc.TransitionMoveInT,
PAGETURN = {cc.TransitionPageTurn, false},
ROTOZOOM = cc.TransitionRotoZoom,
SHRINKGROW = cc.TransitionShrinkGrow,
SLIDEINB = cc.TransitionSlideInB,
SLIDEINL = cc.TransitionSlideInL,
SLIDEINR = cc.TransitionSlideInR,
SLIDEINT = cc.TransitionSlideInT,
SPLITCOLS = cc.TransitionSplitCols,
SPLITROWS = cc.TransitionSplitRows,
TURNOFFTILES = cc.TransitionTurnOffTiles,
ZOOMFLIPANGULAR = cc.TransitionZoomFlipAngular,
ZOOMFLIPX = {cc.TransitionZoomFlipX, cc.TRANSITION_ORIENTATION_LEFT_OVER},
ZOOMFLIPY = {cc.TransitionZoomFlipY, cc.TRANSITION_ORIENTATION_UP_OVER},
}

display.TEXTURES_PIXEL_FORMAT = {}

display.DEFAULT_TTF_FONT = "fonts/huakangziti.TTF"
display.DEFAULT_TTF_FONT_SIZE = 32


local PARAMS_EMPTY = {}
local RECT_ZERO = cc.rect(0, 0, 0, 0)

local sceneIndex = 0
function display.newScene(name, params)
params = params or PARAMS_EMPTY
sceneIndex = sceneIndex + 1
local scene
if not params.physics then
scene = cc.Scene:create()
else
scene = cc.Scene:createWithPhysics()
end
scene.name_ = string.format("%s:%d", name or "<unknown-scene>", sceneIndex)

if params.transition then
scene = display.wrapSceneWithTransition(scene, params.transition, params.time, params.more)
end

return scene
end

function display.wrapScene(scene, transition, time, more)
local key = string.upper(tostring(transition))

if key == "RANDOM" then
local keys = table.keys(display.SCENE_TRANSITIONS)
key = keys[math.random(1, #keys)]
end

if display.SCENE_TRANSITIONS[key] then
local t = display.SCENE_TRANSITIONS[key]
time = time or 0.2
more = more or t[2]
if type(t) == "table" then
scene = t[1]:create(time, scene, more)
else
scene = t:create(time, scene)
end
else
error(string.format("display.wrapScene() - invalid transition %s", tostring(transition)))
end
return scene
end

function display.runScene(newScene, transition, time, more)
if director:getRunningScene() then
if transition then
newScene = display.wrapScene(newScene, transition, time, more)
end
director:replaceScene(newScene)
else
director:runWithScene(newScene)
end
end

function display.getRunningScene()
return director:getRunningScene()
end

function display.newNode()
return cc.Node:create()
end

function display.newLayer(...)
local params = {...}
local c = #params
local layer
if c == 0 then
-- /** creates a fullscreen black layer */
-- static Layer *create();
layer = cc.Layer:create()
elseif c == 1 then
-- /** creates a Layer with color. Width and height are the window size. */
-- static LayerColor * create(const Color4B& color);
layer = cc.LayerColor:create(cc.convertColor(params[1], "4b"))
elseif c == 2 then
-- /** creates a Layer with color, width and height in Points */
-- static LayerColor * create(const Color4B& color, const Size& size);
--
-- /** Creates a full-screen Layer with a gradient between start and end. */
-- static LayerGradient* create(const Color4B& start, const Color4B& end);
local color1 = cc.convertColor(params[1], "4b")
local p2 = params[2]
assert(type(p2) == "table" and (p2.width or p2.r), "display.newLayer() - invalid paramerter 2")
if p2.r then
layer = cc.LayerGradient:create(color1, cc.convertColor(p2, "4b"))
else
layer = cc.LayerColor:create(color1, p2.width, p2.height)
end
elseif c == 3 then
-- /** creates a Layer with color, width and height in Points */
-- static LayerColor * create(const Color4B& color, GLfloat width, GLfloat height);
--
-- /** Creates a full-screen Layer with a gradient between start and end in the direction of v. */
-- static LayerGradient* create(const Color4B& start, const Color4B& end, const Vec2& v);
local color1 = cc.convertColor(params[1], "4b")
local p2 = params[2]
local p2type = type(p2)
if p2type == "table" then
layer = cc.LayerGradient:create(color1, cc.convertColor(p2, "4b"), params[3])
else
layer = cc.LayerColor:create(color1, p2, params[3])
end
end
return layer
end

function display.newSprite(source, x, y, params)
local spriteClass = cc.Sprite
local scale9 = false

if type(x) == "table" and not x.x then
-- x is params
params = x
x = nil
y = nil
end

local params = params or PARAMS_EMPTY
if params.scale9 or params.capInsets then
spriteClass = ccui.Scale9Sprite
scale9 = true
params.capInsets = params.capInsets or RECT_ZERO
params.rect = params.rect or RECT_ZERO
end

local sprite
while true do
-- create sprite
if not source then
sprite = spriteClass:create()
break
end

local sourceType = type(source)
if sourceType == "string" then
if string.byte(source) == 35 then -- first char is #
-- create sprite from spriteFrame
if not scale9 then
sprite = spriteClass:createWithSpriteFrameName(string.sub(source, 2))
else
sprite = spriteClass:createWithSpriteFrameName(string.sub(source, 2), params.capInsets)
end
break
end

-- create sprite from image file
if display.TEXTURES_PIXEL_FORMAT[source] then
cc.Texture2D:setDefaultAlphaPixelFormat(display.TEXTURES_PIXEL_FORMAT[source])
end
if not scale9 then
sprite = spriteClass:create(source)
else
-- sprite = spriteClass:create(source, params.rect, params.capInsets)
sprite = spriteClass:create(source)
sprite:setScale9Enabled(true)
sprite:setCapInsets(params.capInsets)
-- sprite:setBorderEnabled(true)
-- sprite:setBorder(params.rect)
end
if display.TEXTURES_PIXEL_FORMAT[source] then
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_BGR_A8888)
end
break
elseif sourceType ~= "userdata" then
error(string.format("display.newSprite() - invalid source type \"%s\"", sourceType), 0)
else
sourceType = tolua.type(source)
if sourceType == "cc.SpriteFrame" then
if not scale9 then
sprite = spriteClass:createWithSpriteFrame(source)
else
sprite = spriteClass:createWithSpriteFrame(source, params.capInsets)
end
elseif sourceType == "cc.Texture2D" then
sprite = spriteClass:createWithTexture(source)
else
error(string.format("display.newSprite() - invalid source type \"%s\"", sourceType), 0)
end
end
break
end

if sprite then
if x and y then sprite:setPosition(cc.p(x, y)) end
if params.size then sprite:setContentSize(params.size) end
else
error(string.format("display.newSprite() - create sprite failure, source \"%s\"", tostring(source)), 0)
end

return sprite
end

function display.newSpriteFrame(source, ...)
local frame
if type(source) == "string" then
if string.byte(source) == 35 then -- first char is #
source = string.sub(source, 2)
end
frame = spriteFrameCache:getSpriteFrame(source)
if not frame then
error(string.format("display.newSpriteFrame() - invalid frame name \"%s\"", tostring(source)), 0)
end
elseif tolua.type(source) == "cc.Texture2D" then
frame = cc.SpriteFrame:createWithTexture(source, ...)
else
error("display.newSpriteFrame() - invalid parameters", 0)
end
return frame
end

function display.newFrames(pattern, begin, length, isReversed)
local frames = {}
local step = 1
local last = begin + length - 1
if isReversed then
last, begin = begin, last
step = -1
end

for index = begin, last, step do
local frameName = string.format(pattern, index)
local frame = spriteFrameCache:getSpriteFrame(frameName)
if not frame then
error(string.format("display.newFrames() - invalid frame name %s", tostring(frameName)), 0)
end
frames[#frames + 1] = frame
end
return frames
end

local function newAnimation(frames, time)
local count = #frames
assert(count > 0, "display.newAnimation() - invalid frames")
time = time or 1.0 / count
return cc.Animation:createWithSpriteFrames(frames, time),
cc.Sprite:createWithSpriteFrame(frames[1])
end

function display.newAnimation(...)
local params = {...}
local c = #params
if c == 2 then
-- frames, time
return newAnimation(params[1], params[2])
elseif c == 4 then
-- pattern, begin, length, time
local frames = display.newFrames(params[1], params[2], params[3])
return newAnimation(frames, params[4])
elseif c == 5 then
-- pattern, begin, length, isReversed, time
local frames = display.newFrames(params[1], params[2], params[3], params[4])
return newAnimation(frames, params[5])
else
error("display.newAnimation() - invalid parameters")
end
end

function display.loadImage(imageFilename, callback)
if not callback then
return textureCache:addImage(imageFilename)
else
textureCache:addImageAsync(imageFilename, callback)
end
end

local fileUtils = cc.FileUtils:getInstance()
function display.getImage(imageFilename)
local fullpath = fileUtils:fullPathForFilename(imageFilename)
return textureCache:getTextureForKey(fullpath)
end

function display.removeImage(imageFilename)
textureCache:removeTextureForKey(imageFilename)
end

function display.loadSpriteFrames(dataFilename, imageFilename, callback)
if display.TEXTURES_PIXEL_FORMAT[imageFilename] then
cc.Texture2D:setDefaultAlphaPixelFormat(display.TEXTURES_PIXEL_FORMAT[imageFilename])
end
if not callback then
spriteFrameCache:addSpriteFrames(dataFilename, imageFilename)
else
spriteFrameCache:addSpriteFramesAsync(dataFilename, imageFilename, callback)
end
if display.TEXTURES_PIXEL_FORMAT[imageFilename] then
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_BGR_A8888)
end
end

function display.removeSpriteFrames(dataFilename, imageFilename)
spriteFrameCache:removeSpriteFramesFromFile(dataFilename)
if imageFilename then
display.removeImage(imageFilename)
end
end

function display.removeSpriteFrame(imageFilename)
spriteFrameCache:removeSpriteFrameByName(imageFilename)
end

function display.setTexturePixelFormat(imageFilename, format)
display.TEXTURES_PIXEL_FORMAT[imageFilename] = format
end

function display.setAnimationCache(name, animation)
animationCache:addAnimation(animation, name)
end

function display.getAnimationCache(name)
return animationCache:getAnimation(name)
end

function display.removeAnimationCache(name)
animationCache:removeAnimation(name)
end

function display.removeUnusedSpriteFrames()
spriteFrameCache:removeUnusedSpriteFrames()
textureCache:removeUnusedTextures()
end

return display
--display_lua--display.lua

+ 81
- 0
core/luaScript/ModuleEapSdk/EapFunc/framework/extends/LayerEx.lua Näytä tiedosto

@@ -0,0 +1,81 @@
--[[

Copyright (c) 2011-2014 chukong-inc.com

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.

]]

local Layer = cc.Layer

function Layer:onTouch(callback, isMultiTouches, swallowTouches)
if type(isMultiTouches) ~= "boolean" then isMultiTouches = false end
if type(swallowTouches) ~= "boolean" then swallowTouches = false end

self:registerScriptTouchHandler(function(state, ...)
local args = {...}
local event = {name = state}
if isMultiTouches then
args = args[1]
local points = {}
for i = 1, #args, 3 do
local x, y, id = args[i], args[i + 1], args[i + 2]
points[id] = {x = x, y = y, id = id}
end
event.points = points
else
event.x = args[1]
event.y = args[2]
end
return callback( event )
end, isMultiTouches, 0, swallowTouches)
self:setTouchEnabled(true)
return self
end

function Layer:removeTouch()
self:unregisterScriptTouchHandler()
self:setTouchEnabled(false)
return self
end

function Layer:onKeypad(callback)
self:registerScriptKeypadHandler(callback)
self:setKeyboardEnabled(true)
return self
end

function Layer:removeKeypad()
self:unregisterScriptKeypadHandler()
self:setKeyboardEnabled(false)
return self
end

function Layer:onAccelerate(callback)
self:registerScriptAccelerateHandler(callback)
self:setAccelerometerEnabled(true)
return self
end

function Layer:removeAccelerate()
self:unregisterScriptAccelerateHandler()
self:setAccelerometerEnabled(false)
return self
end
--LayerEx_lua--LayerEx.lua

+ 32
- 0
core/luaScript/ModuleEapSdk/EapFunc/framework/extends/MenuEx.lua Näytä tiedosto

@@ -0,0 +1,32 @@
--[[

Copyright (c) 2011-2014 chukong-inc.com

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.

]]

local Menu = cc.Menu
local MenuItem = cc.MenuItem

function MenuItem:onClicked(callback)
self:registerScriptTapHandler(callback)
return self
end
--MenuEx_lua--MenuEx.lua

+ 229
- 0
core/luaScript/ModuleEapSdk/EapFunc/framework/extends/NodeEx.lua Näytä tiedosto

@@ -0,0 +1,229 @@
--[[

Copyright (c) 2011-2014 chukong-inc.com

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.

]]

local Node = cc.Node

function Node:add(child, zorder, tag)
if tag then
self:addChild(child, zorder, tag)
elseif zorder then
self:addChild(child, zorder)
else
self:addChild(child)
end
return self
end

function Node:addTo(parent, zorder, tag)
if tag then
parent:addChild(self, zorder, tag)
elseif zorder then
parent:addChild(self, zorder)
else
parent:addChild(self)
end
return self
end

function Node:removeSelf()
self:removeFromParent()
return self
end

function Node:align(anchorPoint, x, y)
self:setAnchorPoint(anchorPoint)
return self:move(x, y)
end

function Node:show()
self:setVisible(true)
return self
end

function Node:hide()
self:setVisible(false)
return self
end

function Node:move(x, y)
if y then
self:setPosition(cc.p(x, y))
else
self:setPosition(x)
end
return self
end

function Node:moveTo(args)
transition.moveTo(self, args)
return self
end

function Node:moveBy(args)
transition.moveBy(self, args)
return self
end

function Node:fadeIn(args)
transition.fadeIn(self, args)
return self
end

function Node:fadeOut(args)
transition.fadeOut(self, args)
return self
end

function Node:fadeTo(args)
transition.fadeTo(self, args)
return self
end

function Node:rotate(rotation)
self:setRotation(rotation)
return self
end

function Node:rotateTo(args)
transition.rotateTo(self, args)
return self
end

function Node:rotateBy(args)
transition.rotateBy(self, args)
return self
end

function Node:scaleTo(args)
transition.scaleTo(self, args)
return self
end

function Node:onUpdate(callback)
self:scheduleUpdateWithPriorityLua(callback, 0)
return self
end

Node.scheduleUpdate = Node.onUpdate

function Node:onNodeEvent(eventName, callback)
if "enter" == eventName then
self.onEnterCallback_ = callback
elseif "exit" == eventName then
self.onExitCallback_ = callback
elseif "enterTransitionFinish" == eventName then
self.onEnterTransitionFinishCallback_ = callback
elseif "exitTransitionStart" == eventName then
self.onExitTransitionStartCallback_ = callback
elseif "cleanup" == eventName then
self.onCleanupCallback_ = callback
end
self:enableNodeEvents()
end

function Node:enableNodeEvents()
if self.isNodeEventEnabled_ then
return self
end

self:registerScriptHandler(function(state)
if state == "enter" then
self:onEnter_()
elseif state == "exit" then
self:onExit_()
elseif state == "enterTransitionFinish" then
self:onEnterTransitionFinish_()
elseif state == "exitTransitionStart" then
self:onExitTransitionStart_()
elseif state == "cleanup" then
self:onCleanup_()
end
end)
self.isNodeEventEnabled_ = true

return self
end

function Node:disableNodeEvents()
self:unregisterScriptHandler()
self.isNodeEventEnabled_ = false
return self
end


function Node:onEnter()
end

function Node:onExit()
end

function Node:onEnterTransitionFinish()
end

function Node:onExitTransitionStart()
end

function Node:onCleanup()
end

function Node:onEnter_()
self:onEnter()
if not self.onEnterCallback_ then
return
end
self:onEnterCallback_()
end

function Node:onExit_()
self:onExit()
if not self.onExitCallback_ then
return
end
self:onExitCallback_()
end

function Node:onEnterTransitionFinish_()
self:onEnterTransitionFinish()
if not self.onEnterTransitionFinishCallback_ then
return
end
self:onEnterTransitionFinishCallback_()
end

function Node:onExitTransitionStart_()
self:onExitTransitionStart()
if not self.onExitTransitionStartCallback_ then
return
end
self:onExitTransitionStartCallback_()
end

function Node:onCleanup_()
self:onCleanup()
if not self.onCleanupCallback_ then
return
end
self:onCleanupCallback_()
end
--NodeEx_lua--NodeEx.lua

+ 68
- 0
core/luaScript/ModuleEapSdk/EapFunc/framework/extends/SpriteEx.lua Näytä tiedosto

@@ -0,0 +1,68 @@
--[[

Copyright (c) 2011-2014 chukong-inc.com

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.

]]

local Sprite = cc.Sprite

function Sprite:playAnimationOnce(animation, args)
local actions = {}

local showDelay = args.showDelay or 0
if showDelay then
self:setVisible(false)
actions[#actions + 1] = cc.DelayTime:create(showDelay)
actions[#actions + 1] = cc.Show:create()
end

local delay = args.delay or 0
if delay > 0 then
actions[#actions + 1] = cc.DelayTime:create(delay)
end

actions[#actions + 1] = cc.Animate:create(animation)

if args.removeSelf then
actions[#actions + 1] = cc.RemoveSelf:create()
end

if args.onComplete then
actions[#actions + 1] = cc.CallFunc:create(args.onComplete)
end

local action
if #actions > 1 then
action = cc.Sequence:create(actions)
else
action = actions[1]
end
self:runAction(action)
return action
end

function Sprite:playAnimationForever(animation)
local animate = cc.Animate:create(animation)
local action = cc.RepeatForever:create(animate)
self:runAction(action)
return action
end
--SpriteEx_lua--SpriteEx.lua

+ 41
- 0
core/luaScript/ModuleEapSdk/EapFunc/framework/extends/UICheckBox.lua Näytä tiedosto

@@ -0,0 +1,41 @@

--[[

Copyright (c) 2011-2014 chukong-inc.com

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.

]]

local CheckBox = ccui.CheckBox

function CheckBox:onEvent(callback)
self:addEventListener(function(sender, eventType)
local event = {}
if eventType == 0 then
event.name = "selected"
else
event.name = "unselected"
end
event.target = sender
callback(event)
end)
return self
end
--UICheckBox_lua--UICheckBox.lua

+ 42
- 0
core/luaScript/ModuleEapSdk/EapFunc/framework/extends/UIEditBox.lua Näytä tiedosto

@@ -0,0 +1,42 @@

--[[

Copyright (c) 2011-2014 chukong-inc.com

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.

]]

local EditBox = ccui.EditBox

function EditBox:onEditHandler(callback)
self:registerScriptEditBoxHandler(function(name, sender)
local event = {}
event.name = name
event.target = sender
callback(event)
end)
return self
end

function EditBox:removeEditHandler()
self:unregisterScriptEditBoxHandler()
return self
end
--UIEditBox_lua--UIEditBox.lua

+ 69
- 0
core/luaScript/ModuleEapSdk/EapFunc/framework/extends/UIListView.lua Näytä tiedosto

@@ -0,0 +1,69 @@

--[[

Copyright (c) 2011-2014 chukong-inc.com

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.

]]

local ListView = ccui.ListView

function ListView:onEvent(callback)
self:addEventListener(function(sender, eventType)
local event = {}
if eventType == 0 then
event.name = "ON_SELECTED_ITEM_START"
else
event.name = "ON_SELECTED_ITEM_END"
end
event.target = sender
callback(event)
end)
return self
end

function ListView:onScroll(callback)
self:addScrollViewEventListener(function(sender, eventType)
local event = {}
if eventType == 0 then
event.name = "SCROLL_TO_TOP"
elseif eventType == 1 then
event.name = "SCROLL_TO_BOTTOM"
elseif eventType == 2 then
event.name = "SCROLL_TO_LEFT"
elseif eventType == 3 then
event.name = "SCROLL_TO_RIGHT"
elseif eventType == 4 then
event.name = "SCROLLING"
elseif eventType == 5 then
event.name = "BOUNCE_TOP"
elseif eventType == 6 then
event.name = "BOUNCE_BOTTOM"
elseif eventType == 7 then
event.name = "BOUNCE_LEFT"
elseif eventType == 8 then
event.name = "BOUNCE_RIGHT"
end
event.target = sender
callback(event)
end)
return self
end
--UIListView_lua--UIListView.lua

+ 39
- 0
core/luaScript/ModuleEapSdk/EapFunc/framework/extends/UIPageView.lua Näytä tiedosto

@@ -0,0 +1,39 @@

--[[

Copyright (c) 2011-2014 chukong-inc.com

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.

]]

local PageView = ccui.PageView

function PageView:onEvent(callback)
self:addEventListener(function(sender, eventType)
local event = {}
if eventType == 0 then
event.name = "TURNING"
end
event.target = sender
callback(event)
end)
return self
end
--UIPageView_lua--UIPageView.lua

+ 57
- 0
core/luaScript/ModuleEapSdk/EapFunc/framework/extends/UIScrollView.lua Näytä tiedosto

@@ -0,0 +1,57 @@

--[[

Copyright (c) 2011-2014 chukong-inc.com

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.

]]

local ScrollView = ccui.ScrollView

function ScrollView:onEvent(callback)
self:addEventListener(function(sender, eventType)
local event = {}
if eventType == 0 then
event.name = "SCROLL_TO_TOP"
elseif eventType == 1 then
event.name = "SCROLL_TO_BOTTOM"
elseif eventType == 2 then
event.name = "SCROLL_TO_LEFT"
elseif eventType == 3 then
event.name = "SCROLL_TO_RIGHT"
elseif eventType == 4 then
event.name = "SCROLLING"
elseif eventType == 5 then
event.name = "BOUNCE_TOP"
elseif eventType == 6 then
event.name = "BOUNCE_BOTTOM"
elseif eventType == 7 then
event.name = "BOUNCE_LEFT"
elseif eventType == 8 then
event.name = "BOUNCE_RIGHT"
end
event.target = sender
callback(event)
end)
return self
end

ScrollView.onScroll = ScrollView.onEvent
--UIScrollView_lua--UIScrollView.lua

+ 39
- 0
core/luaScript/ModuleEapSdk/EapFunc/framework/extends/UISlider.lua Näytä tiedosto

@@ -0,0 +1,39 @@

--[[

Copyright (c) 2011-2014 chukong-inc.com

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.

]]

local Slider = ccui.Slider

function Slider:onEvent(callback)
self:addEventListener(function(sender, eventType)
local event = {}
if eventType == 0 then
event.name = "ON_PERCENTAGE_CHANGED"
end
event.target = sender
callback(event)
end)
return self
end
--UISlider_lua--UISlider.lua

+ 45
- 0
core/luaScript/ModuleEapSdk/EapFunc/framework/extends/UITextField.lua Näytä tiedosto

@@ -0,0 +1,45 @@

--[[

Copyright (c) 2011-2014 chukong-inc.com

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.

]]

local TextField = ccui.TextField

function TextField:onEvent(callback)
self:addEventListener(function(sender, eventType)
local event = {}
if eventType == 0 then
event.name = "ATTACH_WITH_IME"
elseif eventType == 1 then
event.name = "DETACH_WITH_IME"
elseif eventType == 2 then
event.name = "INSERT_TEXT"
elseif eventType == 3 then
event.name = "DELETE_BACKWARD"
end
event.target = sender
callback(event)
end)
return self
end
--UITextField_lua--UITextField.lua

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

Ladataan…
Peruuta
Tallenna