util.lua 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701
  1. local cjson = require("cjson")
  2. local matetable = require("util/MainMateTable")
  3. local tconcat = table.concat
  4. local tinsert = table.insert
  5. local tostring = tostring
  6. local pairs = pairs
  7. local type = type
  8. local next = next
  9. local sreverse = string.reverse
  10. local sformat = string.format
  11. local sfind = string.find
  12. local sbyte = string.byte
  13. local sgsub = string.gsub
  14. local ssub = string.sub
  15. local srep = string.rep
  16. local slen = string.len
  17. local globalSchedule = {} -- 全局函数回调
  18. local preDevScheduleID = nil -- 预加载Dev文件的ScheduleID
  19. _DEBUG = global.isDebugMode
  20. function releasePrint(...)
  21. if global.isGMMode then
  22. return
  23. end
  24. release_print(...)
  25. end
  26. function Print(...)
  27. if _DEBUG then
  28. release_print(...)
  29. end
  30. end
  31. rawset(_G, "print", Print)
  32. function PrintTableByTree(root)
  33. if not _DEBUG then
  34. return nil
  35. end
  36. if nil == root then
  37. release_print("nil")
  38. return nil
  39. end
  40. local cache = {[root] = "."}
  41. local function _dump(t, space, name)
  42. local temp = {}
  43. local value = ""
  44. local tempStr = ""
  45. local endPos = nil
  46. for k, v in pairs(t) do
  47. local key = tostring(k)
  48. if cache[v] then
  49. tinsert(temp, "+" .. key .. " {" .. cache[v] .. "}")
  50. elseif type(v) == "table" then
  51. local new_key = name .. "." .. key
  52. cache[v] = new_key
  53. tinsert(temp, "+" .. key .. _dump(v, space .. (next(t, k) and "|" or " ") .. srep(" ", #key), new_key))
  54. else
  55. value = tostring(v)
  56. if nil == value then
  57. tempStr = "nil"
  58. else
  59. endPos = sfind(value, "\0")
  60. if endPos == nil then
  61. tempStr = value
  62. elseif endPos == 1 then
  63. tempStr = ""
  64. else
  65. tempStr = ssub(value, 1, endPos)
  66. end
  67. end
  68. tinsert(temp, "+" .. key .. " : " .. tempStr)
  69. end
  70. end
  71. return tconcat(temp, "\n" .. space)
  72. end
  73. release_print("Table:" .. tostring(root) .. "\n" .. _dump(root, "", ""))
  74. end
  75. PrintTable = PrintTableByTree
  76. -- print call traceback
  77. function PrintTraceback()
  78. local traceback = string.split(debug.traceback("", 2), "\n")
  79. PrintTable(traceback)
  80. end
  81. function CreateExport(fileName)
  82. local ui = requireExport(fileName).create()
  83. if ui.root then
  84. local new_widget = ccui.Widget:create()
  85. new_widget:setAnchorPoint(cc.p(0, 0))
  86. local children = ui.root:getChildren()
  87. for _, child in pairs(children) do
  88. child:removeFromParent()
  89. end
  90. for _, child in pairs(children) do
  91. new_widget:addChild(child)
  92. end
  93. local name = ui.root:getName()
  94. -- 自适应代码
  95. if name ~= "Layer" and name ~= "Node" then
  96. local visible = cc.Director:getInstance():getVisibleSize()
  97. new_widget:setContentSize(visible)
  98. ccui.Helper:doLayout(new_widget)
  99. else
  100. new_widget:setContentSize(ui.root:getContentSize())
  101. end
  102. rawset(ui, "root", new_widget)
  103. return new_widget, ui
  104. end
  105. return nil
  106. end
  107. function getResFullPath(path)
  108. return path
  109. end
  110. function requireCommand(path)
  111. return require("game/command/" .. path)
  112. end
  113. function requireMediator(path)
  114. return require("game/mediator/" .. path)
  115. end
  116. function requireProxy(path)
  117. return require("game/proxy/" .. path)
  118. end
  119. function requireView(path)
  120. return require("game/view/" .. path)
  121. end
  122. function requireLayerUI(path)
  123. return require("game/view/layersui/" .. path)
  124. end
  125. function requireMainUI(path)
  126. return require("game/view/mainui/" .. path)
  127. end
  128. function requireMainUIWIN32(path)
  129. return require("game/view/mainui-win32/" .. path)
  130. end
  131. function requireExport(path)
  132. return require("game/view/export/" .. path)
  133. end
  134. -- value object
  135. function requireVO(path)
  136. return require("game/valueobject/" .. path)
  137. end
  138. function requireUtil(path)
  139. return require("util/" .. path)
  140. end
  141. function requireConfig(path)
  142. return require("config/" .. path)
  143. end
  144. function requireGameConfig(path)
  145. return require("game_config/" .. path)
  146. end
  147. function requireSUI(path)
  148. return require("GUI/sui/" .. path)
  149. end
  150. function requireCUI(path)
  151. return require("GUI/CUI/" .. path)
  152. end
  153. function requireGuide(path)
  154. return require("GUI/guide/" .. path)
  155. end
  156. function requireLayerGUI(path)
  157. return require("game/view/layersui/gui_layer/" .. path)
  158. end
  159. function releaseLayerGUI(path)
  160. package.loaded["game/view/layersui/gui_layer/" .. path] = nil
  161. end
  162. function LoadTxt(path, delimiter, callback)
  163. if nil == path or nil == callback then
  164. print("LoadText error")
  165. return
  166. end
  167. local fileUtil = global.FileUtilCtl
  168. local strBuffer = fileUtil:getDataFromFileEx(path)
  169. strBuffer = sgsub(strBuffer, "\r", "")
  170. local lineBreak = "\n"
  171. local lines = string.split(strBuffer, lineBreak)
  172. local len = 0
  173. local pos1 = nil
  174. for k, v in pairs(lines) do
  175. len = slen(v)
  176. if len > 0 then
  177. pos1, _ = sfind(v, "//")
  178. if not pos1 then -- skip //
  179. local dataTable
  180. if delimiter == nil or delimiter == "" or delimiter == "\n" then -- ignore "" \n
  181. dataTable = {}
  182. dataTable[1] = v
  183. else
  184. dataTable = string.split(v, delimiter)
  185. end
  186. callback(dataTable)
  187. end
  188. end
  189. end
  190. end
  191. function Random(b, e) -- 简单随机
  192. if nil == e then
  193. return math.random(b)
  194. end
  195. return math.random(b, e)
  196. end
  197. function Schedule(callback, interval)
  198. return global.Scheduler:scheduleScriptFunc(callback, interval, false)
  199. end
  200. function UnSchedule(scheduleID)
  201. global.Scheduler:unscheduleScriptEntry(scheduleID)
  202. end
  203. --[[--
  204. 计划一个全局延时回调,并返回该计划的句柄。
  205. -- @function [parent=#scheduler] PerformWithDelayGlobal
  206. -- @param function listener 回调函数
  207. -- @param number time 延迟时间
  208. -- @return mixed#mixed ret (return value: mixed) schedule句柄
  209. scheduler.performWithDelayGlobal() 会在等待指定时间后执行一次回调函数,然后自动取消该计划。
  210. ]]
  211. function PerformWithDelayGlobal(listener, time)
  212. local handle
  213. handle =
  214. global.Scheduler:scheduleScriptFunc(
  215. function()
  216. global.Scheduler:unscheduleScriptEntry(handle)
  217. listener()
  218. end,
  219. time,
  220. false
  221. )
  222. return handle
  223. end
  224. -- 秒转时间 format : h:m:s
  225. -- p2 : 是否转为字符串
  226. function SecondToHMS(sec, isToStr, isSimple)
  227. local d = math.floor(sec / 86400)
  228. local h = math.fmod(math.floor(sec / 3600), 24)
  229. local m = math.fmod(math.floor(sec / 60), 60)
  230. local s = math.fmod(sec, 60)
  231. local time = {}
  232. time.d = d
  233. time.h = h
  234. time.m = m
  235. time.s = s
  236. if type(isToStr) == "boolean" and isToStr == true then
  237. if time.d > 0 then
  238. if isSimple then
  239. return sformat("%d天%d时", time.d, time.h)
  240. else
  241. return sformat("%d天%d时%d分%d秒", time.d, time.h, time.m, time.s)
  242. end
  243. else
  244. if time.h > 0 then
  245. if isSimple then
  246. return sformat("%d时%d分", time.h, time.m)
  247. else
  248. return sformat("%d时%d分%d秒", time.h, time.m, time.s)
  249. end
  250. else
  251. if time.m > 0 then
  252. return sformat("%d分%d秒", time.m, time.s)
  253. else
  254. return sformat("%d秒", time.s)
  255. end
  256. end
  257. end
  258. else
  259. return time
  260. end
  261. end
  262. function TimeFormat(time)
  263. if not time then
  264. return
  265. end
  266. local day,hour,min,sce = 0,0,0,0
  267. day = math.floor(time / 86400)
  268. hour = math.fmod( math.floor(time / 3600) , 24)
  269. min = math.fmod( math.floor(time/60),60)
  270. sce = math.fmod(time,60)
  271. return day,hour,min,sce
  272. end
  273. -- 00:00:00
  274. function TimeFormatToString(time)
  275. local day, h, m, s = TimeFormat(time)
  276. if day < 1 then
  277. return sformat("%02d:%02d:%02d", h, m, s)
  278. end
  279. return sformat(GET_STRING(2000), day, h, m)
  280. end
  281. function Shader_Grey(node)
  282. if not node then
  283. return
  284. end
  285. local data = {}
  286. data.node = node
  287. global.Facade:sendNotification(global.NoticeTable.GrayNodeShader, data)
  288. end
  289. function Shader_Normal(node)
  290. if not node then
  291. return
  292. end
  293. local data = {}
  294. data.node = node
  295. global.Facade:sendNotification(global.NoticeTable.NormalNodeShader, data)
  296. end
  297. --显示菊花转
  298. function ShowLoadingBar(isCheckOutTimer)
  299. global.Facade:sendNotification(global.NoticeTable.Layer_LoadingBar_Open, isCheckOutTimer)
  300. end
  301. --关闭菊花转
  302. function HideLoadingBar()
  303. global.Facade:sendNotification(global.NoticeTable.Layer_LoadingBar_Close)
  304. end
  305. function EnterWorldLoadingProgress(unit)
  306. if not global.LoadingPercent then
  307. global.LoadingPercent = 0
  308. -- open loading
  309. end
  310. if unit then
  311. global.LoadingPercent = global.LoadingPercent + unit
  312. end
  313. end
  314. function ClearWorldLoadingProgress()
  315. global.LoadingPercent = nil
  316. end
  317. function HTTPRequest(url, callback)
  318. local httpRequest = cc.XMLHttpRequest:new()
  319. httpRequest.responseType = cc.XMLHTTPREQUEST_RESPONSE_JSON
  320. httpRequest.timeout = 100000 -- 10 s
  321. httpRequest:open("GET", url)
  322. if callback then
  323. local function HttpResponseCB()
  324. local code = httpRequest.status
  325. local success = code >= 200 and code < 300
  326. local response = httpRequest.response
  327. release_print("Http Request Code:" .. tostring(code))
  328. callback(success, response)
  329. end
  330. httpRequest:registerScriptHandler(HttpResponseCB)
  331. end
  332. httpRequest:send()
  333. end
  334. function HTTPRequestPost(url, callback, data, header, notForce)
  335. local httpRequest = cc.XMLHttpRequest:new()
  336. httpRequest.responseType = cc.XMLHTTPREQUEST_RESPONSE_JSON
  337. httpRequest.timeout = 100000 -- 10 s
  338. httpRequest:open("POST", url)
  339. if header then
  340. for k, v in pairs(header) do
  341. httpRequest:setRequestHeader(k, v)
  342. end
  343. end
  344. if callback then
  345. local function HttpResponseCB()
  346. local code = httpRequest.status
  347. local success = code >= 200 and code < 300
  348. local response = httpRequest.response
  349. release_print("Http Request Code:" .. tostring(code))
  350. callback(success, response, code)
  351. end
  352. if not notForce then
  353. httpRequest:setRequestHeader("Content-type", "application/x-www-form-urlencoded")
  354. end
  355. httpRequest:registerScriptHandler(HttpResponseCB)
  356. end
  357. httpRequest:send(data)
  358. end
  359. --指定parent获取child
  360. function UIGetChildByName(widget, ...)
  361. local parent = widget
  362. local widgetNameList = {...}
  363. for _, widgetName in pairs(widgetNameList) do
  364. parent = parent:getChildByName(widgetName)
  365. if not parent then
  366. return nil
  367. end
  368. end
  369. return parent
  370. end
  371. -- "#FFFFFF" --> cc.c3b( 0xff, 0xff, 0xff )
  372. function GetColorFromHexString(hexString)
  373. hexString = tostring(hexString)
  374. local hex = sgsub(hexString, "#", "0x")
  375. local num = tonumber(hex)
  376. if not num then
  377. return cc.Color3B.WHITE
  378. end
  379. return GetColorFromHex(num)
  380. end
  381. --
  382. function GetColorFromHex(hexadecimalCode)
  383. local B = bit.band(hexadecimalCode, 0xff)
  384. local G = bit.band(bit.rshift(hexadecimalCode, 8), 0xff)
  385. local R = bit.band(bit.rshift(hexadecimalCode, 16), 0xff)
  386. return cc.c3b(R, G, B)
  387. end
  388. -- cc.c3b( 0xff, 0xff, 0xff ) --> 0xFFFFFF
  389. function GetColorHexFromRBG(rgb)
  390. return sformat("#%02x%02x%02x", rgb.r, rgb.g, rgb.b)
  391. end
  392. -- "#FFFFFF" --> cc.c4b( 0xff, 0xff, 0xff, 0xff )
  393. function GetRGBAFromHexString(hexString)
  394. local hex = sgsub(hexString, "#", "0x")
  395. local num = tonumber(hex)
  396. if not num then
  397. return cc.Color3B.WHITE
  398. end
  399. local A = bit.band(num, 0xff)
  400. local B = bit.band(bit.rshift(num, 8), 0xff)
  401. local G = bit.band(bit.rshift(num, 16), 0xff)
  402. local R = bit.band(bit.rshift(num, 24), 0xff)
  403. return cc.c4b(R, G, B, A)
  404. end
  405. GoodsItem = {}
  406. GoodsItem.create = function(self, data)
  407. -- self不能使用
  408. local GoodsItem = require("util/GoodsItem")
  409. local item = GoodsItem.new()
  410. item._isGood = true
  411. item:init(data)
  412. return item
  413. end
  414. BagItemLayer = {}
  415. BagItemLayer.create = function(data, Zorder)
  416. if Zorder == global.MMO.BAG_ITEM_ZORDER then
  417. local BagItemLayer = requireLayerUI("bag_layer/BagItemLayer")
  418. local item = BagItemLayer.new()
  419. item:init(data)
  420. return item
  421. elseif Zorder == global.MMO.BAG_TEXT_ZORDER then
  422. local BagItemTextLayer = requireLayerUI("bag_layer/BagItemTextLayer")
  423. local item = BagItemTextLayer.new()
  424. item:init(data)
  425. return item
  426. elseif Zorder == global.MMO.BAG_EFFECT_ZORDER then
  427. local BagItemEffectLayer = requireLayerUI("bag_layer/BagItemEffectLayer")
  428. local item = BagItemEffectLayer.new()
  429. item:init(data)
  430. return item
  431. end
  432. end
  433. SkillItem = {}
  434. SkillItem.create = function(self, data)
  435. -- self不能使用
  436. local SkillItem = require("util/SkillItem")
  437. local item = SkillItem.new()
  438. item:init(data)
  439. return item
  440. end
  441. SItemBox = {}
  442. function SItemBox:create(data)
  443. if not data or not next(data) then
  444. return
  445. end
  446. local boxindex = tonumber(data.boxindex)
  447. local img = data.img
  448. local stdmode = data.stdmode
  449. local SUIHelper = require("sui/SUIHelper")
  450. local img = SUIHelper.fixImageFileName(img)
  451. local fullPath = img
  452. local widget = ccui.ImageView:create()
  453. if global.FileUtilCtl:isFileExist(fullPath) then
  454. widget:loadTexture(fullPath)
  455. end
  456. widget:ignoreContentAdaptWithSize(false)
  457. widget:setContentSize(widget:getVirtualRendererSize())
  458. widget:setTouchEnabled(true)
  459. --
  460. local ItemMoveProxy = global.Facade:retrieveProxy(global.ProxyTable.ItemMoveProxy)
  461. local function addItemToITEMBOX(touchPos)
  462. local state = ItemMoveProxy:GetMovingItemState()
  463. if state then
  464. local goToName = ItemMoveProxy.ItemGoTo.SSR_ITEM_BOX
  465. local data = {}
  466. data.target = goToName
  467. data.stdmode = stdmode
  468. data.widget = widget
  469. data.boxindex = boxindex
  470. ItemMoveProxy:CheckAndCallBack( data )
  471. else
  472. return -1
  473. end
  474. end
  475. local function setNoswallowMouse()
  476. return -1
  477. end
  478. global.mouseEventController:registerMouseButtonEvent(
  479. widget,
  480. {
  481. down_r = setNoswallowMouse,
  482. special_r = addItemToITEMBOX,
  483. checkIsVisible = true
  484. }
  485. )
  486. global.Facade:sendNotification(global.NoticeTable.SSR_ITEMBOXWidget_Add, {boxindex = boxindex, widget = widget})
  487. return widget
  488. end
  489. function CheckBit(num, pos)
  490. return bit.band(bit.rshift(num, pos), 0x1) == 1
  491. end
  492. function H16Bit(value)
  493. if not value then
  494. return 0
  495. end
  496. return bit.band(bit.rshift(value, 16), 0xffff)
  497. end
  498. function L16Bit(value)
  499. if not value then
  500. return 0
  501. end
  502. return bit.band(value, 0xffff)
  503. end
  504. function H8Bit(value)
  505. if not value then
  506. return 0
  507. end
  508. return bit.band(bit.rshift(value, 8), 0xff)
  509. end
  510. function L8Bit(value)
  511. if not value then
  512. return 0
  513. end
  514. return bit.band(value, 0xff)
  515. end
  516. function Merge16Bit(v1, v2)
  517. local ret = bit.lshift(v2, 16)
  518. ret = bit.bor(ret, v1)
  519. return ret
  520. end
  521. function CreateRedPoint(targetNode, offset)
  522. local red = nil
  523. local sprite = cc.Sprite:create(global.MMO.PATH_RES_PUBLIC .. "btn_npcfh_04.png")
  524. if sprite then
  525. red = sprite
  526. end
  527. if red then
  528. local size = targetNode:getContentSize()
  529. local pos = {}
  530. pos.x = size.width - (offset and offset.x or 0)
  531. pos.y = size.height - (offset and offset.y or 0)
  532. red:setPosition(cc.p(pos.x, pos.y))
  533. targetNode:addChild(red)
  534. end
  535. return red
  536. end
  537. function DelayTouchEnabled(target, delay)
  538. delay = delay or 0.2
  539. target:stopActionByTag(10999)
  540. target:setTouchEnabled(false)
  541. local action = performWithDelay(
  542. target,
  543. function()
  544. target:setTouchEnabled(true)
  545. end,
  546. delay
  547. )
  548. action:setTag(10999)
  549. end
  550. function GetFrameAnimIndex(act, dir)
  551. return act * 8 + dir
  552. end
  553. function GetFrameAnimConfigID( rawAnimID, sex, animType )
  554. -- 0xfffff f f f
  555. -- animID type sex act
  556. return animType * 10000000 + sex * 5000000 + rawAnimID
  557. end
  558. --获取服务器时间 (根据服务器和本地的时间差,算出当前服务器的时间)
  559. function GetServerTime()
  560. local sub = global.MMO.ServerTime_Sub or 0
  561. return os.time() + sub
  562. end
  563. function ErrorReport(tag, content)
  564. local tagStr = tostring(tag)
  565. local contentStr = tostring(content)
  566. if not tagStr or not contentStr then
  567. return
  568. end
  569. local contentLen = slen(contentStr)
  570. local reportContent = contentLen <= 512 and contentStr or ssub(contentStr, 1, 512)
  571. if cc.PLATFORM_OS_ANDROID == global.Platform then
  572. buglyLog(1, tagStr, reportContent)
  573. buglyReportLuaException(tagStr, tagStr, false)
  574. else
  575. local data = {}
  576. data.ChannelId = 1
  577. data.Msg = tagStr .. " : " .. reportContent
  578. global.Facade:sendNotification(global.NoticeTable.SystemTips, "ERROR! " .. data.Msg)
  579. global.Facade:sendNotification(global.NoticeTable.AddChatItem, data)
  580. end
  581. end
  582. function RecordBuglyLogIm(index, value)
  583. if not index or not value then
  584. return
  585. end
  586. if cc.PLATFORM_OS_ANDROID == global.Platform then
  587. buglyLog(1, tostring(index), tostring(value))
  588. else
  589. release_print(tostring(index) .. ":" .. tostring(value))
  590. end
  591. end
  592. function RemoveAllWidgetClickEventListener(widget)
  593. if not widget then
  594. return
  595. end
  596. global.ScriptHandlerMgr:removeObjectAllHandlers(widget)
  597. widget:addClickEventListener(
  598. function()
  599. end
  600. )
  601. end
  602. function RemoveAllWidgetTouchEventListener(widget)
  603. if not widget then
  604. return
  605. end
  606. global.ScriptHandlerMgr:removeObjectAllHandlers(widget)
  607. widget:addTouchEventListener(
  608. function()
  609. end
  610. )
  611. end
  612. function CreateEditBoxByTextField(textField)
  613. local inputStr = textField:getString()
  614. local textColor = textField:getColor()
  615. local placeHolderColor = textField:getPlaceHolderColor()
  616. local placeHolder = textField:getPlaceHolder()
  617. local contentSize = textField:getContentSize()
  618. local fontSize = textField:getFontSize()
  619. local fontName = textField:getFontName()
  620. local parent = textField:getParent()
  621. local anchorPoint = textField:getAnchorPoint()
  622. local positionX = textField:getPositionX()
  623. local positionY = textField:getPositionY()
  624. local maxLength = textField:getMaxLength()
  625. local maxLengthEnable = textField:isMaxLengthEnabled()
  626. local horizontalAlignment = textField:getTextHorizontalAlignment()
  627. local name = textField:getName()
  628. textField:removeFromParent()
  629. textField = nil
  630. local fontPath = global.MMO.PATH_FONT2
  631. local editBox = ccui.EditBox:create(contentSize, global.MMO.PATH_RES_ALPHA)
  632. parent:addChild(editBox)
  633. if global.isMobile then
  634. editBox:setFontName(fontPath)
  635. end
  636. editBox:setFontSize(fontSize)
  637. editBox:setFontColor(textColor)
  638. editBox:setColor(textColor)
  639. editBox:setAnchorPoint(anchorPoint)
  640. if global.Platform == cc.PLATFORM_OS_ANDROID then
  641. positionX = positionX + 1
  642. positionY = positionY + 1
  643. editBox:setNativeOffset(cc.p(0, -13))
  644. end
  645. editBox:setPosition(cc.p(positionX, positionY))
  646. if maxLengthEnable then
  647. editBox:setMaxLength(maxLength)
  648. end
  649. editBox:setPlaceHolder(placeHolder)
  650. editBox:setPlaceholderFontColor(placeHolderColor)
  651. editBox:setPlaceholderFontSize(fontSize)
  652. editBox:setTextHorizontalAlignment(horizontalAlignment)
  653. editBox:setText(inputStr)
  654. editBox:setName(name)
  655. return editBox
  656. end
  657. local EditBox = ccui.EditBox
  658. function EditBox:getString()
  659. return self:getText()
  660. end
  661. function EditBox:setString(input)
  662. self:setText(input)
  663. end
  664. function EditBox:addEventListener(callback)
  665. self:onEditHandler(
  666. function(event)
  667. local name = event.name
  668. local sender = event.target
  669. if name == "began" then
  670. callback(sender, 0)
  671. elseif name == "ended" then
  672. callback(sender, 1)
  673. elseif name == "changed" then
  674. callback(sender, 2)
  675. elseif name == "return" then
  676. callback(sender, 3)
  677. elseif name == "send" then
  678. callback(sender, 4)
  679. end
  680. end
  681. )
  682. end
  683. ----------------------------------------------------------------------------
  684. local Text = ccui.Text
  685. local Label = cc.Label
  686. local Widget = ccui.Widget
  687. local Button = ccui.Button
  688. local CheckBox = ccui.CheckBox
  689. local RichText = ccui.RichText
  690. function CheckBox:addClickEventListener(callback)
  691. self._clickCallBack_ = callback
  692. local backup = getmetatable(getmetatable(self))[".backup"]
  693. backup.addClickEventListener(self, callback)
  694. end
  695. function Widget:addTouchBeganEventListener(callback)
  696. self:addTouchEventListener(
  697. function(_, eventType)
  698. if eventType == 0 then
  699. callback()
  700. end
  701. end
  702. )
  703. end
  704. function Widget:addClickEventListener(callback)
  705. local backup = nil
  706. if tolua.type(self) == "ccui.Widget" then
  707. backup = getmetatable(self)[".backup"]
  708. elseif tolua.type(self) == "ccui.ListView" then
  709. backup = getmetatable(getmetatable(getmetatable(self)))[".backup"]
  710. else
  711. backup = getmetatable(getmetatable(self))[".backup"]
  712. end
  713. if backup then
  714. if type(backup.onEvent) == "function" then
  715. backup.onEvent(self, callback)
  716. self._clickCallBack_ = callback
  717. elseif type(backup.addClickEventListener) == "function" then
  718. backup.addClickEventListener(self, callback)
  719. self._clickCallBack_ = callback
  720. end
  721. end
  722. end
  723. function Widget:addTouchEventListener(...)
  724. local params = {...}
  725. if #params == 1 then
  726. self._touchCallBack_ = ...
  727. else
  728. self._touchCallBack_ = params[2]
  729. end
  730. local backup = nil
  731. if tolua.type(self) == "ccui.Widget" then
  732. backup = getmetatable(self)[".backup"]
  733. elseif tolua.type(self) == "ccui.ListView" then
  734. backup = getmetatable(getmetatable(getmetatable(self)))[".backup"]
  735. else
  736. backup = getmetatable(getmetatable(self))[".backup"]
  737. end
  738. backup.addTouchEventListener(self, ...)
  739. end
  740. function Widget:_addClickEventListener(callback)
  741. self:addClickEventListener(
  742. function()
  743. if not self.longTouchEvent then
  744. callback(self)
  745. end
  746. end
  747. )
  748. end
  749. function Widget:_addLongTouchEventListener(callback)
  750. local actionTAG = 123321
  751. self:addTouchEventListener(
  752. function(_, eventType)
  753. if eventType == 0 then
  754. self.longTouchEvent = false
  755. self:stopActionByTag(actionTAG)
  756. local action =
  757. performWithDelay(
  758. self,
  759. function()
  760. self.longTouchEvent = true
  761. callback(self)
  762. end,
  763. 0.7
  764. )
  765. action:setTag(actionTAG)
  766. elseif eventType == 2 or eventType == 3 then
  767. self:stopActionByTag(actionTAG)
  768. end
  769. end
  770. )
  771. end
  772. function Widget:addMouseOverTips(tips, offset, anchor, param, show)
  773. local checkCallback = param and param.checkCallback
  774. global.mouseEventController:registerMouseMoveEvent(
  775. self,
  776. {
  777. enter = function(touchPos)
  778. if not global.userInputController:isTouching() and self:isVisible() then
  779. if not checkCallback or checkCallback(touchPos) then
  780. showMouseOverTips(self, tips, offset, anchor)
  781. end
  782. end
  783. end,
  784. leave = function()
  785. hideMouseOverTips()
  786. end,
  787. show = show
  788. }
  789. )
  790. end
  791. function Button:loadTextureMouseOver(nfileName, mfileName, enterCB, leaveCB)
  792. local function checkResType(path)
  793. if global.SpriteFrameCache:getSpriteFrame(path) then
  794. return 1
  795. end
  796. if global.FileUtilCtl:isFileExist(path) then
  797. return 0
  798. end
  799. return 0
  800. end
  801. local function checkRes(path)
  802. local resType = checkResType(path)
  803. self:loadTextureNormal(path, resType)
  804. end
  805. self:setSwallowMouse(true)
  806. self:setMouseEnabled(true)
  807. self:addMouseEventListener(function(sender, eventType)
  808. if eventType == 1 then
  809. checkRes(mfileName)
  810. if enterCB then
  811. enterCB()
  812. end
  813. elseif eventType == 2 then
  814. checkRes(nfileName)
  815. if leaveCB then
  816. leaveCB()
  817. end
  818. end
  819. end)
  820. end
  821. function Button:setTitleText(str)
  822. local stProxy = global.Facade:retrieveProxy( global.ProxyTable.StringTable )
  823. local newStr = stProxy:fixNewLanguageString(str) or ""
  824. getmetatable(self)[".backup"].setTitleText(self, newStr)
  825. end
  826. function Widget:setString(str)
  827. local stProxy = global.Facade:retrieveProxy( global.ProxyTable.StringTable )
  828. local newStr = stProxy:fixNewLanguageString(str) or ""
  829. getmetatable(self)[".backup"].setString(self, newStr)
  830. end
  831. function Widget:createWithXML(str,data)
  832. local stProxy = global.Facade:retrieveProxy( global.ProxyTable.StringTable )
  833. local newStr = stProxy:fixNewLanguageString(str) or ""
  834. return getmetatable(self)[".backup"].createWithXML(self, newStr, data or {})
  835. end
  836. function Label:setString(str)
  837. local stProxy = global.Facade:retrieveProxy( global.ProxyTable.StringTable )
  838. local newStr = stProxy:fixNewLanguageString(str) or ""
  839. getmetatable(self)[".backup"].setString(self, newStr)
  840. end
  841. -- 调用来自 C++
  842. function g_OnEnterForColor(sender, param)
  843. -- 自动设置按钮下压效果
  844. if sender:getDescription() == "Button" and not sender.invalidZoomScale then
  845. sender:setZoomScale(-0.05)
  846. end
  847. end
  848. -- 调用来自 C++
  849. function g_ColorStyleRichText(sender, colorStyleID)
  850. end
  851. ----------------------------------------------------------------------------
  852. function convert2ZeroPos(node)
  853. local positionX = 0
  854. local positionY = 0
  855. if type(node:getPosition()) == "table" then
  856. positionX = node:getPosition().x
  857. positionY = node:getPosition().y
  858. else
  859. positionX = node:getPositionX()
  860. positionY = node:getPositionY()
  861. end
  862. local anchorPoint = node:getAnchorPoint()
  863. local contentSize = node:getContentSize()
  864. local newPosition = cc.p(positionX - anchorPoint.x * contentSize.width, positionY - anchorPoint.y * contentSize.height)
  865. newPosition = cc.p(math.floor(newPosition.x), math.floor(newPosition.y))
  866. node:setAnchorPoint(cc.p(0, 0))
  867. node:setPosition(newPosition)
  868. return newPosition
  869. end
  870. function showWorldTips(tips, worldPos, anchorPoint)
  871. hideMouseOverTips()
  872. local layoutTips = ccui.Layout:create()
  873. layoutTips:setBackGroundColor(cc.c3b(0, 0, 0))
  874. layoutTips:setBackGroundColorType(1)
  875. layoutTips:setBackGroundColorOpacity(100)
  876. local imageFrame = ccui.ImageView:create()
  877. layoutTips:addChild(imageFrame)
  878. imageFrame:loadTexture(global.MMO.PATH_RES_PUBLIC .. "1900000582.png")
  879. imageFrame:setScale9Enabled(true)
  880. imageFrame:setCapInsets({x = 10, y = 10, width = 10, height = 10})
  881. if type(tips) == "function" then
  882. tips = tips()
  883. end
  884. local RichTextHelp = require("util/RichTextHelp")
  885. local fontSize = SL:GetMetaValue("GAME_DATA","DEFAULT_FONT_SIZE") or 16
  886. local textTips = RichTextHelp:CreateRichTextWithFCOLOR(tips, 1136, fontSize, cc.c3b(0xff, 0xff, 0xff))
  887. layoutTips:addChild(textTips)
  888. textTips:formatText()
  889. local rcontentSize = textTips:getContentSize()
  890. local lcontentSize = {width = rcontentSize.width+10, height = rcontentSize.height+10}
  891. layoutTips:setContentSize(lcontentSize)
  892. textTips:setAnchorPoint(cc.p(0.5, 0.5))
  893. textTips:setPosition(cc.p(lcontentSize.width/2, lcontentSize.height/2))
  894. imageFrame:setContentSize(lcontentSize)
  895. imageFrame:setPosition(cc.p(lcontentSize.width/2, lcontentSize.height/2))
  896. layoutTips:setAnchorPoint(anchorPoint)
  897. layoutTips:setPosition(worldPos)
  898. convert2ZeroPos(layoutTips)
  899. layoutTips:setName("__MouseTips")
  900. global.Facade:sendNotification(global.NoticeTable.Layer_Notice_AddChild, {child = layoutTips})
  901. end
  902. function showMouseOverTips(widget, tips, offset, anchor)
  903. hideMouseOverTips()
  904. offset = offset or {x=0, y=0}
  905. anchor = anchor or {x=0.5, y=0.5}
  906. local layoutTips = ccui.Layout:create()
  907. layoutTips:setBackGroundColor(cc.c3b(0, 0, 0))
  908. layoutTips:setBackGroundColorType(1)
  909. layoutTips:setBackGroundColorOpacity(100)
  910. local imageFrame = ccui.ImageView:create()
  911. layoutTips:addChild(imageFrame)
  912. imageFrame:loadTexture(global.MMO.PATH_RES_PUBLIC .. "1900000582.png")
  913. imageFrame:setScale9Enabled(true)
  914. imageFrame:setCapInsets({x = 10, y = 10, width = 10, height = 10})
  915. if type(tips) == "function" then
  916. tips = tips()
  917. end
  918. local RichTextHelp = require("util/RichTextHelp")
  919. local fontSize = SL:GetMetaValue("GAME_DATA","DEFAULT_FONT_SIZE") or 16
  920. local textTips = RichTextHelp:CreateRichTextWithFCOLOR(tips, 1136, fontSize, cc.c3b(0xff, 0xff, 0xff))
  921. layoutTips:addChild(textTips)
  922. textTips:formatText()
  923. local rcontentSize = textTips:getContentSize()
  924. local lcontentSize = {width = rcontentSize.width+10, height = rcontentSize.height+10}
  925. layoutTips:setContentSize(lcontentSize)
  926. textTips:setAnchorPoint(cc.p(0.5, 0.5))
  927. textTips:setPosition(cc.p(lcontentSize.width/2, lcontentSize.height/2))
  928. imageFrame:setContentSize(lcontentSize)
  929. imageFrame:setPosition(cc.p(lcontentSize.width/2, lcontentSize.height/2))
  930. local contentSize = widget:getContentSize()
  931. local anchorPoint = widget:getAnchorPoint()
  932. local worldPos = widget:getWorldPosition()
  933. local fixWorldPos = cc.pAdd(worldPos, cc.p((0.5-anchorPoint.x)*contentSize.width, (1-anchorPoint.y)*contentSize.height + lcontentSize.height * anchor.y))
  934. layoutTips:setAnchorPoint(anchor)
  935. layoutTips:setPosition(cc.pAdd(fixWorldPos, offset))
  936. convert2ZeroPos(layoutTips)
  937. layoutTips:setName("__MouseTips")
  938. global.Facade:sendNotification(global.NoticeTable.Layer_Notice_AddChild, {child = layoutTips})
  939. end
  940. function hideMouseOverTips()
  941. global.Facade:sendNotification(global.NoticeTable.Layer_Notice_RemoveChild, "__MouseTips")
  942. end
  943. function GetTimeInMS()
  944. local socket = require "socket"
  945. return socket.gettime()
  946. end
  947. local Widget = ccui.Widget
  948. function Widget:cloneEx()
  949. local ret = self:clone()
  950. ret.UserData = self.UserData
  951. local function setChildrenUserData(targetNode, originNode)
  952. local targetChildren = targetNode:getChildren()
  953. local originChildren = originNode:getChildren()
  954. if #targetChildren == 0 or #originChildren == 0 then
  955. return nil
  956. end
  957. for key, value in pairs(targetChildren) do
  958. targetChildren[key].UserData = originChildren[key].UserData
  959. setChildrenUserData(targetChildren[key], originChildren[key])
  960. end
  961. end
  962. setChildrenUserData(ret, self)
  963. cloneLabelRender(self,ret)
  964. return ret
  965. end
  966. function cloneLabelRender(originNode,targetNode)
  967. if originNode:getDescription() == "BmpText" then
  968. GUI:SetBmpTextProperties(targetNode)
  969. local originNodeRenderer = originNode:getVirtualRenderer()
  970. local fontColor = originNodeRenderer:getColor()
  971. targetNode:setBMFontFilePath()
  972. targetNode:setFontSize(12)
  973. targetNode:setTextColor(fontColor)
  974. end
  975. local targetChildren = targetNode:getChildren()
  976. local originChildren = originNode:getChildren()
  977. if #targetChildren == 0 or #originChildren == 0 then
  978. return nil
  979. end
  980. for i,ch in ipairs(targetChildren) do
  981. local orich = originChildren[i]
  982. cloneLabelRender(orich,ch)
  983. end
  984. end
  985. local function _compareBracket(str)
  986. local offset = 1
  987. local strIdx = 2
  988. local len = string.len(str)
  989. local IDX = 1
  990. while 1 do
  991. IDX = IDX + 1
  992. if IDX > 10 then
  993. return nil
  994. end
  995. local lIdx = string.find(str, "%(", strIdx) or len
  996. local rIdx = string.find(str, "%)", strIdx) or len
  997. if lIdx < rIdx then
  998. strIdx = lIdx + 1
  999. offset = offset + 1
  1000. else
  1001. strIdx = rIdx + 1
  1002. offset = offset - 1
  1003. end
  1004. if offset == 0 then
  1005. strIdx = strIdx - 1
  1006. break
  1007. end
  1008. if strIdx > string.len(str) then
  1009. print(">>>>>>>condition () not compare", str, IDX)
  1010. return nil
  1011. end
  1012. end
  1013. return strIdx
  1014. end
  1015. local function _stringtoCondition(str)
  1016. local rawCondition = string.split(str, "#")
  1017. local conditon = tonumber(str)
  1018. local conditionType = math.floor(conditon/100000)
  1019. local conditionkey = conditon%100000
  1020. local condition = {}
  1021. condition.dType = 1
  1022. condition.type = tonumber(conditionType)
  1023. condition.key1 = tonumber(conditon%100000) or 0
  1024. condition.key2 = 0
  1025. condition.key3 = 0
  1026. return condition
  1027. end
  1028. function ParseConditionStr(str)
  1029. if not str or str == "" then
  1030. return nil
  1031. end
  1032. local conditions = {}
  1033. local idx = 0
  1034. while 1 do
  1035. idx = idx + 1
  1036. if str == "" or idx > 100 then
  1037. break
  1038. end
  1039. local condition = nil
  1040. local len = string.len(str)
  1041. local andIdx = string.find(str, "#")
  1042. local orIdx = string.find(str, "|")
  1043. local splitIdx = math.min(andIdx or len + 1, orIdx or len + 1)
  1044. local fchar = string.sub(str, 0, 1)
  1045. if fchar == "(" then
  1046. local rightBracketIdx = _compareBracket(str)
  1047. if not rightBracketIdx then
  1048. rightBracketIdx = string.len(str)
  1049. print(">>Bracket compare error:", str)
  1050. end
  1051. condition = ParseConditionStr(string.sub(str, 2, rightBracketIdx - 1))
  1052. conditions[idx] = condition
  1053. local fchar = string.sub(str, rightBracketIdx + 1, rightBracketIdx + 1)
  1054. str = string.sub(str, rightBracketIdx + 2)
  1055. andIdx = string.find(fchar, "#")
  1056. orIdx = string.find(fchar, "|")
  1057. else
  1058. local splitIdx = math.min(andIdx or len + 1, orIdx or len + 1)
  1059. local conditionStr = string.sub(str, 1, splitIdx - 1)
  1060. -- print("idx", andIdx, orIdx, len, str, conditionStr)
  1061. condition = _stringtoCondition(conditionStr)
  1062. conditions[idx] = condition
  1063. str = string.sub(str, splitIdx + 1)
  1064. end
  1065. if condition then
  1066. if andIdx and (not orIdx or orIdx > andIdx) then
  1067. condition.opType = 1
  1068. end
  1069. if orIdx and (not andIdx or andIdx > orIdx) then
  1070. condition.opType = 2
  1071. end
  1072. end
  1073. end
  1074. if #conditions == 0 then
  1075. return nil
  1076. end
  1077. if #conditions == 1 then
  1078. return conditions[1]
  1079. end
  1080. local data = {}
  1081. data.dType = 2
  1082. data.conditions = conditions
  1083. return data
  1084. end
  1085. function SetRichText(txtObj, richText, color, bAutoLine)
  1086. if bAutoLine == nil then
  1087. bAutoLine = true
  1088. end
  1089. local RichHelp = require("util/RichTextHelp")
  1090. txtObj:setVisible(false)
  1091. local resName = txtObj:getName()
  1092. local richName = resName .. "__rich"
  1093. local richObj = txtObj:getParent():getChildByName(richName)
  1094. if richObj then
  1095. richObj:removeFromParent()
  1096. richObj = nil
  1097. end
  1098. local fontSize = txtObj:getFontSize()
  1099. color = color or GetColorHexFromRBG(txtObj:getTextColor())
  1100. local size = txtObj:getLayoutSize()
  1101. if size.width == 0 then
  1102. print(">>>>>>>SetRichText err!!" .. richText, richName)
  1103. return
  1104. end
  1105. local width = size.width
  1106. if not bAutoLine then
  1107. width = 9999
  1108. end
  1109. local richObj = RichHelp:CreateRichTextWithXML(richText, width, fontSize, color)
  1110. if richObj then
  1111. local ap = txtObj:getAnchorPoint()
  1112. local posX = txtObj:getPositionX()
  1113. local posY = txtObj:getPositionY()
  1114. txtObj:getParent():addChild(richObj)
  1115. richObj:setAnchorPoint(ap)
  1116. richObj:formatText()
  1117. richObj:setPosition(cc.p(posX, posY))
  1118. richObj:setName(richName)
  1119. else
  1120. print("!!!!!!!!!!!!!!richText error", richText)
  1121. end
  1122. return richObj
  1123. end
  1124. function CloneShadow(sprite)
  1125. if not sprite then
  1126. return
  1127. end
  1128. sprite:setBlendFunc({src = gl.DST_COLOR, dst = gl.ONE_MINUS_SRC_ALPHA})
  1129. sprite:setRotationSkewX(40.0)
  1130. sprite:setScaleY(0.8)
  1131. sprite:setOpacity(150)
  1132. sprite:setColor(cc.Color3B.BLACK)
  1133. global.Facade:sendNotification(global.NoticeTable.HighLightNodeShader, sprite, global.MMO.SHADER_TYPE_SHADOW)
  1134. end
  1135. --中文转换成竖着显示
  1136. function ChineseToVertical(str)
  1137. local UTF8 = require("util/utf8")
  1138. local len = UTF8:length(str)
  1139. local newStr = ""
  1140. for i = 1, len do
  1141. newStr = newStr .. UTF8:sub(str, i, 1)
  1142. if i < len then
  1143. newStr = newStr .. "\n"
  1144. end
  1145. end
  1146. return newStr
  1147. end
  1148. --哈希表转成按数组
  1149. function HashToSortArray(hashTab, sortFunc)
  1150. if hashTab == nil or type(hashTab) ~= "table" then
  1151. return nil
  1152. end
  1153. local sortTable = {}
  1154. for _, v in pairs(hashTab) do
  1155. table.insert(sortTable, v)
  1156. end
  1157. if sortFunc then
  1158. table.sort(sortTable, sortFunc)
  1159. end
  1160. return sortTable
  1161. end
  1162. function ui_delegate(nativeUI)
  1163. if (nativeUI == nil) then
  1164. return nil
  1165. end
  1166. local function getChildInSubNodes(nodeTable, key)
  1167. if #nodeTable == 0 then
  1168. return nil
  1169. end
  1170. local child = nil
  1171. local subNodeTable = {}
  1172. for _, v in ipairs(nodeTable) do
  1173. child = GUI:getChildByName(v, key)
  1174. if (child) then
  1175. return child
  1176. end
  1177. end
  1178. for _, v in ipairs(nodeTable) do
  1179. local subNodes = GUI:getChildren(v)
  1180. if #subNodes ~= 0 then
  1181. for _, v1 in ipairs(subNodes) do
  1182. table.insert(subNodeTable, v1)
  1183. end
  1184. end
  1185. end
  1186. return getChildInSubNodes(subNodeTable, key)
  1187. end
  1188. local function getChildByKey(parent, key)
  1189. return getChildInSubNodes({parent}, key)
  1190. end
  1191. local tt = {
  1192. __index = function(t, k)
  1193. local u = getChildByKey(t.nativeUI, k)
  1194. rawset(t, k, u)
  1195. return u
  1196. end
  1197. }
  1198. local r = {["nativeUI"] = nativeUI}
  1199. setmetatable(r, tt)
  1200. return r
  1201. end
  1202. function getChildInSubNodes(nodeTable, key)
  1203. if #nodeTable == 0 then
  1204. return nil
  1205. end
  1206. local child = nil
  1207. local subNodeTable = {}
  1208. for _, v in ipairs(nodeTable) do
  1209. child = v:getChildByName(key)
  1210. if (child) then
  1211. return child
  1212. end
  1213. end
  1214. for _, v in ipairs(nodeTable) do
  1215. local subNodes = v:getChildren()
  1216. if #subNodes ~= 0 then
  1217. for _, v1 in ipairs(subNodes) do
  1218. table.insert(subNodeTable, v1)
  1219. end
  1220. end
  1221. end
  1222. return getChildInSubNodes(subNodeTable, key)
  1223. end
  1224. function checkNotchPhone()
  1225. local visibleSize = global.Director:getVisibleSize()
  1226. local glView = global.Director:getOpenGLView()
  1227. local viewRect = glView:getVisibleRect()
  1228. local safeRect = global.Director:getSafeAreaRect()
  1229. local notch = (math.abs(viewRect.width - safeRect.width) > 5)
  1230. local deviceRotation = global.L_GameEnvManager:GetDeviceRotation()
  1231. if notch then
  1232. local notchWidth = 50
  1233. viewRect.x = (deviceRotation == 1 and notchWidth or 0)
  1234. viewRect.y = 0
  1235. viewRect.width = viewRect.width - notchWidth
  1236. viewRect.height = visibleSize.height
  1237. end
  1238. return notch, viewRect
  1239. end
  1240. -- 根据服务器json参数转换外观
  1241. function TransformFeatureByJson(jsonData)
  1242. local ret = {
  1243. clothID = 0,
  1244. hairID = 0,
  1245. weaponID = 0,
  1246. shieldID = 0,
  1247. mountID = 0,
  1248. wingsID = 0,
  1249. weaponEff = 0,
  1250. shieldEffect = 0,
  1251. leftWeaponID = 0,
  1252. leftWeaponEff = 0,
  1253. }
  1254. ret.clothID = jsonData.clothID
  1255. ret.weaponID = jsonData.weaponID
  1256. -- 左武器
  1257. ret.leftWeaponID = jsonData.leftWeaponID
  1258. ret.leftWeaponEff = jsonData.leftWeaponEff
  1259. -- 发型
  1260. local hairID = jsonData.Hair
  1261. -- 骑马
  1262. ret.mountID = jsonData.mountID
  1263. -- 幻武 时装 翅膀 足迹 武器特效
  1264. local wingsID = jsonData.clothEff
  1265. local weaponEff = jsonData.weaponEff
  1266. local capID = jsonData.Cap
  1267. local mountEff = jsonData.mountEff --足迹特效
  1268. local mountCloth = jsonData.mountCloth --骑马人物外观
  1269. local shieldID = jsonData.shieldID --盾牌
  1270. local shieldEffect = jsonData.shieldEffect --盾牌特效
  1271. if hairID and hairID > 0 then
  1272. ret.hairID = hairID
  1273. end
  1274. if capID and capID > 0 then
  1275. ret.capID = capID
  1276. end
  1277. if wingsID and wingsID > 0 then
  1278. ret.wingsID = wingsID
  1279. end
  1280. if weaponEff and weaponEff > 0 then
  1281. ret.weaponEff = weaponEff
  1282. end
  1283. if mountEff and mountEff > 0 then
  1284. ret.mountEff = mountEff
  1285. end
  1286. if mountCloth and mountCloth > 0 then
  1287. ret.mountCloth = mountCloth
  1288. end
  1289. if shieldID and shieldID > 0 then --盾牌
  1290. ret.shieldID = shieldID
  1291. end
  1292. if shieldEffect and shieldEffect > 0 then --盾牌特效
  1293. ret.shieldEffect = shieldEffect
  1294. end
  1295. return ret
  1296. end
  1297. --划线
  1298. function CreateDrawLine(size, beginPos, endPos, color)
  1299. size = size or 1
  1300. color = color or cc.c4f(1, 0, 0, 1)
  1301. local drowRoot = cc.DrawNode:create(size)
  1302. drowRoot:drawLine(beginPos, endPos, color)
  1303. return drowRoot
  1304. end
  1305. --[[
  1306. README:
  1307. data.dataLength 总长度
  1308. 或者data.items长度
  1309. data.pageLength 每页长度
  1310. data.isShowLat 是否显示上页最后一项
  1311. ]]
  1312. function GetPageData(data)
  1313. if not data then
  1314. return nil
  1315. end
  1316. local length = 0
  1317. if data.dataLength then
  1318. length = data.dataLength
  1319. end
  1320. if data.items then
  1321. length = #data.items
  1322. end
  1323. local pageData = {}
  1324. local page = 1
  1325. local pageLength = data.pageLength or global.MMO.NPC_STORE_LIST_LENGTH
  1326. local isShowLastItem = data.isShowLast
  1327. if isShowLastItem then
  1328. pageLength = pageLength - 1
  1329. end
  1330. local maxPage = math.ceil(length/pageLength)
  1331. for index=page,maxPage do
  1332. local beginItem = (index - 1)*pageLength + 1
  1333. local endItem = index*pageLength
  1334. if isShowLastItem then
  1335. endItem = index*pageLength + 1
  1336. end
  1337. if index == maxPage then
  1338. endItem = length
  1339. end
  1340. pageData[index] = {
  1341. beginItem = beginItem,
  1342. endItem = endItem
  1343. }
  1344. end
  1345. return pageData
  1346. end
  1347. --文本提示框
  1348. function GetWordTips(data)
  1349. local str = data.str or "" --文本
  1350. local width = data.width or 800 --文本宽度
  1351. local richTextHelp = require("util/RichTextHelp")
  1352. local tips = ccui.Layout:create()
  1353. tips:setBackGroundImage(global.MMO.PATH_RES_PRIVATE .. "item_tips/bg_tipszy_05.png")
  1354. tips:setBackGroundImageCapInsets({x = 44, y = 57, width = 47, height = 100})
  1355. tips:setBackGroundImageScale9Enabled(true)
  1356. tips:setAnchorPoint(0, 0)
  1357. local richText = richTextHelp:CreateRichTextWithXML(str, width, 16, "#ffffff")
  1358. richText:formatText()
  1359. richText:setAnchorPoint(0, 1)
  1360. richText:setName("richText")
  1361. tips:addChild(richText)
  1362. local textSize = richText:getContentSize()
  1363. richText:setPosition(10, textSize.height + 10)
  1364. if textSize.width < width then
  1365. width = textSize.width
  1366. end
  1367. tips:setContentSize(cc.size(width + 20, textSize.height + 20))
  1368. return tips
  1369. end
  1370. function CalcCameraZoom( camera )
  1371. local winSize = global.Director:getWinSize()
  1372. local rtPos = cc.p( winSize.width, winSize.height ) -- right-top
  1373. local lbPos = cc.p( 0, 0 ) -- left-bottom
  1374. local rtPosGL = camera:projectGL( rtPos )
  1375. local lbPosGL = camera:projectGL( lbPos )
  1376. local zoomWidth = rtPosGL.x - lbPosGL.x
  1377. local zoomHeight = rtPosGL.y - lbPosGL.y
  1378. local scaleX = winSize.width / zoomWidth
  1379. local scaleY = winSize.height / zoomHeight
  1380. return scaleX, scaleY
  1381. end
  1382. function Screen2World( srcPos )
  1383. local camera = global.gameMapController:GetViewCamera()
  1384. if not camera then
  1385. return nil
  1386. end
  1387. local scaleX, scaleY = CalcCameraZoom( camera )
  1388. local p = cc.p( srcPos.x * scaleX, srcPos.y * scaleY )
  1389. local cameraPos = cc.p(camera:getPosition())
  1390. local winSize = global.Director:getWinSize()
  1391. local centerOfView = cc.p( winSize.width * 0.5 * scaleX, winSize.height * 0.5 * scaleY )
  1392. return cc.pSub(cc.pAdd( cameraPos, p ), centerOfView )
  1393. end
  1394. function World2Screen( srcPos )
  1395. local camera = global.gameMapController:GetViewCamera()
  1396. if not camera then
  1397. return nil
  1398. end
  1399. local scaleX, scaleY = CalcCameraZoom( camera )
  1400. local cameraPos = cc.p(camera:getPosition())
  1401. local winSize = global.Director:getWinSize()
  1402. local centerOfView = cc.p( winSize.width * 0.5 * scaleX, winSize.height * 0.5 * scaleY )
  1403. local p = cc.pSub( cc.pAdd( srcPos, centerOfView ), cameraPos )
  1404. p.x = p.x / scaleX
  1405. p.y = p.y / scaleY
  1406. return p
  1407. end
  1408. function RegisterNodeMovable( node, param )
  1409. local itemMoveState = {
  1410. begin = 1,
  1411. moving = 2,
  1412. end_move = 3,
  1413. }
  1414. local pressCallBack = param.pressCallBack
  1415. local clickCallBack = param.clickCallBack
  1416. local replaceClick = param.replaceClick
  1417. local replacePress = param.replacePress
  1418. local doubleEventCallBack = param.doubleEventCallBack
  1419. local nodeFrom = param.nodeFrom
  1420. local beginMoveCallBack = param.beginMoveCall
  1421. local endMoveCallBack = param.endMoveCall
  1422. local cancelMoveCallBack = param.cancelMoveCall
  1423. local itemData = param.itemData
  1424. local isNeedItemData = param.dataNeed
  1425. local isNode = param.moveNode
  1426. local skillId = param.skillId
  1427. local function resetMoveState( mySelf, bool )
  1428. if mySelf and not tolua.isnull(mySelf) then
  1429. mySelf._movingState = bool
  1430. if bool then
  1431. if beginMoveCallBack then
  1432. beginMoveCallBack( mySelf, bool )
  1433. end
  1434. else
  1435. if endMoveCallBack then
  1436. endMoveCallBack( mySelf, bool )
  1437. end
  1438. end
  1439. end
  1440. end
  1441. local function SetGoodItemState(state, movePos)
  1442. if isNeedItemData and not itemData then
  1443. return
  1444. end
  1445. if itemMoveState.begin == state then
  1446. resetMoveState(node,true)
  1447. global.Facade:sendNotification(global.NoticeTable.Layer_ItemTips_Close)
  1448. global.Facade:sendNotification(global.NoticeTable.Layer_Moved_Begin,{
  1449. pos = movePos,
  1450. itemData = itemData,
  1451. cancelCallBack = cancelMoveCallBack,
  1452. from = nodeFrom,
  1453. movingNode = isNode:clone(),
  1454. skillId = skillId
  1455. })
  1456. elseif itemMoveState.moving == state then
  1457. elseif itemMoveState.end_move == state then
  1458. global.Facade:sendNotification(global.NoticeTable.Layer_Moved_End, movePos)
  1459. end
  1460. end
  1461. local function clickEventCallBack(clickNode, eventtype)
  1462. --不在道具移动
  1463. if clickNode._movingState then
  1464. return
  1465. end
  1466. local panelPos = clickNode:getWorldPosition()
  1467. if global.isWinPlayMode then
  1468. SetGoodItemState(itemMoveState.begin, panelPos)
  1469. end
  1470. if clickCallBack then
  1471. clickCallBack(clickNode)
  1472. end
  1473. end
  1474. local function pressEventCallBack()
  1475. --不在道具移动
  1476. if node._movingState then
  1477. return
  1478. end
  1479. local panelPos = node:getWorldPosition()
  1480. if global.isWinPlayMode then
  1481. SetGoodItemState(itemMoveState.begin, panelPos)
  1482. end
  1483. if pressCallBack then
  1484. pressCallBack(node)
  1485. end
  1486. end
  1487. local clickEventCallBack = replaceClick or clickEventCallBack
  1488. local pressEventCallBack = replacePress or pressEventCallBack
  1489. local isEventPress = false
  1490. local isMoved = true
  1491. local hasEventCallOnTouchBegin = false --只有在响应了touchbegin 时才会去响应延时方法 因为在延时后 鼠标事件的 状态已经被置掉
  1492. local isMobile = not global.isWinPlayMode
  1493. local function delayCallback()
  1494. isEventPress = true
  1495. if pressEventCallBack then
  1496. if not pressEventCallBack then
  1497. return false
  1498. end
  1499. if not isMoved then
  1500. pressEventCallBack()
  1501. return false
  1502. end
  1503. local movedPos = node:getTouchMovePosition()
  1504. local beganPos = node:getTouchBeganPosition()
  1505. local diff = cc.pSub(movedPos, beganPos)
  1506. local distSq = cc.pLengthSQ(diff)
  1507. if distSq <= 100 then
  1508. pressEventCallBack()
  1509. end
  1510. end
  1511. end
  1512. local function touchEvent( touch, eventType )
  1513. if global.isWinPlayMode then
  1514. local ItemMoveProxy = global.Facade:retrieveProxy(global.ProxyTable.ItemMoveProxy)
  1515. local itemMoving = ItemMoveProxy:GetMovingItemState()
  1516. if itemMoving then --在道具移动中
  1517. return
  1518. end
  1519. end
  1520. if eventType == 0 then
  1521. isEventPress = false
  1522. isMoved = false
  1523. hasEventCallOnTouchBegin = true
  1524. if pressEventCallBack then
  1525. performWithDelay(node, delayCallback, global.MMO.CLICK_DOUBLE_TIME)
  1526. end
  1527. elseif eventType == 1 then
  1528. local movedPos = node:getTouchMovePosition()
  1529. local beganPos = node:getTouchBeganPosition()
  1530. local diff = cc.pSub(movedPos, beganPos)
  1531. local distSq = cc.pLengthSQ(diff)
  1532. if not isMoved and distSq > 100 then
  1533. isMoved = true
  1534. if isMobile then
  1535. local beginMovePos = node:getWorldPosition()
  1536. SetGoodItemState(itemMoveState.begin, beginMovePos)
  1537. end
  1538. end
  1539. if isMobile then
  1540. local movedPos = node:getTouchMovePosition()
  1541. global.Facade:sendNotification(global.NoticeTable.Layer_Moved_Moving,{pos = movedPos})
  1542. end
  1543. elseif eventType == 2 then
  1544. node:stopAllActions()
  1545. if not isMoved then
  1546. if not isEventPress then
  1547. -- 判断是否有双击事件
  1548. if doubleEventCallBack then
  1549. -- 记录上一次点击时间
  1550. if not node._lastClickTime then
  1551. node._lastClickTime = true
  1552. -- 记录单击触发
  1553. -- 记录进入此处时的状态,避免在延时操作后状态被改变
  1554. local stateOnbegin = hasEventCallOnTouchBegin
  1555. node._clickDelayHandler =
  1556. PerformWithDelayGlobal(
  1557. function()
  1558. if clickEventCallBack and stateOnbegin then
  1559. clickEventCallBack(node, eventType)
  1560. end
  1561. node._lastClickTime = nil
  1562. end,
  1563. global.MMO.CLICK_DOUBLE_TIME
  1564. )
  1565. else
  1566. if node._clickDelayHandler then
  1567. UnSchedule(node._clickDelayHandler)
  1568. node._clickDelayHandler = nil
  1569. end
  1570. if doubleEventCallBack then
  1571. doubleEventCallBack()
  1572. end
  1573. node._lastClickTime = nil
  1574. end
  1575. else
  1576. local stateOnbegin = hasEventCallOnTouchBegin
  1577. if clickEventCallBack and stateOnbegin then
  1578. clickEventCallBack(node, eventType)
  1579. end
  1580. end
  1581. end
  1582. else
  1583. if isMobile then
  1584. local endPos = node:getTouchEndPosition()
  1585. SetGoodItemState(itemMoveState.end_move, endPos)
  1586. end
  1587. end
  1588. hasEventCallOnTouchBegin = false
  1589. elseif eventType == 3 then
  1590. if isMobile then
  1591. local endPos = node:getTouchEndPosition()
  1592. SetGoodItemState(itemMoveState.end_move, endPos)
  1593. end
  1594. hasEventCallOnTouchBegin = false
  1595. end
  1596. end
  1597. node:addTouchEventListener( touchEvent )
  1598. end
  1599. function CreateStaticUIModel(sex, feature, scale, params)
  1600. SL:RequireFile(SLDefine.LUAFile.LUA_FILE_UIMODEL)
  1601. return UIModel.main(sex, feature, scale, params)
  1602. end
  1603. function ParseModelEffect(effect)
  1604. local effectSet = {}
  1605. if not effect then
  1606. return effectSet
  1607. end
  1608. if type(effect) == "number" then
  1609. effect = effect.."#0"
  1610. end
  1611. local effectArry = string.split(effect or "","&")
  1612. local isShowLook = tonumber(effectArry[2]) ~= 0
  1613. local effectList = string.split(effectArry[1] or "", "|")
  1614. for i=1,#effectList do
  1615. local effectParam = effectList[i]
  1616. local effectParamPar = string.split(effectParam or "", "#")
  1617. local effectData = {
  1618. effectId = effectParamPar[1] and tonumber(effectParamPar[1]) or 0,
  1619. zOrder = effectParamPar[2] and tonumber(effectParamPar[2]) or 0,
  1620. offX = effectParamPar[3] and tonumber(effectParamPar[3]) or 0,
  1621. offY = effectParamPar[4] and tonumber(effectParamPar[4]) or 0,
  1622. scale = effectParamPar[6] and tonumber(effectParamPar[6]) or 1 --"PC缩放#手机缩放"
  1623. }
  1624. if global.isWinPlayMode then
  1625. effectData.scale = effectParamPar[5] and tonumber(effectParamPar[5]) or 1
  1626. effectData.offX = effectParamPar[7] and tonumber(effectParamPar[7]) or effectData.offX
  1627. effectData.offY = effectParamPar[8] and tonumber(effectParamPar[8]) or effectData.offY
  1628. end
  1629. table.insert(effectSet, effectData)
  1630. end
  1631. return effectSet, isShowLook
  1632. end
  1633. function GetItemDataNumber(typeId,param)
  1634. local count = 0
  1635. if not typeId then
  1636. return 0
  1637. end
  1638. local countFamilar = param and param.realbool
  1639. if typeId < 100 then
  1640. local MoneyProxy = global.Facade:retrieveProxy(global.ProxyTable.MoneyProxy)
  1641. count = MoneyProxy:GetMoneyCountById(typeId, countFamilar)
  1642. else
  1643. local BagProxy = global.Facade:retrieveProxy(global.ProxyTable.Bag)
  1644. count = BagProxy:GetItemCountByIndex(typeId, countFamilar)
  1645. local QuickUseProxy = global.Facade:retrieveProxy(global.ProxyTable.QuickUseProxy)
  1646. count = count + QuickUseProxy:GetQuickUseItemNum(typeId, countFamilar)
  1647. end
  1648. return count
  1649. end
  1650. -- articleType: 禁止类型(有些绑定可以进行操作)
  1651. function CheckItemisBind(itemData, articleType)
  1652. if not itemData then
  1653. return false, false
  1654. end
  1655. -- release_print("===CheckItemisBind: ", itemData.Bind, global.ConstantConfig.bangdingguize or "")
  1656. local cfgArticle = itemData.Article or ""
  1657. if (itemData.Bind and itemData.Bind > 0) or string.len(cfgArticle) > 0 then
  1658. local isBindSelf = false
  1659. if itemData.Bind == itemData.Index then
  1660. isBindSelf = true
  1661. end
  1662. local isMeetType = false
  1663. if itemData.Bind and itemData.Bind > 0 and articleType and articleType > 0 then
  1664. isMeetType = CheckBit(itemData.Bind,articleType-1)
  1665. end
  1666. local bindParam = SL:GetMetaValue("GAME_DATA","bangdingguize") or ""
  1667. local bindArticles = string.split(bindParam,"&")
  1668. local isBind = true
  1669. local checkCount = 0
  1670. local ItemConfigProxy = global.Facade:retrieveProxy( global.ProxyTable.ItemConfigProxy )
  1671. for i,v in ipairs(bindArticles) do
  1672. if v and v ~= "" then
  1673. local vParam = string.split(v,"#")
  1674. isBind = false
  1675. for ii,vv in ipairs(vParam) do
  1676. if tonumber(vv) then
  1677. checkCount = checkCount + 1
  1678. if itemData.Bind and itemData.Bind > 0 then
  1679. isBind = CheckBit(itemData.Bind,tonumber(vv)-1)
  1680. end
  1681. if not isBind then
  1682. local itemArticleType = ItemConfigProxy:GetBindArticleTypeToItemArticle(tonumber(vv))
  1683. if itemArticleType then
  1684. local checkArticleType = {[itemArticleType]=true}
  1685. if ItemConfigProxy:GetItemArticle(itemData.Index,checkArticleType) then
  1686. isBind = true
  1687. end
  1688. end
  1689. end
  1690. if isBind then
  1691. break
  1692. end
  1693. end
  1694. end
  1695. end
  1696. if isBind == false then
  1697. break
  1698. end
  1699. end
  1700. if not itemData.Bind or itemData.Bind <= 0 then
  1701. if checkCount == 0 then
  1702. isBind = false
  1703. end
  1704. end
  1705. return isBind, isBindSelf, isMeetType
  1706. else
  1707. return false, false, false
  1708. end
  1709. end
  1710. function GetSimpleNumber(n)
  1711. local unitFunc = function( num,pointBit )
  1712. if pointBit == 0 then
  1713. return math.floor(num)
  1714. end
  1715. local iNum,fNum = math.modf(num)
  1716. local fDecimal = math.pow(10, pointBit)
  1717. local newNum = tostring(fNum*fDecimal)
  1718. newNum = tonumber(newNum)
  1719. local newFNum = math.floor(newNum)
  1720. newFNum = tostring( newFNum )
  1721. newFNum = tonumber( newFNum )
  1722. local newINum = iNum + (newFNum/fDecimal)
  1723. return newINum
  1724. end
  1725. if n >= 100000000 then
  1726. return string.format("%s%s", unitFunc(n/100000000,2), GET_STRING(1045))
  1727. end
  1728. if n >= 100000 then
  1729. return string.format("%d%s", n/10000, GET_STRING(1005))
  1730. end
  1731. if n >= 10000 then
  1732. return string.format("%s%s", unitFunc(n/10000,2), GET_STRING(1005))
  1733. end
  1734. return tostring(n)
  1735. end
  1736. function GetJobName(job)
  1737. if not job then return nil end
  1738. if job == 4 then
  1739. return GET_STRING(1100)
  1740. elseif job >= 5 and job <= 15 then
  1741. local jobData = SL:GetMetaValue("GAME_DATA", "MultipleJobSetMap")[job]
  1742. local isOpen = jobData and jobData.isOpen
  1743. local str = isOpen and jobData.name or string.format("未命名%s", job)
  1744. return str
  1745. end
  1746. return GET_STRING(1067+job)
  1747. end
  1748. function ShowSystemTips(str)
  1749. global.Facade:sendNotification(global.NoticeTable.SystemTips, str)
  1750. end
  1751. function ShowDebugSystemTips(data)
  1752. global.Facade:sendNotification(global.NoticeTable.DebugSystemTips, data)
  1753. end
  1754. function ShowSystemChat(str, FColor, BColor, mt)
  1755. local ChatProxy = global.Facade:retrieveProxy(global.ProxyTable.Chat)
  1756. local mdata = {
  1757. Msg = str,
  1758. FColor = FColor or 249,
  1759. BColor = BColor or 255,
  1760. ChannelId = ChatProxy.CHANNEL.System,
  1761. mt = mt or ChatProxy.MSG_TYPE.SystemTips,
  1762. }
  1763. global.Facade:sendNotification(global.NoticeTable.AddChatItem, mdata)
  1764. end
  1765. function CheckCanDoSomething(noTips)
  1766. local canDoSomething = true
  1767. local StallProxy = global.Facade:retrieveProxy(global.ProxyTable.StallProxy)
  1768. local isTrading = StallProxy:GetMyTradingStatus()
  1769. if canDoSomething and isTrading then
  1770. canDoSomething = false
  1771. end
  1772. if not noTips and not canDoSomething then
  1773. ShowSystemTips(GET_STRING(90170001))
  1774. end
  1775. return canDoSomething
  1776. end
  1777. function GetGuildOfficialName(official)
  1778. local GuildProxy = global.Facade:retrieveProxy(global.ProxyTable.GuildProxy)
  1779. return GuildProxy:getGuildTitleByRank(official) or ""
  1780. end
  1781. local ListView = ccui.ListView
  1782. function ListView:paintItems()
  1783. local items = self:getItems()
  1784. local direction = self:getDirection()
  1785. local lowerBound = #items - 1
  1786. local upperBound = 0
  1787. if (direction ~= 1) then
  1788. lowerBound = self:getIndex(self:getRightmostItemInCurrentView())
  1789. upperBound = self:getIndex(self:getLeftmostItemInCurrentView())
  1790. end
  1791. if (direction ~= 2) then
  1792. lowerBound = math.min(self:getIndex(self:getTopmostItemInCurrentView()), lowerBound)
  1793. upperBound = math.max(self:getIndex(self:getBottommostItemInCurrentView()), upperBound)
  1794. end
  1795. for i, item in ipairs(items) do
  1796. item:setVisible(lowerBound <= (i-1) and (i-1) <= upperBound)
  1797. end
  1798. end
  1799. local ScrollView = ccui.ScrollView
  1800. function ScrollView:addMouseScrollPercent(callback)
  1801. self:setMouseEnabled(true)
  1802. self:setSwallowMouse(false)
  1803. self:addMouseEventListener(function(sender, eventType)
  1804. if eventType == 1 then
  1805. elseif eventType == 3 then
  1806. local speed = 30
  1807. local param = self:getMouseScrollPosition()
  1808. local scorllX = param.x
  1809. local scorllY = param.y
  1810. local contentSize = self:getContentSize()
  1811. local innerSize = self:getInnerContainerSize()
  1812. if innerSize.height > contentSize.height then
  1813. local innerPos = self:getInnerContainerPosition()
  1814. local vHeight = innerSize.height - contentSize.height
  1815. local dis = speed * scorllY
  1816. local percent = (vHeight + innerPos.y + dis) / vHeight * 100
  1817. percent = math.min(math.max(0, percent), 100)
  1818. self:scrollToPercentVertical(percent, 0.03, false)
  1819. if callback then
  1820. callback(percent)
  1821. end
  1822. end
  1823. end
  1824. end)
  1825. end
  1826. function CreateScrollLabel(txt, config)
  1827. local anchorPoint = {0, 0}
  1828. if config and config.anchorPoint then
  1829. anchorPoint = config.anchorPoint
  1830. end
  1831. local layoutName = ccui.Layout:create()
  1832. layoutName:setClippingEnabled(true)
  1833. layoutName:setLayoutComponentEnabled(true)
  1834. layoutName:setAnchorPoint(anchorPoint[1], anchorPoint[2])
  1835. local componentSize = {
  1836. width = 80,
  1837. height = 20
  1838. }
  1839. if config and config.visibleSize then
  1840. componentSize = {
  1841. width = config.visibleSize[1],
  1842. height = config.visibleSize[2]
  1843. }
  1844. end
  1845. local layout = ccui.LayoutComponent:bindLayoutComponent(layoutName)
  1846. layout:setSize(
  1847. {
  1848. width = componentSize.width,
  1849. height = componentSize.height
  1850. }
  1851. )
  1852. local string = txt or ""
  1853. local nameLabel = ccui.Text:create(txt, config and config.fontName or global.MMO.PATH_FONT2, config.fontSize or 18)
  1854. nameLabel:setAnchorPoint(anchorPoint[1], anchorPoint[2])
  1855. if config and config.labelColour then
  1856. nameLabel:setTextColor(config.labelColour)
  1857. end
  1858. if config and config.colorId then
  1859. nameLabel:setTextColor(GET_COLOR_BYID_C3B(config.colorId))
  1860. end
  1861. local maxSize = componentSize.width or 80
  1862. local function StartNameAction(cell)
  1863. local textWid = cell:getContentSize().width
  1864. if textWid > maxSize then
  1865. cell:runAction(
  1866. cc.RepeatForever:create(
  1867. cc.Sequence:create(cc.MoveBy:create(4, cc.p(-textWid, 0)), cc.MoveBy:create(0, cc.p(textWid, 0)))
  1868. )
  1869. )
  1870. end
  1871. end
  1872. StartNameAction(nameLabel)
  1873. nameLabel:setPosition(cc.p(componentSize.width*anchorPoint[1], componentSize.height*anchorPoint[2]))
  1874. layoutName:addChild(nameLabel)
  1875. return layoutName
  1876. end
  1877. -- 用于检测goodsitem 是否在listview 并且可视
  1878. function CheckNodeCanCallBack( node, mousePos, checkLevel )
  1879. local child = node
  1880. local times = 0
  1881. local checkEnable = true
  1882. local maxTimes = checkLevel or 6
  1883. local function GetParentAndCheck(childNode)
  1884. if times >= maxTimes then
  1885. checkEnable = true
  1886. return
  1887. end
  1888. if not tolua.isnull(childNode) then
  1889. local parent = childNode:getParent()
  1890. if not tolua.isnull(parent) then
  1891. if not parent:isVisible() then
  1892. checkEnable = false
  1893. return
  1894. end
  1895. if tolua.iskindof(parent,"ccui.ListView") or tolua.iskindof(parent,"ccui.ScrollView") then
  1896. local contentSize = parent:getContentSize()
  1897. local parentPos = parent:getWorldPosition()
  1898. local anchorPoint = parent:getAnchorPoint()
  1899. local width = contentSize.width
  1900. local height = contentSize.height
  1901. local minX = parentPos.x - width*anchorPoint.x
  1902. local maxX = parentPos.x + width*(1-anchorPoint.x)
  1903. local minY = parentPos.y - height*anchorPoint.y
  1904. local maxY = parentPos.y + height*(1-anchorPoint.y)
  1905. if mousePos.x < minX or maxX < mousePos.x or mousePos.y < minY or maxY < mousePos.y then
  1906. checkEnable = false
  1907. return
  1908. end
  1909. end
  1910. times = times + 1
  1911. GetParentAndCheck(parent)
  1912. end
  1913. end
  1914. end
  1915. GetParentAndCheck(child)
  1916. return checkEnable
  1917. end
  1918. function NumberToChinese(szNum)
  1919. ---阿拉伯数字转中文大写
  1920. local szChMoney = ""
  1921. local iLen = 0
  1922. local iNum = 0
  1923. local iAddZero = 0
  1924. local hzUnit = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千", "万", "十", "百", "千"}
  1925. local hzNum = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"}
  1926. if nil == tonumber(szNum) then
  1927. return tostring(szNum)
  1928. end
  1929. iLen = string.len(szNum)
  1930. if iLen > 10 or iLen == 0 or tonumber(szNum) < 0 then
  1931. return tostring(szNum)
  1932. end
  1933. for i = 1, iLen do
  1934. iNum = tonumber( string.sub(szNum, i, i) )
  1935. if iNum == 0 and i ~= iLen then
  1936. iAddZero = iAddZero + 1
  1937. else
  1938. if iAddZero > 0 then
  1939. szChMoney = szChMoney .. hzNum[1]
  1940. end
  1941. szChMoney = szChMoney .. hzNum[iNum + 1] --//转换为相应的数字
  1942. iAddZero = 0
  1943. end
  1944. if (iAddZero < 4) and (0 == (iLen - i) % 4 or 0 ~= tonumber(iNum)) then
  1945. szChMoney = szChMoney .. hzUnit[iLen - i + 1]
  1946. end
  1947. end
  1948. local function removeZero(num)
  1949. --去掉末尾多余的 零
  1950. num = tostring(num)
  1951. local szLen = string.len(num)
  1952. local zero_num = 0
  1953. for i = szLen, 1, -3 do
  1954. szNum = string.sub(num, i - 2, i)
  1955. if szNum == hzNum[1] then
  1956. zero_num = zero_num + 1
  1957. else
  1958. break
  1959. end
  1960. end
  1961. num = string.sub(num, 1, szLen - zero_num * 3)
  1962. szNum = string.sub(num, 1, 6)
  1963. --- 开头的 "一十" 转成 "十" , 贴近人的读法
  1964. if szNum == hzNum[2] .. hzUnit[2] then
  1965. num = string.sub(num, 4, string.len(num))
  1966. end
  1967. return num
  1968. end
  1969. return removeZero(szChMoney)
  1970. end
  1971. function UseItemByIndex(Index)
  1972. local BagProxy = global.Facade:retrieveProxy(global.ProxyTable.Bag)
  1973. local QuickUseProxy = global.Facade:retrieveProxy(global.ProxyTable.QuickUseProxy)
  1974. local item = nil
  1975. local items = QuickUseProxy:GetQucikUseDataByIndex(Index)
  1976. if items and next(items) then
  1977. item = items[1]
  1978. end
  1979. if not item then
  1980. local items = BagProxy:GetItemDataByItemIndex(Index)
  1981. if items and next(items) then
  1982. item = items[1]
  1983. end
  1984. end
  1985. if item then
  1986. local ItemUseProxy = global.Facade:retrieveProxy(global.ProxyTable.ItemUseProxy)
  1987. ItemUseProxy:UseItem(item)
  1988. return true
  1989. end
  1990. return false
  1991. end
  1992. function StoreBuyTipsOpen(storeIndex, limitStr)
  1993. if not storeIndex then
  1994. return
  1995. end
  1996. local PageStoreProxy = global.Facade:retrieveProxy(global.ProxyTable.PageStoreProxy)
  1997. local storeData = PageStoreProxy:GetItemDataByStoreIndex(storeIndex)
  1998. if not storeData or next(storeData) == nil then
  1999. return
  2000. end
  2001. local canBy = PageStoreProxy:CheckStoreLimitStatus(storeIndex)
  2002. if not canBy then
  2003. if limitStr and string.len(limitStr) > 0 then
  2004. ShowSystemTips(limitStr)
  2005. end
  2006. return
  2007. end
  2008. local buyData = {
  2009. data = storeData,
  2010. }
  2011. global.Facade:sendNotification(global.NoticeTable.Layer_StoreBuy_Open, buyData)
  2012. end
  2013. function PlayEffectOnScreen(data)
  2014. local effectId = data.effectId
  2015. local x = data.x
  2016. local y = data.y
  2017. local playSpeed = data.speed
  2018. local playTimes = data.times
  2019. local playMode = data.mode --2行会 3地图 4组队
  2020. local isLoop = false
  2021. if playTimes == 0 then
  2022. isLoop = true
  2023. end
  2024. -- 播放特效
  2025. local sfxAnim = global.FrameAnimManager:CreateSFXAnim(effectId)
  2026. sfxAnim:setPosition( x, y)
  2027. sfxAnim:Play(0, 0, true, playSpeed)
  2028. local count = 0
  2029. local function removeEvent()
  2030. count = count + 1
  2031. if playTimes == count then
  2032. sfxAnim:removeFromParent()
  2033. end
  2034. end
  2035. sfxAnim:SetAnimEventCallback( removeEvent )
  2036. if data.id then
  2037. sfxAnim:setName(tostring(data.id))
  2038. end
  2039. local mediator = global.Facade:retrieveMediator("NoticeMediator")
  2040. dump(data)
  2041. if mediator._layer and mediator._layer._root:getChildByName(tostring(data.id)) then
  2042. global.Facade:sendNotification(global.NoticeTable.Layer_Notice_RemoveChild, tostring(data.id))
  2043. end
  2044. if tonumber(playMode) > 1 and tonumber(playMode) < 5 then
  2045. table.insert(mediator._typeEffects[playMode - 1], tostring(data.id))
  2046. dump(mediator._typeEffects[playMode - 1])
  2047. end
  2048. global.Facade:sendNotification(global.NoticeTable.Layer_Notice_AddChild, {child = sfxAnim})
  2049. end
  2050. function LoByte( value )
  2051. local high_value = math.floor(value/256)
  2052. high_value = high_value*256
  2053. local low_value = value - high_value
  2054. return low_value
  2055. end
  2056. function HiByte( value )
  2057. local high_value = math.floor(value/256)
  2058. return high_value
  2059. end
  2060. function AdjustAb(abil, val)
  2061. local lo = LoByte(abil)
  2062. local hi = HiByte(abil)
  2063. local lov = 0
  2064. local hiv = 0
  2065. for i=1, val do
  2066. if (lo+1 < hi) then
  2067. lo = lo + 1
  2068. if lo > 255 then
  2069. lo = 0
  2070. end
  2071. lov = lov +1
  2072. else
  2073. hi = hi + 1
  2074. if hi > 255 then
  2075. hi = 0
  2076. end
  2077. hiv = hiv + 1
  2078. end
  2079. end
  2080. return lov, hiv
  2081. end
  2082. function SHOW_SUI_DESCTIP(widget, str, width, offset, anchorPoint)
  2083. local btnAnchor = widget:getAnchorPoint()
  2084. local contentSize = widget:getContentSize()
  2085. local worldPos = widget:getWorldPosition()
  2086. --anchorPoint此时为SUI组件设置锚点
  2087. local fixWorldPos = cc.pAdd(worldPos, cc.p((anchorPoint.x-btnAnchor.x)*contentSize.width, (anchorPoint.y-btnAnchor.y)*contentSize.height))
  2088. offset = offset or {x=0, y=0}
  2089. width = width or 1136
  2090. local tempWorldPos = cc.pAdd(fixWorldPos, offset)
  2091. anchorPoint = cc.p(0.5,0.5)
  2092. global.Facade:sendNotification(global.NoticeTable.Layer_Common_Desc_Open, {str = str, worldPos = tempWorldPos, width = width, anchorPoint = anchorPoint, isSUI = true})
  2093. end
  2094. function SHOW_DESCTIP( str, width, worldPos, anchorPoint, swallowType)
  2095. worldPos = worldPos or cc.p(0, 0)
  2096. width = width or 1136
  2097. global.Facade:sendNotification(global.NoticeTable.Layer_Common_Desc_Open, {str = str, worldPos = worldPos, width = width, anchorPoint = anchorPoint, swallowType = swallowType})
  2098. end
  2099. --飞向人物
  2100. function ShowFakeDropItemsJustFly(targetID, items)
  2101. if global.L_GameEnvManager:GetEnvDataByKey("isAliCloudPhone") then
  2102. return
  2103. end
  2104. local ServerTimeProxy = global.Facade:retrieveProxy( global.ProxyTable.ServerTimeProxy )
  2105. local ItemConfigProxy = global.Facade:retrieveProxy(global.ProxyTable.ItemConfigProxy)
  2106. local inputProxy = global.Facade:retrieveProxy(global.ProxyTable.PlayerInputProxy)
  2107. local sceneRoot = global.sceneGraphCtl:GetSceneNode( global.MMO.NODE_ACTOR_SPRITE )
  2108. local target = global.actorManager:GetActor(targetID)
  2109. if not target then
  2110. return nil
  2111. end
  2112. local DROPITEM_RES_PATH = "res/item"
  2113. local DROPITEM_GROUND_RES_PATH = "res/item_ground"
  2114. local PUBLIC_UNDEFINE = "un_define.pvr.ccz"
  2115. local function createDropItem(index, item)
  2116. local itemIndex = item.id or 1
  2117. local itemData = ItemConfigProxy:GetItemDataByIndex(itemIndex)
  2118. local itemName = ItemConfigProxy:GetItemNameByIndex(itemIndex)
  2119. if not itemData then
  2120. return nil
  2121. end
  2122. -- 资源路径
  2123. local itemLooks = itemData.Looks or 1
  2124. local groundFile = global.dropItemController:GetItemGroundFile(itemLooks)
  2125. local dropItemTexc = global.CustomCache:GetImage(groundFile)
  2126. local itemScale = SL:GetMetaValue("GAME_DATA","itemGroundSacle") or (global.isWinPlayMode and 0.5 or 0.8)
  2127. if not dropItemTexc then
  2128. groundFile = string.format("%s/%s",DROPITEM_RES_PATH,PUBLIC_UNDEFINE)
  2129. dropItemTexc = global.CustomCache:GetImage(groundFile)
  2130. print( "Failed to load drop item avatar:"..fileName.."\n" )
  2131. end
  2132. local dropItemSprite = cc.Sprite:createWithTexture( dropItemTexc )
  2133. dropItemSprite:setScale(itemScale)
  2134. dropItemSprite.GetBoundingBox = dropItemSprite.getBoundingBox
  2135. --------------
  2136. -- 计算初始坐标和目标坐标
  2137. local originPos = global.sceneManager:MapPos2WorldPos(item.mapX, item.mapY, true)
  2138. -- 创建道具图标
  2139. local imageItem = dropItemSprite--ccui.ImageView:create()
  2140. sceneRoot:addChild(dropItemSprite)
  2141. imageItem:setPosition(originPos)
  2142. imageItem:setTag(index)
  2143. imageItem:setVisible(false)
  2144. ------------
  2145. local function moveToTarget()
  2146. local speed = 400
  2147. local interval = 1/60
  2148. local function callback()
  2149. local target = global.actorManager:GetActor(targetID)
  2150. if not target then
  2151. global.CustomCache:RmImage(imageItem)
  2152. return nil
  2153. end
  2154. local targetPos = target:getPosition()
  2155. local curItemPos = cc.p(imageItem:getPosition())
  2156. local distance = speed * interval
  2157. local destSub = cc.pSub(targetPos, curItemPos)
  2158. local flyDir = cc.pNormalize(destSub)
  2159. local displ = cc.pMul(flyDir, distance)
  2160. local posNew = cc.pAdd(curItemPos, displ)
  2161. imageItem:setPosition(posNew)
  2162. local destSub = cc.pSub(targetPos, curItemPos)
  2163. local destDist = cc.pGetLength(destSub)
  2164. if destDist <= distance*3 then
  2165. global.CustomCache:RmImage(imageItem)
  2166. end
  2167. end
  2168. schedule(imageItem, callback, interval)
  2169. performWithDelay(imageItem, function()
  2170. global.CustomCache:RmImage(imageItem)
  2171. end, 1)
  2172. end
  2173. imageItem:runAction(cc.Sequence:create(
  2174. cc.Show:create(),
  2175. cc.CallFunc:create(moveToTarget)
  2176. ))
  2177. end
  2178. --
  2179. for index, item in ipairs(items) do
  2180. createDropItem(index, item)
  2181. end
  2182. end
  2183. --飘经验特效
  2184. function EXPFly(actorID,effectID)
  2185. if global.L_GameEnvManager:GetEnvDataByKey("isAliCloudPhone") then
  2186. return
  2187. end
  2188. local actor = global.actorManager:GetActor(actorID)
  2189. if not actor then
  2190. return nil
  2191. end
  2192. local MainPropertyMediator = global.Facade:retrieveMediator("MainPropertyMediator")
  2193. if not MainPropertyMediator or not MainPropertyMediator._layer or not MainPropertyMediator._layer._quickUI or not MainPropertyMediator._layer._quickUI.LoadingBar_exp then
  2194. return
  2195. end
  2196. local widget = MainPropertyMediator._layer._quickUI.LoadingBar_exp
  2197. local X = actor:GetMapX()
  2198. local Y = actor:GetMapY()
  2199. -- 计算初始坐标和目标坐标
  2200. local originPos = global.sceneManager:MapPos2WorldPos(X, Y)
  2201. local sceneRoot = global.sceneGraphCtl:GetSceneNode( global.MMO.NODE_UI_NORMAL )
  2202. local sfxRoot = global.sceneGraphCtl:GetSceneNode(global.MMO.NODE_ACTOR_SFX_FRONT)
  2203. if effectID == 0 then
  2204. effectID= 5057
  2205. end
  2206. local anim = global.CustomCache:GetSFXAnim( effectID )
  2207. if not anim then
  2208. return nil
  2209. end
  2210. local Percentage = widget:getPercent()
  2211. local targetPos = widget:convertToWorldSpace(cc.p(0,0))
  2212. local box = widget:getBoundingBox()
  2213. targetPos.y = 0.5*box.height+targetPos.y
  2214. targetPos.x = targetPos.x + Percentage/100*box.width
  2215. sfxRoot:addChild(anim)
  2216. anim:setLocalZOrder(effectID)
  2217. anim:Play( 0, 0, true)
  2218. anim:setPosition(originPos)
  2219. anim:setVisible(true)
  2220. anim:SetAnimEventCallback(function()
  2221. global.CustomCache:RmSFXAnim(anim)
  2222. local worldpos = World2Screen(originPos)
  2223. local count = math.random(3,5)
  2224. for i = 1,count do
  2225. local lz = global.CustomCache:GetImage(string.format("%slizi.png",global.MMO.PATH_RES_PUBLIC))
  2226. local newWorldPos = cc.p(worldpos.x + math.random(-50,50),worldpos.y + math.random(-50,50)+180)
  2227. lz:setPosition(newWorldPos)
  2228. sceneRoot:addChild(lz)
  2229. lz:runAction(cc.Sequence:create(
  2230. cc.MoveTo:create(1, targetPos),
  2231. cc.CallFunc:create(function(sender)
  2232. global.CustomCache:RmImage(lz)
  2233. if i == count then
  2234. local anim2 = global.CustomCache:GetSFXAnim( 5058 )
  2235. if not anim2 then
  2236. return
  2237. end
  2238. sceneRoot:addChild(anim2)
  2239. anim2:setPosition(targetPos)
  2240. anim2:Play( 0, 0, false)
  2241. anim2:SetAnimEventCallback(function()
  2242. global.CustomCache:RmSFXAnim(anim2)
  2243. end)
  2244. end
  2245. end )
  2246. ))
  2247. end
  2248. end)
  2249. end
  2250. --飞向指定按钮
  2251. function ShowFakeDropItemsJustFly2(targetPos,items)
  2252. if global.L_GameEnvManager:GetEnvDataByKey("isAliCloudPhone") then
  2253. return
  2254. end
  2255. local sceneRoot = global.sceneGraphCtl:GetSceneNode( global.MMO.NODE_UI_NORMAL )
  2256. local ItemConfigProxy = global.Facade:retrieveProxy(global.ProxyTable.ItemConfigProxy)
  2257. local DROPITEM_RES_PATH = "res/item"
  2258. local DROPITEM_GROUND_RES_PATH = "res/item_ground"
  2259. local PUBLIC_UNDEFINE = "un_define.pvr.ccz"
  2260. local function createDropItem(index, item)
  2261. local itemIndex = item.id or 1
  2262. if not tonumber(itemIndex) or tonumber(itemIndex) < 100 then
  2263. return nil
  2264. end
  2265. local itemData = ItemConfigProxy:GetItemDataByIndex(itemIndex)
  2266. local itemName = ItemConfigProxy:GetItemNameByIndex(itemIndex)
  2267. if not itemData or not next(itemData) then
  2268. return nil
  2269. end
  2270. -- 资源路径
  2271. local itemLooks = itemData.Looks or 1
  2272. local groundFile = global.dropItemController:GetItemGroundFile(itemLooks)
  2273. local dropItemTexc = global.CustomCache:GetImage(groundFile)
  2274. local itemScale = SL:GetMetaValue("GAME_DATA","itemGroundSacle") or (global.isWinPlayMode and 0.5 or 0.8)
  2275. if not dropItemTexc then
  2276. groundFile = string.format("%s/%s",DROPITEM_RES_PATH,PUBLIC_UNDEFINE)
  2277. dropItemTexc = global.CustomCache:GetImage(groundFile)
  2278. print( "Failed to load drop item avatar:"..fileName.."\n" )
  2279. end
  2280. local dropItemSprite = dropItemTexc
  2281. dropItemSprite:setScale(itemScale)
  2282. --------------
  2283. -- 计算初始坐标和目标坐标
  2284. local originPos = global.sceneManager:MapPos2WorldPos(item.mapX, item.mapY, true)
  2285. local worldpos = World2Screen(originPos)
  2286. -- 创建道具图标
  2287. local imageItem = dropItemSprite
  2288. sceneRoot:addChild(imageItem)
  2289. imageItem:setPosition(worldpos)
  2290. imageItem:setTag(index)
  2291. imageItem:setVisible(false)
  2292. ------------
  2293. local function moveToTarget()
  2294. local speed = 600
  2295. local interval = 1/60
  2296. local function callback()
  2297. local curItemPos = cc.p(imageItem:getPosition())
  2298. local distance = speed * interval
  2299. local destSub = cc.pSub(targetPos, curItemPos)
  2300. local flyDir = cc.pNormalize(destSub)
  2301. local displ = cc.pMul(flyDir, distance)
  2302. local posNew = cc.pAdd(curItemPos, displ)
  2303. imageItem:setPosition(posNew)
  2304. local destDist = cc.pGetLength(destSub)
  2305. if destDist <= 3*distance then
  2306. global.CustomCache:RmImage(imageItem)
  2307. SLBridge:onLUAEvent(LUA_EVENT_FLYIN_BTN_ITEM_COMPLETE, {itemIndex = itemIndex})
  2308. end
  2309. end
  2310. schedule(imageItem, callback, interval)
  2311. end
  2312. imageItem:runAction(cc.Sequence:create(cc.Show:create(), cc.CallFunc:create(moveToTarget)))
  2313. end
  2314. local scheduleNode = sceneRoot:getChildByName("SCHEDULE_NODE")
  2315. if scheduleNode then
  2316. scheduleNode:removeFromParent()
  2317. scheduleNode = nil
  2318. end
  2319. scheduleNode = cc.Node:create()
  2320. scheduleNode:setName("SCHEDULE_NODE")
  2321. sceneRoot:addChild(scheduleNode)
  2322. local starIndex = 0
  2323. local maxCount = #items
  2324. -- 间隔加载
  2325. local function scheduleCreate(callfunc,delayTime)
  2326. local oneTimeCount = 15
  2327. starIndex = starIndex + 1
  2328. if not callfunc or starIndex > maxCount then
  2329. local scheduleNode = sceneRoot:getChildByName("SCHEDULE_NODE")
  2330. if scheduleNode then
  2331. scheduleNode:removeFromParent()
  2332. scheduleNode = nil
  2333. end
  2334. return
  2335. end
  2336. local endIndex = math.min(starIndex+oneTimeCount-1,maxCount)
  2337. performWithDelay(scheduleNode,function()
  2338. for i = starIndex, endIndex, 1 do
  2339. local item = items[i]
  2340. if item then
  2341. callfunc(i, item)
  2342. end
  2343. end
  2344. starIndex = endIndex
  2345. scheduleCreate(callfunc)
  2346. end,delayTime or 0.5)
  2347. end
  2348. scheduleCreate(createDropItem,0)
  2349. end
  2350. --[[
  2351. 解析奖励展示 也会把里面的box解析出来
  2352. 参数: str="id#count&id#count", sp="&" parseBox = 是否解析box 默认解析
  2353. ]]
  2354. function ParseRewards(str, sp, parseBox)
  2355. str = str or ""
  2356. sp = sp or "&"
  2357. local rewards = {}
  2358. local sliceStr = string.split(str, sp)
  2359. for i=1, #sliceStr do
  2360. local sliceStr2 = string.split(sliceStr[i], "#")
  2361. local id = tonumber(sliceStr2[1])
  2362. if id then
  2363. local count = tonumber(sliceStr2[2]) or 1
  2364. table.insert(rewards, {id=id, count=count})
  2365. end
  2366. end
  2367. return rewards
  2368. end
  2369. function JudgeIsRefreshTargetHP(data)
  2370. local proxyPlayerInput = global.Facade:retrieveProxy( global.ProxyTable.PlayerInputProxy )
  2371. local targetID = proxyPlayerInput:GetTargetID()
  2372. if targetID and targetID == data.actorID then
  2373. ssr.ssrBridge:OnRefreshTargetHP(data.actorID, data.HP, data.maxHP)
  2374. end
  2375. end
  2376. function randDataID( role_id )
  2377. -- body
  2378. local data_id = role_id
  2379. local function getRandomStr(n)
  2380. local s = ""
  2381. for i = 1, n do
  2382. local type = math.random(1,3)
  2383. if type == 1 then
  2384. s = s .. math.random(0, 9)
  2385. elseif type == 2 then
  2386. s = s .. string.char(math.random(0, 25) + 65)
  2387. elseif type == 3 then
  2388. s = s .. string.char(math.random(0, 25) + 97)
  2389. end
  2390. end
  2391. return s
  2392. end
  2393. data_id = data_id.."-"..getRandomStr(16)
  2394. return data_id
  2395. end
  2396. function CheckPasswordIsSimple(password, account)
  2397. if password and string.len( password ) < 6 then
  2398. return true
  2399. end
  2400. if account == password then
  2401. return true
  2402. end
  2403. if not string.match( password, "[^%d]" ) then
  2404. return true
  2405. end
  2406. if not string.match( password, "[^%a]") then
  2407. return true
  2408. end
  2409. return false
  2410. end
  2411. function ResetBagPos(isHero)
  2412. local BagProxy = isHero and global.Facade:retrieveProxy(global.ProxyTable.HeroBagProxy) or global.Facade:retrieveProxy(global.ProxyTable.Bag)
  2413. if not isHero then
  2414. local QuickUseProxy = global.Facade:retrieveProxy( global.ProxyTable.QuickUseProxy )
  2415. local bagData = BagProxy:GetBagData()
  2416. for k, v in pairs(bagData) do
  2417. if v.StdMode == 2 then
  2418. local isCanAddToQuick = QuickUseProxy:CheckItemCanAddToQuickUse(v)
  2419. local quickUsePos = QuickUseProxy:CheckQuickUseHasEmpty()
  2420. if isCanAddToQuick and quickUsePos then --快捷栏道具
  2421. QuickUseProxy:AutoAddBagItemToQuick(v, quickUsePos)
  2422. end
  2423. end
  2424. end
  2425. end
  2426. local newData = BagProxy:GetBagData()
  2427. BagProxy:CleanBagPosData()
  2428. BagProxy:AmendHistoryPos(newData, true)
  2429. if isHero then
  2430. global.Facade:sendNotification(global.NoticeTable.HeroBag_Pos_Reset)
  2431. SLBridge:onLUAEvent(LUA_EVENT_REF_HERO_ITEM_LIST)
  2432. else
  2433. global.Facade:sendNotification(global.NoticeTable.Bag_Pos_Reset)
  2434. SLBridge:onLUAEvent(LUA_EVENT_REF_ITEM_LIST)
  2435. end
  2436. end
  2437. -- 添加全局回调事件
  2438. function AddGlobalScheduleFunc(funcMethodName, callback, interval)
  2439. RmoveGlobalScheduleFunc(funcMethodName)
  2440. interval = interval or 1
  2441. globalSchedule[funcMethodName] = {
  2442. sFunc =callback
  2443. }
  2444. globalSchedule[funcMethodName].scheuleId = Schedule( function()
  2445. if globalSchedule[funcMethodName].sFunc then
  2446. globalSchedule[funcMethodName]:sFunc()
  2447. end
  2448. end, interval)
  2449. if callback then
  2450. callback()
  2451. end
  2452. end
  2453. -- 移除单个全局事件( funcMethodName: 函数名 没参数就删除所有的)
  2454. function RmoveGlobalScheduleFunc(funcMethodName)
  2455. if funcMethodName then
  2456. if globalSchedule[funcMethodName] then
  2457. local scheuleId = globalSchedule[funcMethodName].scheuleId
  2458. UnSchedule(scheuleId)
  2459. globalSchedule[funcMethodName] = nil
  2460. end
  2461. return
  2462. end
  2463. globalSchedule = globalSchedule or {}
  2464. for k,v in pairs(globalSchedule) do
  2465. local scheuleId = v.scheuleId
  2466. UnSchedule(scheuleId)
  2467. end
  2468. globalSchedule = {}
  2469. end
  2470. function CheckEquipPowerThanSelf(itemInfo, from)
  2471. return GUIFunction:CompareEquipOnBody(itemInfo, from)
  2472. end
  2473. -- uf8字符串截取 str: 字符串 subStar: 截取开始 subEnd: 截取结束
  2474. function stringUTF8Sub( str,subStar,subEnd )
  2475. if not str or str == "" then
  2476. return ""
  2477. end
  2478. local charsize = function(ch)
  2479. if not ch then
  2480. return 0
  2481. elseif ch >= 252 then
  2482. return 6
  2483. elseif ch >= 248 and ch < 252 then
  2484. return 5
  2485. elseif ch >= 240 and ch < 248 then
  2486. return 4
  2487. elseif ch >= 224 and ch < 240 then
  2488. return 3
  2489. elseif ch >= 192 and ch < 224 then
  2490. return 2
  2491. elseif ch < 192 then
  2492. return 1
  2493. end
  2494. end
  2495. subStar = subStar or 1
  2496. subEnd = subEnd or string.utf8len(str)
  2497. local subLen = subEnd-subStar+1
  2498. local byteStar,byteEnd,tempLen = 0,1,0
  2499. while subStar <= subEnd and subLen > 0 do
  2500. local char = string.byte(str, byteEnd)
  2501. byteEnd = byteEnd + charsize(char)
  2502. tempLen = tempLen + 1
  2503. if tempLen > subStar then
  2504. subLen = subLen - 1
  2505. elseif tempLen == subStar then
  2506. byteStar = byteEnd - charsize(char)
  2507. subLen = subLen - 1
  2508. end
  2509. end
  2510. return string.sub(str, byteStar, byteEnd-1)
  2511. end
  2512. function CheckInputOnlyChinese( str )
  2513. local charsize = function(ch)
  2514. if not ch then
  2515. return 0
  2516. elseif ch >= 252 then
  2517. return 6
  2518. elseif ch >= 248 and ch < 252 then
  2519. return 5
  2520. elseif ch >= 240 and ch < 248 then
  2521. return 4
  2522. elseif ch >= 224 and ch < 240 then
  2523. return 3
  2524. elseif ch >= 192 and ch < 224 then
  2525. return 2
  2526. elseif ch < 192 then
  2527. return 1
  2528. end
  2529. end
  2530. -- Unicode 4E00 - 9FA5
  2531. local function checkChinese(ch, k)
  2532. if k == 1 and ch >= 228 and ch <= 233 then
  2533. return true
  2534. end
  2535. if k and ( k == 2 or k == 3 ) then
  2536. if ch >= 128 and ch <= 191 then
  2537. return true
  2538. end
  2539. end
  2540. return false
  2541. end
  2542. local inputStr = ""
  2543. local currentIndex = 1
  2544. while currentIndex <= #str do
  2545. local char = string.byte(str, currentIndex)
  2546. if charsize(char) == 3 then
  2547. local index = currentIndex
  2548. local isCh = true
  2549. for i = 1, 3 do
  2550. isCh = isCh and checkChinese(string.byte(str, index + i - 1), i)
  2551. end
  2552. if isCh then
  2553. inputStr = inputStr .. string.sub(str, index, index + 3-1)
  2554. end
  2555. end
  2556. currentIndex = currentIndex + charsize(char)
  2557. end
  2558. return inputStr
  2559. end
  2560. -- 获取字符串的byte长度
  2561. function GetUTF8ByteLen( str )
  2562. local function chsize(char)
  2563. if not char then
  2564. print("not char")
  2565. return 0
  2566. elseif char > 240 then
  2567. return 4
  2568. elseif char > 225 then
  2569. return 3
  2570. elseif char > 192 then
  2571. return 2
  2572. else
  2573. return 1
  2574. end
  2575. end
  2576. local len = 0
  2577. local chineseLen = 0
  2578. local currentIndex = 1
  2579. while currentIndex <= #str do
  2580. local char = string.byte(str, currentIndex)
  2581. local charS = chsize(char)
  2582. currentIndex = currentIndex + charS
  2583. len = len + charS
  2584. if charS >= 3 then
  2585. chineseLen = chineseLen + 1
  2586. end
  2587. end
  2588. return len,chineseLen
  2589. end
  2590. function CheckItemCountEnoughEX(data, speicalYuanBao)
  2591. if speicalYuanBao == nil then
  2592. data.speicalYuanBao = true
  2593. else
  2594. data.speicalYuanBao = speicalYuanBao
  2595. end
  2596. local PayProxy = global.Facade:retrieveProxy(global.ProxyTable.PayProxy)
  2597. local result = PayProxy:CheckItemCountEX(data)
  2598. return result
  2599. end
  2600. --------------------------------------------
  2601. --%S -> %s %D -> %d %x ->%%x %%x ->%%x
  2602. -- %s %d %%D %xxx %s %xx %m % ->%s %d %%d %%xxx %s %%xx %%m %%
  2603. function Msg_formatPercent(str)
  2604. if not str then
  2605. return ""
  2606. end
  2607. str = string.gsub(str,"%%S","%%s")
  2608. str = string.gsub(str,"%%D","%%d")
  2609. str = string.gsub(str,"([^%%])(%%[^sSdD%%])","%1%%%2")
  2610. str = string.gsub(str,"%%$","%%%%")
  2611. str = string.gsub(str,"^%%([^sSdD%%])","%%%%%1")--开头是%x的
  2612. return str
  2613. end
  2614. --------------------------------------------
  2615. local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -- You will need this for encoding/decoding
  2616. -- encoding
  2617. function base64enc(data)
  2618. return ((data:gsub('.', function(x)
  2619. local r,b='',x:byte()
  2620. for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
  2621. return r;
  2622. end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
  2623. if (#x < 6) then return '' end
  2624. local c=0
  2625. for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
  2626. return b:sub(c+1,c+1)
  2627. end)..({ '', '==', '=' })[#data%3+1])
  2628. end
  2629. -- decoding
  2630. function base64dec(data)
  2631. data = string.gsub(data, '[^'..b..'=]', '')
  2632. return (data:gsub('.', function(x)
  2633. if (x == '=') then return '' end
  2634. local r,f='',(b:find(x)-1)
  2635. for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
  2636. return r;
  2637. end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
  2638. if (#x ~= 8) then return '' end
  2639. local c=0
  2640. for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end
  2641. return string.char(c)
  2642. end))
  2643. end
  2644. function setCusTomCursor(CursorType)
  2645. if CursorType ~= global.CurrentCurSorType then
  2646. local path = ""
  2647. if CursorType == global.MMO.CURSOR_TYPE_NORMAL then
  2648. path = global.MMO.PATH_RES_PUBLIC.."CustomCursor1.png"
  2649. elseif CursorType == global.MMO.CURSOR_TYPE_PK then
  2650. path = global.MMO.PATH_RES_PUBLIC.."CustomCursor2.png"
  2651. elseif CursorType == global.MMO.CURSOR_TYPE_NPC then
  2652. path = global.MMO.PATH_RES_PUBLIC.."CustomCursor3.png"
  2653. end
  2654. if setCustomCursor and cc.FileUtils:getInstance():isFileExist(path) then
  2655. setCustomCursor(path)
  2656. end
  2657. global.CurrentCurSorType = CursorType
  2658. end
  2659. end
  2660. --刷新坐标变整数
  2661. function refPositionByParent(layer)
  2662. if global.isWinPlayMode then
  2663. local visitChildren
  2664. local refPos = function(v)
  2665. if not v.CheckAndLoadRes then
  2666. local worldpos = v:convertToWorldSpace(cc.p(0,0))
  2667. local newpos = cc.p(math.floor(worldpos.x), math.floor(worldpos.y))
  2668. local pos = cc.p(v:getPosition())
  2669. v:setPosition(cc.pAdd(pos, cc.pSub(newpos, worldpos)))
  2670. local needRefChild = true
  2671. if (v.InitWidgetConfig and tolua.type(v) == "ccui.Widget") or (v._unRefPos and tolua.type(v) == "ccui.ListView") then
  2672. needRefChild = false
  2673. end
  2674. -- UIModel
  2675. if needRefChild and v:getName() == "baseNode" then
  2676. needRefChild = false
  2677. end
  2678. if needRefChild then
  2679. if #v:getChildren() > 0 then
  2680. visitChildren(v)
  2681. end
  2682. end
  2683. end
  2684. end
  2685. visitChildren = function (parent)
  2686. for i,v in pairs(parent:getChildren()) do
  2687. refPos(v)
  2688. end
  2689. end
  2690. refPos(layer)
  2691. end
  2692. end
  2693. -- 禁止聊天
  2694. function IsForbidSay(autoTaost)
  2695. local envProxy = global.Facade:retrieveProxy( global.ProxyTable.GameEnvironment )
  2696. local LoginProxy = global.Facade:retrieveProxy(global.ProxyTable.Login)
  2697. local forbidChat = tonumber(envProxy:GetCustomDataByKey("forbidSay")) == 1 or LoginProxy:IsForbidChat() == true
  2698. if forbidChat and autoTaost then
  2699. ShowSystemTips(GET_STRING(30103600))
  2700. end
  2701. return forbidChat
  2702. end
  2703. -- 禁止取名
  2704. function IsForbidName(autoTaost)
  2705. local envProxy = global.Facade:retrieveProxy( global.ProxyTable.GameEnvironment )
  2706. local LoginProxy = global.Facade:retrieveProxy( global.ProxyTable.Login )
  2707. local forbidName = tonumber(envProxy:GetCustomDataByKey("forbidName")) == 1 or LoginProxy:IsForbidName()
  2708. if forbidName and autoTaost then
  2709. ShowSystemTips(GET_STRING(30103600))
  2710. end
  2711. return forbidName
  2712. end
  2713. function fixMinusNumber(value)
  2714. if value < 0 then
  2715. return value + 4294967295 + 1
  2716. end
  2717. return value
  2718. end
  2719. function fixNetMsgHeader(header)
  2720. if header.recog < 0 then
  2721. header.recog = header.recog + 4294967295 + 1
  2722. end
  2723. if header.param1 < 0 then
  2724. header.param1 = header.param1 + 4294967295 + 1
  2725. end
  2726. if header.param2 < 0 then
  2727. header.param2 = header.param2 + 4294967295 + 1
  2728. end
  2729. if header.param3 < 0 then
  2730. header.param3 = header.param3 + 4294967295 + 1
  2731. end
  2732. end
  2733. function IsForbidOpenBagOrEquip()
  2734. local NPCLayerMediator = global.Facade:retrieveMediator("NPCLayerMediator")
  2735. if NPCLayerMediator and NPCLayerMediator._layer and NPCLayerMediator._forbidBagEquip then
  2736. return true
  2737. end
  2738. return false
  2739. end
  2740. function CheckLayerOutScreen(tag)
  2741. local LayerFacadeMediator = global.Facade:retrieveMediator("LayerFacadeMediator")
  2742. if tag and tag == "BAG" then
  2743. local mediator = global.Facade:retrieveMediator("BagLayerMediator")
  2744. if not mediator then
  2745. mediator = global.Facade:retrieveMediator("MergeBagLayerMediator")
  2746. end
  2747. return LayerFacadeMediator:checkOutScreen(mediator)
  2748. end
  2749. return false
  2750. end
  2751. function IterAllChild(root, widget)
  2752. for k,v in pairs(widget:getChildren()) do
  2753. local name = v:getName()
  2754. root[name] = v
  2755. IterAllChild(root, v)
  2756. end
  2757. end
  2758. function FixPath(path)
  2759. if path and string.len(path) > 0 then
  2760. return sgsub(sgsub(sgsub(sgsub(string.trim(path), [[\\]], "/"), [[\]], "/"), "dev/", ""), "^/", "")
  2761. else
  2762. return path
  2763. end
  2764. end
  2765. -- 检测节点是否在容器内
  2766. function CheckNodeInInside(node, list)
  2767. local visiblesize = list:getContentSize()
  2768. local worSpacePos = list:getWorldPosition()
  2769. local anchorPoint = list:getAnchorPoint()
  2770. local lowPos = worSpacePos.y - visiblesize.height * anchorPoint.y
  2771. local uprPos = lowPos + visiblesize.height
  2772. local worldPos = node:getWorldPosition()
  2773. if worldPos.y > lowPos and worldPos.y < uprPos then
  2774. return true
  2775. end
  2776. return false
  2777. end
  2778. function stringToUTF8String(convertStr)
  2779. if type(convertStr) ~= "string" then
  2780. return convertStr
  2781. end
  2782. local utf8Str = ""
  2783. local i = 1
  2784. local numericCodes = string.byte(convertStr, i)
  2785. --
  2786. while numericCodes ~= nil do
  2787. local part1 = 0
  2788. local part2 = 0
  2789. if numericCodes >= 0x00 and numericCodes <= 0x7f then
  2790. part1 = numericCodes
  2791. part2 = 0
  2792. elseif numericCodes >= 0xc0 and numericCodes <= 0xdf then
  2793. local temp1 = 0
  2794. local temp2 = 0
  2795. temp1 = math.fmod(numericCodes, 0x20)
  2796. i = i + 1
  2797. numericCodes = string.byte(convertStr, i)
  2798. temp2 = math.fmod(numericCodes, 0x40)
  2799. part1 = temp2 + 64 * math.fmod(temp1, 0x04)
  2800. part2 = math.floor(temp1 / 4)
  2801. elseif numericCodes >= 0xe0 and numericCodes <= 0xf7 then
  2802. local temp1 = 0
  2803. local temp2 = 0
  2804. local temp3 = 0
  2805. temp1 = math.fmod(numericCodes, 0x10)
  2806. i = i + 1
  2807. numericCodes = string.byte(convertStr, i)
  2808. temp2 = math.fmod(numericCodes, 0x40)
  2809. i = i + 1
  2810. numericCodes = string.byte(convertStr, i)
  2811. temp3 = math.fmod(numericCodes, 0x40)
  2812. part1 = math.fmod(temp2, 0x04) * 64 + temp3
  2813. part2 = temp1 * 16 + math.floor(temp2 / 4)
  2814. else
  2815. part1 = 0x20
  2816. part2 = 0x00
  2817. end
  2818. utf8Str = utf8Str .. string.format("0x%02x%02x", part2, part1)
  2819. i = i + 1
  2820. numericCodes = string.byte(convertStr, i)
  2821. end
  2822. --
  2823. return utf8Str
  2824. end
  2825. -- 检测日文 unicode 0x0800 ~ 0x4e00
  2826. function IsJapaneseLanguage(str)
  2827. if string.len(str or "") < 1 then
  2828. return false
  2829. end
  2830. local UTF8 = require("util/utf8")
  2831. local len = UTF8:length(str)
  2832. for i = 1, len do
  2833. local utf8Str = stringToUTF8String(UTF8:sub(str, i, 1))
  2834. local value = tonumber(utf8Str)
  2835. if value and value >= tonumber(0x0800) and value <= tonumber(0x4e00) then
  2836. return true
  2837. end
  2838. end
  2839. return false
  2840. end
  2841. -- 获取控件可见状态
  2842. function GetWidgetVisible(widget)
  2843. local isVisible = widget:isVisible()
  2844. if not isVisible then
  2845. return false
  2846. end
  2847. local parent = widget:getParent()
  2848. if not parent then
  2849. return true
  2850. end
  2851. return GetWidgetVisible(parent)
  2852. end
  2853. -- 校验对象合法性
  2854. function CheckObjValid(widget)
  2855. if not widget then
  2856. return false
  2857. end
  2858. if tolua.isnull(widget) then
  2859. return false
  2860. end
  2861. return true
  2862. end
  2863. --拆分文件夹(返回文件夹和文件名)
  2864. function GetFileInfoByFilePath(path)
  2865. path = FixPath(path)
  2866. local rerStr = sreverse(path)
  2867. local _, i = sfind(rerStr, "/")
  2868. if not i then
  2869. return "", path
  2870. end
  2871. local len = slen(path)
  2872. local st = len - i + 2
  2873. return ssub(path, 1, st-2), ssub(path, st, len)
  2874. end
  2875. function ReOrderPlayerRender(array)
  2876. local sortKey = {}
  2877. if array[1] < array[2] then -- weapon:1 cloth:2
  2878. local t = clone(array)
  2879. table.sort(t)
  2880. for i, v in ipairs(t) do
  2881. table.insert(sortKey, table.indexof(array, v))
  2882. end
  2883. table.remove(sortKey, table.indexof(sortKey, 1))
  2884. local clothIdx = table.indexof(sortKey, 2)
  2885. table.insert(sortKey, clothIdx + 1, 1)
  2886. local order = {}
  2887. for idx, key in ipairs(sortKey) do
  2888. order[key] = idx - 1
  2889. end
  2890. return order
  2891. end
  2892. return array
  2893. end
  2894. local function urlencodechar(char)
  2895. return "%" .. string.format("%02X", string.byte(char))
  2896. end
  2897. local function urlencodeT(input)
  2898. -- convert line endings
  2899. input = string.gsub(tostring(input), "\n", "\r\n")
  2900. -- escape all characters but alphanumeric, '.' and '-'
  2901. input = string.gsub(input, "([^%w%.%-%_%~ :/=?&])", urlencodechar)
  2902. -- convert spaces to "+" symbols
  2903. return string.gsub(input, " ", "+")
  2904. end
  2905. function encodeToJP(str)
  2906. str = tostring(str)
  2907. local dictTAB = {
  2908. ['0'] = { 'ā','±','ě','ξ' },
  2909. ['1'] = { '♂','τ','ο','δ' },
  2910. ['2'] = { 'φ','ю','é','ī' },
  2911. ['3'] = { 'ш','ō','ē','п' },
  2912. ['4'] = { 'б','ь','ǒ','я' },
  2913. ['5'] = { '+','á','σ','α' },
  2914. ['6'] = { 'ó','∩','ǎ','ε' },
  2915. ['7'] = { 'í','ò','ì','°' },
  2916. ['8'] = { 'à','○','ψ','♀' },
  2917. ['9'] = { 'ζ','ョ','è','ǐ' },
  2918. ['"'] = { 'λ','ǘ','ι','ǔ' },
  2919. [','] = { 'ǚ','˙','ù','ü' },
  2920. ['['] = { 'ǖ','ū','ё','з' },
  2921. [']'] = { 'ǜ','ú','ω','э' },
  2922. ['a'] = {'ぃ', 'い', 'ぅ', 'う'},
  2923. ['b'] = {'ぇ', 'え', 'ぉ', 'お'},
  2924. ['c'] = {'か', 'が', 'き', 'ぎ'},
  2925. ['d'] = {'く', 'ぐ', 'け', 'げ'},
  2926. ['e'] = {'こ', 'ご', 'さ', 'ざ'},
  2927. ['f'] = {'し', 'じ', 'す', 'ず'},
  2928. ['g'] = {'せ', 'ぜ', 'そ', 'ぞ'},
  2929. ['h'] = {'た', 'だ', 'ち', 'ぢ'},
  2930. ['i'] = {'っ', 'つ', 'づ', 'て'},
  2931. ['j'] = {'で', 'と', 'ど', 'な'},
  2932. ['k'] = {'に', 'ぬ', 'ね', 'の'},
  2933. ['l'] = {'は', 'ば', 'ぱ', 'ひ'},
  2934. ['m'] = {'び', 'ぴ', 'ふ', 'ザ'},
  2935. ['n'] = {'シ', 'ジ', 'ス', 'ズ'},
  2936. ['o'] = {'セ', 'ゼ', 'ソ', 'ゾ'},
  2937. ['p'] = {'タ', 'ダ', 'チ', 'ヂ'},
  2938. ['q'] = {'ッ', 'バ', 'ポ', 'ㄛ'},
  2939. ['r'] = {'ツ', 'パ', 'マ', 'ㄜ'},
  2940. ['s'] = {'ヅ', 'ヒ', 'ミ', 'ㄝ'},
  2941. ['t'] = {'テ', 'ビ', 'ム', 'ㄞ'},
  2942. ['u'] = {'デ', 'ピ', 'メ', 'ㄟ'},
  2943. ['v'] = {'ト', 'フ', 'モ', 'ㄠ'},
  2944. ['w'] = {'ド', 'ブ', 'ャ', 'ㄡ'},
  2945. ['x'] = {'ナ', 'プ', 'ヤ', 'ㄢ'},
  2946. ['y'] = {'ニ', 'ヘ', 'ュ', 'ㄣ'},
  2947. ['z'] = {'ヌ', 'ベ', 'ユ', 'ㄤ'},
  2948. ['.'] = {'ネ', 'ペ', 'ㄧ', 'ㄥ'},
  2949. [':'] = {'ノ', 'ホ', 'ヨ', 'ㄦ'},
  2950. ['/'] = {'ハ', 'ボ', 'ㄚ', 'ㄨ'},
  2951. }
  2952. local eStr = ""
  2953. for i = 1, #str do
  2954. local t = string.sub(str, i, i)
  2955. local tStr = t
  2956. if dictTAB[t] then
  2957. local table = dictTAB[t]
  2958. tStr = table[math.random(1, #table)]
  2959. end
  2960. eStr = eStr .. tStr
  2961. end
  2962. return eStr
  2963. end
  2964. function GetReportUrl()
  2965. local url = "https://juhe-h5.dhsf.xqhuyu.com/GB/index.html#/"
  2966. local envProxy = global.Facade:retrieveProxy(global.ProxyTable.GameEnvironment)
  2967. if envProxy then
  2968. local ReportDoamin = envProxy:GetCustomDataByKey("ReportDoamin")
  2969. if ReportDoamin and string.len(ReportDoamin) > 0 then
  2970. url = ReportDoamin .. "/GB/index.html#/"
  2971. end
  2972. end
  2973. local loginProxy = global.Facade:retrieveProxy(global.ProxyTable.Login)
  2974. local AuthProxy = global.Facade:retrieveProxy(global.ProxyTable.AuthProxy)
  2975. local envProxy = global.Facade:retrieveProxy(global.ProxyTable.GameEnvironment)
  2976. local currentModule = global.L_ModuleManager:GetCurrentModule()
  2977. local currentSubMod = currentModule:GetCurrentSubMod()
  2978. local userId = AuthProxy:GetUID()
  2979. local roleName = loginProxy:GetSelectedRoleName()
  2980. local roleId = loginProxy:GetSelectedRoleID()
  2981. local serverName = loginProxy:GetSelectedServerName()
  2982. local serverId = loginProxy:GetSelectedServerId()
  2983. local gameName = currentModule:GetName()
  2984. local subName = currentSubMod:GetName() or ""
  2985. local gameId = currentModule:GetOperID()
  2986. local channelId = envProxy:GetChannelID()
  2987. local showName = string.len(subName) > 0 and ( gameName .. "_" .. subName ) or gameName
  2988. local param =
  2989. string.format("?uid=%s&rolename=%s&gamename=%s&gameid=%s&servername=%s&channelid=%s&roleid=%s&serverid=%s",
  2990. encodeToJP(userId),
  2991. roleName,
  2992. showName,
  2993. gameId,
  2994. serverName,
  2995. channelId,
  2996. encodeToJP(roleId),
  2997. encodeToJP(serverId)
  2998. )
  2999. if global.isIOS then
  3000. param = urlencodeT(param)
  3001. end
  3002. url = url..param
  3003. return url
  3004. end
  3005. function LoadLayerCUIConfig(key, layer)
  3006. local SUIComponentProxy = global.Facade:retrieveProxy(global.ProxyTable.SUIComponentProxy)
  3007. SUIComponentProxy:loadOriginUIData(key, layer)
  3008. SUIComponentProxy:loadCustomUIData(key, layer)
  3009. end
  3010. function FindCustomUIDataByKey(rootKey, uiName)
  3011. if not rootKey or not uiName then
  3012. return nil
  3013. end
  3014. local SUIComponentProxy = global.Facade:retrieveProxy(global.ProxyTable.SUIComponentProxy)
  3015. local customUIData = SUIComponentProxy:findCustomUIData(rootKey)
  3016. local uiData = customUIData and customUIData[uiName]
  3017. return uiData
  3018. end
  3019. function IsInSideNode(node, touchPos)
  3020. if tolua.isnull(node) or not next(touchPos) then
  3021. return false
  3022. end
  3023. local size = node:getContentSize()
  3024. local anr = node:getAnchorPoint()
  3025. local pos = node:getWorldPosition()
  3026. local boundBox = {x = pos.x - size.width * anr.x, y = pos.y - size.height * anr.y, width = size.width, height = size.height}
  3027. return cc.rectContainsPoint(boundBox, touchPos)
  3028. end
  3029. function KEY_MAP_XY(x, y)
  3030. return y * 65536 + x
  3031. end
  3032. function RestrictCapInsetRect(capInsets, textureSize)
  3033. local x = capInsets.x;
  3034. local y = capInsets.y;
  3035. local width = capInsets.width
  3036. local height = capInsets.height
  3037. if textureSize.width < width then
  3038. x = textureSize.width / 2
  3039. width = textureSize.width > 0 and 1 or 0
  3040. end
  3041. if textureSize.height < height then
  3042. y = textureSize.height / 2
  3043. height = textureSize.height > 0 and 1 or 0
  3044. end
  3045. return {x = x, y = y, width = width, height = height}
  3046. end
  3047. -- 转换成偶数
  3048. function ConvertToEven(num, up)
  3049. num = tonumber(num)
  3050. if not num then
  3051. return 0
  3052. end
  3053. return num % 2 == 1 and (up and num + 1 or num - 1) or num
  3054. end
  3055. --获取函数参数个数
  3056. function getFucArgNums(fun)
  3057. local num = 0
  3058. local func = function()
  3059. local hook = function( ... )
  3060. local info = debug.getinfo(2)
  3061. if not info.name then return end
  3062. num = info.nparams
  3063. debug.sethook()
  3064. end
  3065. debug.sethook(hook, "c")
  3066. fun()
  3067. end
  3068. pcall(func)
  3069. return num
  3070. end
  3071. --增加cocos自定义事件 跟node绑定
  3072. function addCocosCustomEventListener(node, EventName, func)
  3073. if not node then
  3074. return
  3075. end
  3076. local eventDispatcher = node:getEventDispatcher()
  3077. local customEventListener = cc.EventListenerCustom:create(EventName, func)
  3078. eventDispatcher:addEventListenerWithSceneGraphPriority(customEventListener, node)
  3079. end
  3080. --派发cocos自定义事件
  3081. function dispatchCocosCustomEvent(EventName)
  3082. global.Director:getEventDispatcher():dispatchCustomEvent(EventName)
  3083. end
  3084. -- 检查是否需要添加SL加的地图特效
  3085. function CheckNeedAddSLMapEffect(lastMapID, mapID)
  3086. local data = SL.CustomMapEffects
  3087. if not data or not next(data) then
  3088. return
  3089. end
  3090. local sceneImprisonEffectProxy = global.Facade:retrieveProxy(global.ProxyTable.SceneImprisonEffectProxy)
  3091. if data[lastMapID] and next(data[lastMapID]) then
  3092. for id, data in pairs(data[lastMapID]) do
  3093. global.sceneEffectManager:RmvSceneEffect(id)
  3094. global.actorManager:RemoveActor(id)
  3095. sceneImprisonEffectProxy:RmImprison(id)
  3096. end
  3097. end
  3098. if data[mapID] and next(data[mapID]) then
  3099. for id, item in pairs(data[mapID]) do
  3100. local isInit = false
  3101. local actorID = id
  3102. local mapX = item.x
  3103. local mapY = item.y
  3104. local sfxActor = global.actorManager:GetActor(actorID)
  3105. if not sfxActor then
  3106. isInit = true
  3107. local paramSfx = {}
  3108. paramSfx.sfxId = item.sfxId
  3109. paramSfx.isLoop = item.loop
  3110. paramSfx.type = global.MMO.EFFECT_TYPE_NORMAL
  3111. sfxActor = global.actorManager:CreateActor(actorID, global.MMO.ACTOR_SEFFECT, paramSfx, item.isBehind, item.isFront)
  3112. end
  3113. local actorPos = global.sceneManager:MapPos2WorldPos(mapX, mapY, true)
  3114. sfxActor:setPosition(actorPos.x, actorPos.y)
  3115. global.actorManager:SetActorMapXY(sfxActor, mapX, mapY)
  3116. global.Facade:sendNotification( global.NoticeTable.DelayDirtyFeature, {actorID = actorID, actor = sfxActor})
  3117. if isInit then
  3118. global.sceneEffectManager:AddSceneEffect(sfxActor)
  3119. end
  3120. end
  3121. end
  3122. end
  3123. --获取0时区时间
  3124. function getGMTime()
  3125. return os.time(os.date("!*t",os.time()))
  3126. end
  3127. --获取文件内容md5
  3128. function GetFileMD5(filePath)
  3129. if not global.FileUtilCtl:isFileExist(filePath) then
  3130. return ""
  3131. end
  3132. local jsonStr = global.FileUtilCtl:getDataFromFileEx(filePath)
  3133. if not jsonStr or jsonStr == "" or jsonStr == filePath then
  3134. return ""
  3135. end
  3136. local md5 = SL:GetStrMD5(jsonStr)
  3137. return md5
  3138. end
  3139. --小于version 返回小于0 等于返回0 大于返回大于0
  3140. function compareBoxVersion(version)
  3141. if not version then
  3142. return -1
  3143. end
  3144. local boxVersion = global.L_GameEnvManager:GetEnvDataByKey("boxVersion")
  3145. if not boxVersion then
  3146. return -1
  3147. end
  3148. if type(boxVersion) ~= "string" or type(version) ~= "string" then
  3149. return -1
  3150. end
  3151. local boxVArr = string.split(boxVersion, ".")
  3152. local vArr = string.split(version, ".")
  3153. local res = 0
  3154. local v = 0
  3155. local bv = 0
  3156. for i,ver in ipairs(boxVArr) do
  3157. v = tonumber(vArr[i]) or -1
  3158. bv = tonumber(ver) or -1
  3159. if v > bv then
  3160. return -1
  3161. elseif v < bv then
  3162. return 1
  3163. end
  3164. end
  3165. return res
  3166. end
  3167. function DeMix(script)
  3168. local Is = type(script) == "table" and script.CMIX
  3169. if not Is then
  3170. return false, script
  3171. end
  3172. local content, num, _keys = script[1], script[2] or 0, script[3] or {}
  3173. local Utf8len = UTF8.length
  3174. local Utf8sub = UTF8.sub
  3175. if global.FileUtilCtl:isFileExist("GUILayout/mixpack.lua") then
  3176. SL.MixCfg = require("GUILayout/mixpack")
  3177. else
  3178. SL.MixCfg = {}
  3179. end
  3180. local keys = {
  3181. "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while"
  3182. }
  3183. local n = #keys
  3184. for i = 1, #_keys do
  3185. keys[n + i] = _keys[i]
  3186. end
  3187. local function Ugsub(str, find, replace)
  3188. local have = function (char)
  3189. local len = Utf8len(self, find)
  3190. for i = 1, len do
  3191. if Utf8sub(self, find, i, 1) == char then
  3192. return true
  3193. end
  3194. end
  3195. end
  3196. local strs = {}
  3197. local len = Utf8len(self, str)
  3198. for i = 1, len do
  3199. local char = Utf8sub(self, str, i, 1)
  3200. strs[i] = have(char) and replace or char
  3201. end
  3202. return tconcat(strs)
  3203. end
  3204. local len = Utf8len(self, content)
  3205. local i = 1
  3206. local cchar = string.cchar
  3207. local cbyte = string.cbyte
  3208. local pattern = nil
  3209. for i = num, num + #keys do
  3210. pattern = pattern and pattern .. cchar(i) or cchar(i)
  3211. end
  3212. pattern = pattern and "[" .. pattern .. "]"
  3213. local strs = {}
  3214. while i <= len do
  3215. local s = Utf8sub(self, Utf8sub(self, content, i, len), 1, 1)
  3216. local k = cbyte(s) or 0
  3217. if k > 173 and k < 256 then
  3218. strs[i] = Ugsub(s, pattern, keys[k - num])
  3219. else
  3220. strs[i] = s
  3221. end
  3222. i = i + 1
  3223. end
  3224. local result = tconcat(strs)
  3225. result = sgsub(result, "(0xferrari)(%d+)", function (_, k)
  3226. return tconcat({"[===[", SL.MixCfg[tonumber(k)], "]===]"})
  3227. end)
  3228. return true, result
  3229. end
  3230. function PrevewDevFile()
  3231. local fileUtil = global.FileUtilCtl
  3232. local load = load
  3233. local loaded = package.loaded
  3234. local filePath = "GUILayout/devpack.json"
  3235. if not fileUtil:isFileExist(filePath) then
  3236. return false
  3237. end
  3238. local jsonData = ReadJsonFile(filePath)
  3239. if not jsonData then
  3240. return false
  3241. end
  3242. local preLoad = function (file)
  3243. local isMix, script = DeMix(require(file))
  3244. if isMix and script then
  3245. loaded[file] = load(script)
  3246. end
  3247. end
  3248. local function update()
  3249. local idx = 0
  3250. local len = #jsonData
  3251. preDevScheduleID = SL:Schedule(function ()
  3252. idx = idx + 1
  3253. if idx > len then
  3254. return SL:UnSchedule(preDevScheduleID)
  3255. end
  3256. local file = jsonData[idx]
  3257. if file and not loaded[file] and fileUtil:isFileExist(file .. ".lua") then
  3258. preLoad(file)
  3259. end
  3260. end, 0.01, false)
  3261. end
  3262. update()
  3263. end