Last active
December 21, 2015 18:19
-
-
Save tangzero/6346573 to your computer and use it in GitHub Desktop.
Squishfied version of https://github.com/makotok/Hanappe/tree/master/projects/hanappe-framework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package.preload['hp/core/Application'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- Module for the start of the application.<br> | |
-- | |
-- @class table | |
-- @name Application | |
-------------------------------------------------------------------------------- | |
-- import | |
local Event = require "hp/event/Event" | |
local EventDispatcher = require "hp/event/EventDispatcher" | |
local InputManager = require "hp/manager/InputManager" | |
-- class | |
local M = EventDispatcher() | |
local super = EventDispatcher | |
-------------------------------------------------------------------------------- | |
-- Start the application. <br> | |
-- You can specify the behavior of the entire application by the config. | |
-- @param config | |
-------------------------------------------------------------------------------- | |
function M:start(config) | |
local title = config.title | |
local screenWidth = config.screenWidth or MOAIEnvironment.horizontalResolution | |
local screenHeight = config.screenHeight or MOAIEnvironment.verticalResolution | |
local viewScale = config.viewScale or 1 | |
local viewWidth = screenWidth / viewScale | |
local viewHeight = screenHeight / viewScale | |
self.title = title | |
self.screenWidth = screenWidth | |
self.screenHeight = screenHeight | |
self.viewWidth = viewWidth | |
self.viewHeight = viewHeight | |
self.viewScale = viewScale | |
MOAISim.openWindow(title, screenWidth, screenHeight) | |
InputManager:initialize() | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns whether the mobile execution environment. | |
-- @return True in the case of mobile. | |
-------------------------------------------------------------------------------- | |
function M:isMobile() | |
local brand = MOAIEnvironment.osBrand | |
return brand == 'Android' or brand == 'iOS' | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns whether the desktop execution environment. | |
-- @return True in the case of desktop. | |
-------------------------------------------------------------------------------- | |
function M:isDesktop() | |
return not self:isMobile() | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns true if the Landscape mode. | |
-- @return true if the Landscape mode. | |
-------------------------------------------------------------------------------- | |
function M:isLandscape() | |
local w, h = MOAIGfxDevice.getViewSize() | |
return w > h | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the background color. | |
-------------------------------------------------------------------------------- | |
function M:setClearColor(r, g, b, a) | |
MOAIGfxDevice.setClearColor(r, g, b, a) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the scale of the Viewport to the screen. | |
-- @return scale of the x-direction, scale of the y-direction, | |
-------------------------------------------------------------------------------- | |
function M:getViewScale() | |
return self.viewScale | |
end | |
return M | |
end) | |
package.preload['hp/display/Animation'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This is a class to animate the MOAIProp. | |
-- You can define the animation to flow. | |
-- If you want to achieve complex animations, will say only this class. | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local MOAIPropUtil = require "hp/util/MOAIPropUtil" | |
local Executors = require "hp/util/Executors" | |
local Event = require "hp/event/Event" | |
local EventDispatcher = require "hp/event/EventDispatcher" | |
-- class | |
local M = class(EventDispatcher) | |
local super = EventDispatcher | |
-- create animation context. | |
local function createContext(self, params) | |
local context = params or {} | |
context.stopped = false | |
context.paused = false | |
table.insert(self._contexts, context) | |
return context | |
end | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-- @param targets (option)MOAIProp array. Or, MOAIProp instance. | |
-- @param sec (option)Animation time of each command. | |
-- @param easeType MOAIEaseType. | |
-------------------------------------------------------------------------------- | |
function M:init(targets, sec, easeType) | |
super.init(self) | |
self._commands = {} | |
self._targets = type(targets) == "userdata" and {targets} or targets or {} | |
self._running = false | |
self._second = sec and sec or 1 | |
self._easeType = easeType | |
self._contexts = {} | |
self._throttle = 1 | |
self._paused = false | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns whether the animation. | |
-- @return True in the case of animation. | |
-------------------------------------------------------------------------------- | |
function M:isRunning() | |
return self._running | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns whether the animation is paused. | |
-- @return boolean indicating the pause state of the current animation. | |
-------------------------------------------------------------------------------- | |
function M:isPaused() | |
return self._paused | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the position of the target object.<br> | |
-- When they are performed is done at the time of animation. | |
-- @param left Left of the position. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:setLeft(left) | |
local playFunc = function(self, context) | |
for i, v in ipairs(self._targets) do | |
MOAIPropUtil.setLeft(v, left) | |
end | |
end | |
local command = self:newCommand(playFunc) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the position of the target object.<br> | |
-- When they are performed is done at the time of animation. | |
-- @param top Top of the position. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:setTop(top) | |
local playFunc = function(self, context) | |
for i, v in ipairs(self._targets) do | |
MOAIPropUtil.setTop(v, top) | |
end | |
end | |
local command = self:newCommand(playFunc) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the position of the target object.<br> | |
-- When they are performed is done at the time of animation. | |
-- @param right Right of the position. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:setRight(right) | |
local playFunc = function(self, context) | |
for i, v in ipairs(self._targets) do | |
MOAIPropUtil.setRight(v, right) | |
end | |
end | |
local command = self:newCommand(playFunc) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the position of the target object.<br> | |
-- When they are performed is done at the time of animation. | |
-- @param bottom Bottom of the position. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:setBottom(bottom) | |
local playFunc = function(self, context) | |
for i, v in ipairs(self._targets) do | |
MOAIPropUtil.setBottom(v, bottom) | |
end | |
end | |
local command = self:newCommand(playFunc) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the position of the target object.<br> | |
-- When they are performed is done at the time of animation. | |
-- @param left Left of the position. | |
-- @param top Top of the position. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:setPos(left, top) | |
local playFunc = function(self, context) | |
for i, v in ipairs(self._targets) do | |
MOAIPropUtil.setPos(v, left, top) | |
end | |
end | |
local command = self:newCommand(playFunc) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the position of the target object.<br> | |
-- When they are performed is done at the time of animation. | |
-- @param x X of the position. | |
-- @param y Y of the position. | |
-- @param z Z of the position. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:setLoc(x, y, z) | |
local playFunc = function(self, context) | |
for i, v in ipairs(self._targets) do | |
v:setLoc(x, y, z) | |
end | |
end | |
local command = self:newCommand(playFunc) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Move the target objects.<br> | |
-- When they are performed is done at the time of animation. | |
-- @param moveX X of the position. | |
-- @param moveY Y of the position. | |
-- @param moveZ Z of the position. | |
-- @param sec (option)Time animation. | |
-- @param mode (option)MOAIEaseType. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:moveLoc(moveX, moveY, moveZ, sec, mode) | |
local actionFunc = function(target, tSec, tMode) | |
return target:moveLoc(moveX, moveY, moveZ, tSec, tMode) | |
end | |
local command = self:newActionCommand(actionFunc, sec, mode) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Seek the target objects.<br> | |
-- When they are performed is done at the time of animation. | |
-- @param x X of the position. | |
-- @param y Y of the position. | |
-- @param z Z of the position. | |
-- @param sec (option)Time animation. | |
-- @param mode (option)MOAIEaseType. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:seekLoc(x, y, z, sec, mode) | |
local actionFunc = function(target, tSec, tMode) | |
return target:seekLoc(x, y, z, tSec, tMode) | |
end | |
local command = self:newActionCommand(actionFunc, sec, mode) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the rotation of the object. | |
-- @param x Rotation of the x-axis. | |
-- @param y Rotation of the y-axis. | |
-- @param z Rotation of the z-axis. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:setRot(x, y, z) | |
local playFunc = function(self, context) | |
for i, v in ipairs(self._targets) do | |
v:setRot(x, y, z) | |
end | |
end | |
local command = self:newCommand(playFunc) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Move the rotation of the object. | |
-- @param x Rotation of the x-axis. | |
-- @param y Rotation of the y-axis. | |
-- @param z Rotation of the z-axis. | |
-- @param sec (option)Time animation. | |
-- @param mode (option)MOAIEaseType. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:moveRot(x, y, z, sec, mode) | |
local actionFunc = function(target, tSec, tMode) | |
return target:moveRot(x, y, z, tSec, tMode) | |
end | |
local command = self:newActionCommand(actionFunc, sec, mode) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Seek the rotation of the object. | |
-- @param x Rotation of the x-axis. | |
-- @param y Rotation of the y-axis. | |
-- @param z Rotation of the z-axis. | |
-- @param sec (option)Time animation. | |
-- @param mode (option)MOAIEaseType. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:seekRot(x, y, z, sec, mode) | |
local actionFunc = function(target, sec, mode) | |
return target:seekRot(x, y, z, sec, mode) | |
end | |
local command = self:newActionCommand(actionFunc, sec, mode) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the scale of the target object. | |
-- @param x Scale of the x-axis | |
-- @param y Scale of the y-axis. | |
-- @param z Scale of the z-axis. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:setScl(x, y, z) | |
local playFunc = function(self, context) | |
for i, v in ipairs(self._targets) do | |
v:setScl(x, y, z) | |
end | |
end | |
local command = self:newCommand(playFunc) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Move the scale of the target object. | |
-- @param x Scale of the x-axis | |
-- @param y Scale of the y-axis. | |
-- @param z Scale of the z-axis. | |
-- @param sec (option)Time animation. | |
-- @param mode (option)MOAIEaseType. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:moveScl(x, y, z, sec, mode) | |
local actionFunc = function(target, sec, mode) | |
return target:moveScl(x, y, z, sec, mode) | |
end | |
local command = self:newActionCommand(actionFunc, sec, mode) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Seek the scale of the target object. | |
-- @param x Scale of the x-axis | |
-- @param y Scale of the y-axis. | |
-- @param z Scale of the z-axis. | |
-- @param sec (option)Time animation. | |
-- @param mode (option)MOAIEaseType. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:seekScl(x, y, z, sec, mode) | |
local actionFunc = function(target, sec, mode) | |
return target:seekScl(x, y, z, sec, mode) | |
end | |
local command = self:newActionCommand(actionFunc, sec, mode) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the value of an attribute of the object. | |
-- @param attrID Attribute. | |
-- @param value Value. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:setAttr(attrID, value) | |
local playFunc = function(self, context) | |
for i, v in ipairs(self._targets) do | |
v:setAttr(attrID, value) | |
end | |
end | |
local command = self:newCommand(playFunc) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Move the value of an attribute of the object. | |
-- @param attrID Attribute. | |
-- @param value Value. | |
-- @param sec (option)Time animation. | |
-- @param mode (option)MOAIEaseType. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:moveAttr(attrID, value, sec, mode) | |
local actionFunc = function(target, sec, mode) | |
return target:moveAttr(attrID, value, sec, mode) | |
end | |
local command = self:newActionCommand(actionFunc, sec, mode) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Seek the value of an attribute of the object. | |
-- @param attrID Attribute. | |
-- @param value Value. | |
-- @param sec (option)Time animation. | |
-- @param mode (option)MOAIEaseType. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:seekAttr(attrID, value, sec, mode) | |
local actionFunc = function(target, sec, mode) | |
return target:seekAttr(attrID, value, sec, mode) | |
end | |
local command = self:newActionCommand(actionFunc, sec, mode) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the index. | |
-- @param index Index. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:setIndex(index) | |
local playFunc = function(self, context) | |
for i, v in ipairs(self._targets) do | |
v:setIndex(index) | |
end | |
end | |
local command = self:newCommand(playFunc) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Move the indexes. | |
-- @param indexes Array of indices. | |
-- @param sec (option)Time animation. | |
-- @param mode (option)MOAIEaseType. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:moveIndex(indexes, sec, mode) | |
local curve = MOAIAnimCurve.new() | |
local anim = MOAIAnim.new() | |
local playFunc = function(self, context) | |
if anim and anim:isBusy() then | |
anim:stop() | |
end | |
local tSec = sec or self._second | |
local tMode = mode or MOAITimer.LOOP | |
curve:reserveKeys(#indexes) | |
for i = 1, #indexes do | |
curve:setKey(i, tSec * (i - 1), indexes[i], MOAIEaseType.FLAT ) | |
end | |
anim:setMode(tMode) | |
anim:reserveLinks(#self._targets) | |
for i, prop in ipairs(self._targets) do | |
anim:setLink(i, curve, prop, MOAIProp.ATTR_INDEX ) | |
end | |
anim:setCurve(curve) | |
anim:start() | |
if tMode == MOAITimer.LOOP then | |
return | |
end | |
MOAICoroutine.blockOnAction(anim) | |
end | |
local resumeFunc = function(self, context) | |
anim:pause(false) | |
end | |
local pauseFunc = function(self, context) | |
anim:pause(true) | |
end | |
local stopFunc = function(self, context) | |
anim:stop() | |
end | |
local command = self:newCommand(playFunc, stopFunc, resumeFunc, pauseFunc) | |
command.action = anim | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- The fade in objects. | |
-- @param sec (option)Time animation. | |
-- @param mode (option)MOAIEaseType. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:fadeIn(sec, mode) | |
local actionFunc = function(target, sec, mode) | |
target:setColor(0, 0, 0, 0) | |
return target:seekColor(1, 1, 1, 1, sec, mode) | |
end | |
local command = self:newActionCommand(actionFunc, sec, mode) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- The fade out objects. | |
-- @param sec (option)Time animation. | |
-- @param mode (option)MOAIEaseType. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:fadeOut(sec, mode) | |
local actionFunc = function(target, sec, mode) | |
target:setColor(1, 1, 1, 1) | |
return target:seekColor(0, 0, 0, 0, sec, mode) | |
end | |
local command = self:newActionCommand(actionFunc, sec, mode) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the color of the object. | |
-- @param red Red. | |
-- @param green Green. | |
-- @param blue Blue. | |
-- @param alpha Alpha. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:setColor(red, green, blue, alpha) | |
local playFunc = function(self) | |
for i, v in ipairs(self._targets) do | |
v:setColor(red, green, blue, alpha) | |
end | |
end | |
local command = self:newCommand(playFunc) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Move the color of the object. | |
-- @param red Red. | |
-- @param green Green. | |
-- @param blue Blue. | |
-- @param alpha Alpha. | |
-- @param sec (option)Time animation. | |
-- @param mode (option)MOAIEaseType. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:moveColor(red, green, blue, alpha, sec, mode) | |
local actionFunc = function(target, sec, mode) | |
return target:moveColor(red, green, blue, alpha, sec, mode) | |
end | |
local command = self:newActionCommand(actionFunc, sec, mode) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Seek the color of the object. | |
-- @param red Red. | |
-- @param green Green. | |
-- @param blue Blue. | |
-- @param alpha Alpha. | |
-- @param sec (option)Time animation. | |
-- @param mode (option)MOAIEaseType. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:seekColor(red, green, blue, alpha, sec, mode) | |
local actionFunc = function(target, sec, mode) | |
return target:seekColor(red, green, blue, alpha, sec, mode) | |
end | |
local command = self:newActionCommand(actionFunc, sec, mode) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the target object visible. | |
-- @param value Visible. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:setVisible(value) | |
local playFunc = function(self) | |
for i, v in ipairs(self._targets) do | |
v:setVisible(value) | |
end | |
end | |
local command = self:newCommand(playFunc) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Call function. | |
-- @param func function object. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:callFunc(func) | |
local playFunc = function(self) | |
func(self) | |
end | |
local command = self:newCommand(playFunc) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- The parallel execution of the animation of the argument. | |
-- @param ... Animations | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:parallel(...) | |
local animations = {...} | |
local command = self:newCommand( | |
-- play | |
function(self, context) | |
local count = 0 | |
local max = #animations | |
-- animation complete handler | |
local completeHandler = function(e) | |
count = count + 1 | |
end | |
-- play animations | |
for i, a in ipairs(animations) do | |
if self._throttle ~= a:getThrottle() then | |
a:setThrottle(self._throttle) | |
end | |
a:play {onComplete = completeHandler} | |
end | |
-- wait animations | |
while count < max do | |
coroutine.yield() | |
for i, a in ipairs(animations) do | |
if self._throttle ~= a:getThrottle() then | |
a:setThrottle(self._throttle) | |
end | |
end | |
end | |
end, | |
-- stop | |
function(self, context) | |
for i, a in ipairs(animations) do | |
a:stop() | |
end | |
end, | |
-- resume | |
function(self, context) | |
for i, a in ipairs(animations) do | |
if a:isRunning() then | |
if self._throttle ~= a:getThrottle() then | |
a:setThrottle(self._throttle) | |
end | |
a:resume() | |
end | |
end | |
end, | |
-- pause | |
function(self, context) | |
for i, a in ipairs(animations) do | |
if a:isRunning() then | |
a:pause() | |
end | |
end | |
end | |
) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- The sequential execution of the animation argument. | |
-- @param ... Animations | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:sequence(...) | |
local animations = {...} | |
local currentAnimation = nil | |
local command = self:newCommand( | |
-- play | |
function(self, context) | |
local count = 0 | |
local max = #animations | |
for i, animation in ipairs(animations) do | |
if self._throttle ~= animation:getThrottle() then | |
animation:setThrottle(self._throttle) | |
end | |
animation:play() | |
while animation:isRunning() do | |
coroutine.yield() | |
if self._throttle ~= animation:getThrottle() then | |
animation:setThrottle(self._throttle) | |
end | |
end | |
if context.stopped then | |
break | |
end | |
end | |
end, | |
-- stop | |
function(self, context) | |
for i, animation in ipairs(animations) do | |
animation:stop() | |
end | |
end, | |
-- resume | |
function(self, context) | |
for i, animation in ipairs(animations) do | |
if animation:isRunning() then | |
if self._throttle ~= animation:getThrottle() then | |
animation:setThrottle(self._throttle) | |
end | |
animation:resume() | |
end | |
end | |
end, | |
-- pause | |
function(self, context) | |
for i, animation in ipairs(animations) do | |
if animation:isRunning() then | |
animation:pause() | |
end | |
end | |
end | |
) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Run the specified number the animation of the argument.<br> | |
-- If you specify a 0 to maxCount is an infinite loop.<br> | |
-- If maxCount of the function, and loop until it returns the function's return value is true.<br> | |
-- | |
-- @param maxCount Loop count, or, End judgment function. | |
-- @param animation Animation | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:loop(maxCount, animation) | |
local loopFunc = type(maxCount) == "function" and maxCount | |
local command = self:newCommand( | |
-- play | |
function(self, context) | |
local count = 0 | |
while true do | |
if self._throttle ~= animation:getThrottle() then | |
animation:setThrottle(self._throttle) | |
end | |
animation:play() | |
while animation:isRunning() do | |
coroutine.yield() | |
if self._throttle ~= animation:getThrottle() then | |
animation:setThrottle(self._throttle) | |
end | |
end | |
if context.stopped then | |
break | |
end | |
count = count + 1 | |
if maxCount > 0 and count > maxCount then | |
break | |
end | |
end | |
end, | |
-- stop | |
function(self, context) | |
animation:stop() | |
end, | |
-- resume | |
function(self, context) | |
if self._throttle ~= animation:getThrottle() then | |
animation:setThrottle(self._throttle) | |
end | |
animation:resume() | |
end, | |
-- pause | |
function(self, context) | |
animation:pause() | |
end | |
) | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Wait a specified amount of time. | |
-- @param sec Waiting time. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:wait(sec) | |
local timer = MOAITimer.new() | |
timer:setSpan(sec) | |
local command = self:newCommand( | |
-- play | |
function(self, context) | |
timer:start() | |
MOAICoroutine.blockOnAction(timer) | |
end, | |
-- stop | |
function(self, context) | |
timer:stop() | |
end, | |
-- resume | |
function(self, context) | |
timer:pause(false) | |
end, | |
-- pause | |
function(self, context) | |
timer:pause(true) | |
end | |
) | |
command.action = timer | |
self:addCommand(command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- To start the animation.<br> | |
-- If during the start will be ignored.<br> | |
-- | |
-- @param params (option)Parameters that control the behavior. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:play(params) | |
if self:isRunning() then | |
-- resume, instead of to start a new context, if in pause state | |
if self:isPaused() then | |
self:resume() | |
end | |
else | |
self._running = true | |
local context = createContext(self, params) | |
Executors.callLater(self.playInternal, self, context) | |
end | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- To execute the command.<br> | |
-- You will not be accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:playInternal(context) | |
if context.stopped then | |
return | |
end | |
local commands = table.copy(self._commands) | |
for i, command in ipairs(commands) do | |
context.currentCommand = command | |
if command.action then | |
command.action:throttle(self._throttle) | |
end | |
while context.paused do | |
-- spinlock until animation is resumed or stopped | |
if context.stopped then | |
return | |
end | |
coroutine.yield() | |
end | |
context.currentCommand.play(self, context) | |
if context.stopped then | |
return | |
end | |
end | |
self._running = false | |
if context.onComplete then | |
context.onComplete(self, context) | |
end | |
local e = Event(Event.COMPLETE) | |
e.context = context | |
self:dispatchEvent(e) | |
end | |
-------------------------------------------------------------------------------- | |
-- Resumes the animation if it's running and in pause state. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:resume() | |
if self:isRunning() and self:isPaused() then | |
self._paused = false | |
for _, context in ipairs(self._contexts) do | |
context.paused = false | |
end | |
for _, command in ipairs(self._commands) do | |
if command.action then | |
command.action:throttle(self._throttle) | |
end | |
command.resume(self, context) | |
end | |
end | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Pauses the animation if it's running and not in pause state. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:pause() | |
if self:isRunning() and not self:isPaused() then | |
self._paused = true | |
for _, context in ipairs(self._contexts) do | |
context.paused = true | |
end | |
for _, command in ipairs(self._commands) do | |
command.pause(self, context) | |
end | |
end | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Stop the animation. | |
-------------------------------------------------------------------------------- | |
function M:stop() | |
if not self:isRunning() then | |
return self | |
end | |
self._running = false | |
-- clear contexts | |
for i, context in ipairs(self._contexts) do | |
context.stopped = true | |
end | |
for _, command in ipairs(self._commands) do | |
command.stop(self) | |
end | |
self._contexts = {} | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Clears the definition animation. | |
-------------------------------------------------------------------------------- | |
function M:clear() | |
if self:isRunning() then | |
return self | |
end | |
self._commands = {} | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Add a command run animation.<br> | |
-- Usually does not need to be used.<br> | |
-- You can add a custom command.<br> | |
-- @param command play,stop,restart | |
-------------------------------------------------------------------------------- | |
function M:addCommand(command) | |
table.insert(self._commands, command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Command to generate the animation.<br> | |
-- @param playFunc playFunc(callback) | |
-- @param stopFunc stopFunc() | |
-- @param resumeFunc resumeFunc() | |
-- @param pauseFunc pauseFunc() | |
-- @return command | |
-------------------------------------------------------------------------------- | |
function M:newCommand(playFunc, stopFunc, resumeFunc, pauseFunc) | |
local emptyFunc = function(obj, callback) end | |
playFunc = playFunc | |
stopFunc = stopFunc and stopFunc or emptyFunc | |
resumeFunc = resumeFunc and resumeFunc or emptyFunc | |
pauseFunc = pauseFunc and pauseFunc or emptyFunc | |
local command = {play = playFunc, stop = stopFunc, resume = resumeFunc, pause = pauseFunc} | |
return command | |
end | |
-------------------------------------------------------------------------------- | |
-- To generate the asynchronous command with the action. | |
-- @param actionFunc 関数名 | |
-- @param sec Time Animation. | |
-- @param mode MOAIEaseType. | |
-- @return command | |
-------------------------------------------------------------------------------- | |
function M:newActionCommand(actionFunc, sec, mode) | |
local actionGroup = MOAIAction.new() | |
local command = self:newCommand( | |
-- play | |
function(self, context) | |
if #self._targets == 0 then | |
return | |
end | |
local tSec = sec or self._second | |
local tMode = mode or self._easeType | |
for i, target in ipairs(self._targets) do | |
local action = actionFunc(target, tSec, tMode) | |
actionGroup:addChild(action) | |
end | |
actionGroup:start() | |
MOAICoroutine.blockOnAction(actionGroup) | |
end, | |
-- stop | |
function(self, context) | |
actionGroup:stop() | |
end, | |
-- resume | |
function(self, context) | |
actionGroup:pause(false) | |
end, | |
-- pause | |
function(self, context) | |
actionGroup:pause(true) | |
end | |
) | |
command.action = actionGroup | |
return command | |
end | |
-------------------------------------------------------------------------------- | |
-- Changes the throttle, as defined by MOAIAction.throttle, of the animation. | |
-- If the animation is already running, update throttle on all commands. | |
-- @param newThrottle Desired new throttle value | |
-- @return none | |
-------------------------------------------------------------------------------- | |
function M:setThrottle(newThrottle) | |
if self:isRunning() then | |
for _, command in ipairs(self._commands) do | |
if command.action then | |
command.action:throttle(newThrottle) | |
end | |
end | |
end | |
self._throttle = newThrottle | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the current throttle value | |
-- @return throttle | |
-------------------------------------------------------------------------------- | |
function M:getThrottle() | |
return self._throttle | |
end | |
return M | |
end) | |
package.preload['hp/display/BackgroundSprite'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This class draws the grid. <br> | |
-- Without the use of MOAITileDeck, use the MOAIGfxQuadDeck2D. <br> | |
-- Corresponding to the format can be flexibility. <br> | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local MapSprite = require "hp/display/MapSprite" | |
-- class | |
local super = MapSprite | |
local M = class(super) | |
---------------------------------------------------------------- | |
-- The constructor. | |
-- @param params (option)Parameter is set to Object.<br> | |
---------------------------------------------------------------- | |
function M:init(params) | |
super.init(self) | |
self:setRepeat(true) | |
self:copyParams(params) | |
end | |
function M:setTexture(texture) | |
super.setTexture(self, texture) | |
if self.texture then | |
local w, h = self.texture:getSize() | |
self:setMapSize(1, 1, w, h) | |
self:setMapSheets(w, h, 1, 1) | |
self:setTile(1, 1, 1) | |
end | |
end | |
return M end) | |
package.preload['hp/display/DisplayObject'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- The base class for all display objects. <br> | |
-- To inherit MOAIPropUtil, you can use the convenience function. <br> | |
-- To inherit EventDispatcher, you can use the event notification. <br> | |
-- <br> | |
-- Use the MOAIProp class. <br> | |
-- By changing the M.MOAI_CLASS, you can change to another class. <br> | |
-- See MOAIProp.<br> | |
-- Base Classes => EventDispatcher, MOAIPropUtil<br> | |
-------------------------------------------------------------------------------- | |
-- import | |
local class = require "hp/lang/class" | |
local table = require "hp/lang/table" | |
local EventDispatcher = require "hp/event/EventDispatcher" | |
local MOAIPropUtil = require "hp/util/MOAIPropUtil" | |
local PropertyUtil = require "hp/util/PropertyUtil" | |
-- class | |
local M = class(EventDispatcher, MOAIPropUtil) | |
local MOAIPropInterface = MOAIProp.getInterfaceTable() | |
-- constraints | |
M.MOAI_CLASS = MOAIProp | |
M.PRIORITY_PROPERTIES = { | |
"texture", | |
} | |
-------------------------------------------------------------------------------- | |
-- Instance generating functions.<br> | |
-- Unlike an ordinary class, and based on the MOAI_CLASS.<br> | |
-- To inherit this function is not recommended.<br> | |
-- @param ... params. | |
-- @return instance. | |
-------------------------------------------------------------------------------- | |
function M:new(...) | |
local obj = self.MOAI_CLASS.new() | |
table.copy(self, obj) | |
EventDispatcher.init(obj) | |
if obj.init then | |
obj:init(...) | |
end | |
obj.new = nil | |
obj.init = nil | |
return obj | |
end | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-------------------------------------------------------------------------------- | |
function M:init(...) | |
self._touchEnabled = true | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the name. | |
-- @param name Object name.<br> | |
-------------------------------------------------------------------------------- | |
function M:setName(name) | |
self.name = name | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the name. | |
-- @return Object name. | |
-------------------------------------------------------------------------------- | |
function M:getName() | |
return self.name | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the parent. | |
-- @return parent object. | |
-------------------------------------------------------------------------------- | |
function M:getParent() | |
return self._parent | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the parent. | |
-- @param parent parent | |
-------------------------------------------------------------------------------- | |
function M:setParent(parent) | |
if parent == self:getParent() then | |
return | |
end | |
-- remove | |
if self._parent and self._parent.isGroup then | |
self._parent:removeChild(self) | |
end | |
-- set | |
MOAIPropInterface.setParent(self, parent) | |
self._parent = parent | |
-- add | |
if parent and parent.isGroup then | |
parent:addChild(self) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the parameter setter function. | |
-- @param params Parameter is set to Object.<br> | |
-------------------------------------------------------------------------------- | |
function M:copyParams(params) | |
if not params then | |
return | |
end | |
-- copy priority properties | |
local priorityParams = {} | |
if self.PRIORITY_PROPERTIES then | |
for i, v in ipairs(self.PRIORITY_PROPERTIES) do | |
priorityParams[v] = params[v] | |
params[v] = nil | |
end | |
PropertyUtil.setProperties(self, priorityParams, true) | |
end | |
-- priority properties | |
PropertyUtil.setProperties(self, params, true) | |
-- reset params | |
if self.PRIORITY_PROPERTIES then | |
for i, v in ipairs(self.PRIORITY_PROPERTIES) do | |
params[v] = priorityParams[v] | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the MOAILayer instance. | |
-------------------------------------------------------------------------------- | |
function M:setLayer(layer) | |
if self.layer == layer then | |
return | |
end | |
if self.layer then | |
self.layer:removeProp(self) | |
end | |
self.layer = layer | |
if self.layer then | |
layer:insertProp(self) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the MOAILayer. | |
-------------------------------------------------------------------------------- | |
function M:getLayer() | |
return self.layer | |
end | |
-------------------------------------------------------------------------------- | |
-- Event Handler | |
-------------------------------------------------------------------------------- | |
function M:getNestLevel() | |
local parent = self:getParent() | |
if parent and parent.getNestLevel then | |
return parent:getNestLevel() + 1 | |
end | |
return 1 | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the touch enabled. | |
-- @param value touch enabled. | |
-------------------------------------------------------------------------------- | |
function M:setTouchEnabled(value) | |
self._touchEnabled = value | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the touch enabled. | |
-- @param value touch enabled. | |
-------------------------------------------------------------------------------- | |
function M:isTouchEnabled() | |
return self._touchEnabled | |
end | |
-------------------------------------------------------------------------------- | |
-- Dispose resourece. | |
-------------------------------------------------------------------------------- | |
function M:dispose() | |
local parent = self:getParent() | |
if parent and parent.isGroup then | |
parent:removeChild(self) | |
end | |
self:setLayer(nil) | |
end | |
-------------------------------------------------------------------------------- | |
-- If the object will collide with the screen, it returns true.<br> | |
-- TODO:If you are rotating, it will not work. | |
-- @param prop MOAIProp object | |
-- @return If the object is a true conflict | |
-------------------------------------------------------------------------------- | |
function M:hitTestObject(prop) | |
local worldX, worldY = prop:getWorldLoc() | |
local x, y = prop:getLoc() | |
local diffX, diffY = worldX - x, worldY - y | |
local left, top = MOAIPropUtil.getLeft(prop) + diffX, MOAIPropUtil.getTop(prop) + diffY | |
local right, bottom = MOAIPropUtil.getRight(prop) + diffX, MOAIPropUtil.getBottom(prop) + diffY | |
if self:inside(left, top, 0) then | |
return true | |
end | |
if self:inside(right, bottom, 0) then | |
return true | |
end | |
if self:inside(left, bottom, 0) then | |
return true | |
end | |
if self:inside(right, bottom, 0) then | |
return true | |
end | |
return false | |
end | |
-------------------------------------------------------------------------------- | |
-- If the object will collide with the screen, it returns true.<br> | |
-- @param screenX x of screen | |
-- @param screenY y of screen | |
-- @param screenZ (option)z of screen | |
-- @return If the object is a true conflict | |
-------------------------------------------------------------------------------- | |
function M:hitTestScreen(screenX, screenY, screenZ) | |
assert(self.layer) | |
screenZ = screenZ or 0 | |
local worldX, worldY, worldZ = self.layer:wndToWorld(screenX, screenY, screenZ) | |
return self:inside(worldX, worldY, worldZ) | |
end | |
-------------------------------------------------------------------------------- | |
-- If the object will collide with the world, it returns true.<br> | |
-- @param worldX world x of layer | |
-- @param worldY world y of layer | |
-- @param worldZ (option)world z of layer | |
-- @return If the object is a true conflict | |
-------------------------------------------------------------------------------- | |
function M:hitTestWorld(worldX, worldY, worldZ) | |
worldZ = worldZ or 0 | |
return self:inside(worldX, worldY, worldZ) | |
end | |
return M end) | |
package.preload['hp/display/Graphics'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- The DisplayObject that has graphics capabilities. <br> | |
-- You can call in the method chain MOAIDraw. <br> | |
-- See MOAIDraw. <br> | |
-- <br> | |
-- Base Classes => DisplayObject, Resizable<br> | |
-- <code> | |
-- example)<br> | |
-- local g = Graphics({width = 100, height = 100})<br> | |
-- g:setPenColor(1, 0, 0, 1):fillRect():drawRect()<br> | |
-- g:setPenColor(0, 1, 0, 1):fillRect(25, 25, 50, 50):drawRect(25, 25, 50, 50)<br> | |
-- g:setLayer(layer)<br> | |
-- </code> | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local DisplayObject = require "hp/display/DisplayObject" | |
local Resizable = require "hp/display/Resizable" | |
-- class | |
local M = class(DisplayObject, Resizable) | |
-- constraints | |
M.ADJUST_OFFSET = 0.01 | |
M.DEFAULT_STEPS = 32 | |
-------------------------------------------------------------------------------- | |
-- private. <br> | |
-- Outputs the vertex data is specified. | |
-------------------------------------------------------------------------------- | |
local function writeBuffers(verts, ...) | |
for i, v in ipairs({...}) do | |
table.insert(verts, v) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- private. <br> | |
-- To create a line in the corner. | |
-------------------------------------------------------------------------------- | |
local function writeCornerLines(verts, cx, cy, rw, rh, angle0, angle1, steps) | |
local step = (angle1 - angle0) / steps | |
for angle = angle0, angle1, step do | |
local radian = angle / 180 * math.pi | |
local x, y = math.cos(radian) * rw + cx, -math.sin(radian) * rh + cy | |
writeBuffers(verts, x, y) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- private. <br> | |
-- Create the vertex data to draw a rectangle with rounded corners. | |
-------------------------------------------------------------------------------- | |
local function createRoundRectDrawData(x0, y0, x1, y1, rw, rh, steps) | |
local offset = M.ADJUST_OFFSET | |
if rw == 0 or rh == 0 then | |
return {x0 + offset, y0 + offset, x0 + offset, y1, x1, y1, x1, y0 + offset, x0, y0} | |
end | |
local vertexs = {} | |
-- x0, y0 | |
writeBuffers(vertexs, x0 + offset, y0 + rh) | |
writeBuffers(vertexs, x0 + offset, y1 - rh) | |
writeCornerLines(vertexs, x0 + rw + offset, y1 - rh, rw, rh, 180, 270, steps) | |
-- x0, y1 | |
writeBuffers(vertexs, x0 + rw, y1) | |
writeBuffers(vertexs, x1 - rw, y1) | |
writeCornerLines(vertexs, x1 - rw, y1 - rh, rw, rh, 270, 360, steps) | |
-- x1, y1 | |
writeBuffers(vertexs, x1, y1 - rh) | |
writeBuffers(vertexs, x1, y0 + rh) | |
writeCornerLines(vertexs, x1 - rw, y0 + rh + offset, rw, rh, 0, 90, steps) | |
-- x1, y0 | |
writeBuffers(vertexs, x1 - rw, y0 + offset) | |
writeBuffers(vertexs, x0 + rw, y0 + offset) | |
writeCornerLines(vertexs, x0 + rw + offset, y0 + rh + offset, rw, rh, 90, 180, steps) | |
return vertexs | |
end | |
-------------------------------------------------------------------------------- | |
-- private. <br> | |
-- Create the vertex data to fill the corners. | |
-------------------------------------------------------------------------------- | |
local function createCornerFans(cx, cy, rw, rh, angle0, angle1, steps) | |
local verts = {} | |
local step = (angle1 - angle0) / steps | |
writeBuffers(verts, cx, cy) | |
for angle = angle0, angle1, step do | |
local radian = angle / 180 * math.pi | |
local x, y = math.cos(radian) * rw + cx, -math.sin(radian) * rh + cy | |
writeBuffers(verts, x, y) | |
end | |
return verts | |
end | |
-------------------------------------------------------------------------------- | |
-- private. <br> | |
-- Create the vertex data to fill a rectangle with rounded corners. | |
-------------------------------------------------------------------------------- | |
local function createRoundRectFillData(x0, y0, x1, y1, rw, rh, steps) | |
if rw == 0 or rh == 0 then | |
return {{x0, y0, x1, y0, x1, y1, x0, y1}} | |
end | |
local fans = {} | |
-- rects | |
writeBuffers(fans, {x0 + rw, y0, x1 - rw, y0, x1 - rw, y1, x0 + rw, y1}) | |
writeBuffers(fans, {x0, y0 + rh, x0 + rw, y0 + rh, x0 + rw, y1 - rh, x0, y1 - rh}) | |
writeBuffers(fans, {x1 - rw, y0 + rh, x1, y0 + rh, x1, y1 - rh, x1 - rw, y1 - rh}) | |
-- fans | |
writeBuffers(fans, createCornerFans(x0 + rw, y0 + rh, rw, rh, 90, 180, steps)) | |
writeBuffers(fans, createCornerFans(x1 - rw, y0 + rh, rw, rh, 0, 90, steps)) | |
writeBuffers(fans, createCornerFans(x1 - rw, y1 - rh, rw, rh, 270, 360, steps)) | |
writeBuffers(fans, createCornerFans(x0 + rw, y1 - rh, rw, rh, 180, 270, steps)) | |
return fans | |
end | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-- @param params (option)Parameter is set to Object.<br> | |
-- (params:width, height) | |
-------------------------------------------------------------------------------- | |
function M:init(params) | |
DisplayObject.init(self) | |
params = params or {} | |
local deck = MOAIScriptDeck.new() | |
self:setDeck(deck) | |
self.deck = deck | |
self.commands = {} | |
deck:setDrawCallback( | |
function(index, xOff, yOff, xFlip, yFlip) | |
if #self.commands == 0 then | |
return | |
end | |
MOAIGfxDevice.setPenColor(self:getRed(), self:getGreen(), self:getBlue(), self:getAlpha()) | |
MOAIGfxDevice.setPenWidth(1) | |
MOAIGfxDevice.setPointSize(1) | |
for i, gfx in ipairs(self.commands) do | |
gfx(self) | |
end | |
end | |
) | |
self:copyParams(params) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the height and width.<br> | |
-- @param width width | |
-- @param height height | |
-------------------------------------------------------------------------------- | |
function M:setSize(width, height) | |
width = width or self:getWidth() | |
height = height or self:getHeight() | |
local left, top = self:getPos() | |
self.deck:setRect(0, 0, width, height) | |
self:setPiv(width / 2, height / 2, 0) | |
self:setPos(left, top) | |
end | |
-------------------------------------------------------------------------------- | |
-- Draw a circle.<br> | |
-- @param x Position of the left. | |
-- @param y Position of the top. | |
-- @param r Radius.(Not in diameter.) | |
-- @param steps Number of points. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:drawCircle(x, y, r, steps) | |
steps = steps or M.DEFAULT_STEPS | |
local command = function(self) | |
if x and y and r and steps then | |
MOAIDraw.drawCircle(x + r, y + r, r, steps) | |
else | |
local rw = math.min(self:getWidth(), self:getHeight()) / 2 | |
MOAIDraw.drawCircle(rw, rw, rw, 360) | |
end | |
end | |
table.insert(self.commands, command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Draw an ellipse.<br> | |
-- @param x Position of the left. | |
-- @param y Position of the top. | |
-- @param xRad Radius.(Not in diameter.) | |
-- @param yRad Radius.(Not in diameter.) | |
-- @param steps Number of points. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:drawEllipse(x, y, xRad, yRad, steps) | |
steps = steps or M.DEFAULT_STEPS | |
local command = function(self) | |
if x and y and xRad and yRad and steps then | |
MOAIDraw.drawEllipse(x + xRad, y + yRad, xRad, yRad, steps) | |
else | |
local rw, rh = self:getWidth() / 2, self:getHeight() / 2 | |
MOAIDraw.drawEllipse(rw, rh, rw, rh, steps) | |
end | |
end | |
table.insert(self.commands, command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Draws a line.<br> | |
-- @param ... Position of the points(x0, y0). | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:drawLine(...) | |
local args = {...} | |
local command = function(self) | |
MOAIDraw.drawLine(unpack(args)) | |
end | |
table.insert(self.commands, command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Draws a point. | |
-- @param ... Position of the points(x0, y0). | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:drawPoints(...) | |
local args = {...} | |
local command = function(self) | |
MOAIDraw.drawPoints(unpack(args)) | |
end | |
table.insert(self.commands, command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Draw a ray. | |
-- @param x Position of the left. | |
-- @param y Position of the top. | |
-- @param dx Direction. | |
-- @param dy Direction. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:drawRay(x, y, dx, dy) | |
local command = function(self) | |
if x and y and dx and dy then | |
MOAIDraw.drawRay(x, y, dx, dy) | |
else | |
MOAIDraw.drawRay(0, 0, self:getWidth(), self:getHeight()) | |
end | |
end | |
table.insert(self.commands, command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Draw a rectangle. | |
-- @param x0 Position of the left. | |
-- @param y0 Position of the top. | |
-- @param x1 Position of the right. | |
-- @param y1 Position of the bottom | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:drawRect(x0, y0, x1, y1) | |
local command = function(self) | |
if x0 and y0 and x1 and y1 then | |
MOAIDraw.drawRect(x0, y0, x1, y1) | |
else | |
MOAIDraw.drawRect(0, 0, self:getWidth(), self:getHeight()) | |
end | |
end | |
table.insert(self.commands, command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Draw a round rectangle. | |
-- @param x0 Position of the left. | |
-- @param y0 Position of the top. | |
-- @param x1 Position of the right. | |
-- @param y1 Position of the bottom. | |
-- @param rw The width of the Corner. | |
-- @param rh The height of the Corner. | |
-- @param steps Number of points. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:drawRoundRect(x0, y0, x1, y1, rw, rh, steps) | |
rw = rw or 0 | |
rh = rh or 0 | |
steps = steps or M.DEFAULT_STEPS / 4 | |
local vertexs = createRoundRectDrawData(x0, y0, x1, y1, rw, rh, steps) | |
local command = function(self) | |
MOAIDraw.drawLine(vertexs) | |
end | |
table.insert(self.commands, command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Fill the circle. | |
-- @param x Position of the left. | |
-- @param y Position of the top. | |
-- @param r Radius.(Not in diameter.) | |
-- @param steps Number of points. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:fillCircle(x, y, r, steps) | |
steps = steps or M.DEFAULT_STEPS | |
local command = function(self) | |
if x and y and r and steps then | |
MOAIDraw.fillCircle(x + r, y + r, r, steps) | |
else | |
local r = math.min(self:getWidth(), self:getHeight()) / 2 | |
MOAIDraw.fillCircle(r, r, r, steps) | |
end | |
end | |
table.insert(self.commands, command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Fill an ellipse. | |
-- @param x Position of the left. | |
-- @param y Position of the top. | |
-- @param xRad Radius.(Not in diameter.) | |
-- @param yRad Radius.(Not in diameter.) | |
-- @param steps Number of points. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:fillEllipse(x, y, xRad, yRad, steps) | |
steps = steps or M.DEFAULT_STEPS | |
local command = function(self) | |
if x and y and xRad and yRad then | |
MOAIDraw.fillEllipse(x + xRad, y + yRad, xRad, yRad, steps) | |
else | |
local rw, rh = self:getWidth() / 2, self:getHeight() / 2 | |
MOAIDraw.fillEllipse(rw, rh, rw, rh, steps) | |
end | |
end | |
table.insert(self.commands, command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Fills the triangle. | |
-- @param ... Position of the points(x0, y0). | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:fillFan(...) | |
local args = {...} | |
local command = function(self) | |
MOAIDraw.fillFan(unpack(args)) | |
end | |
table.insert(self.commands, command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Fill a rectangle. | |
-- @param x0 Position of the left. | |
-- @param y0 Position of the top. | |
-- @param x1 Position of the right. | |
-- @param y1 Position of the bottom. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:fillRect(x0, y0, x1, y1) | |
local command = function(self) | |
if x0 and y0 and x1 and y1 then | |
MOAIDraw.fillRect(x0, y0, x1, y1) | |
else | |
MOAIDraw.fillRect(0, 0, self:getWidth(), self:getHeight()) | |
end | |
end | |
table.insert(self.commands, command) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Fill a round rectangle. | |
-- @param x0 Position of the left. | |
-- @param y0 Position of the top. | |
-- @param x1 Position of the right. | |
-- @param y1 Position of the bottom. | |
-- @param rw The width of the Corner. | |
-- @param rh The height of the Corner. | |
-- @param steps Number of points. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:fillRoundRect(x0, y0, x1, y1, rw, rh, steps) | |
rw = rw or 0 | |
rh = rh or 0 | |
steps = steps or M.DEFAULT_STEPS / 4 | |
local fillDatas = createRoundRectFillData(x0, y0, x1, y1, rw, rh, steps) | |
local command = function(self) | |
for i, verts in ipairs(fillDatas) do | |
MOAIDraw.fillFan(verts) | |
end | |
end | |
table.insert(self.commands, command) | |
return self | |
end | |
--------------------------------------- | |
-- Sets the color of the pen.<br> | |
-- Will be reflected in the drawing functions. | |
-- @param r red | |
-- @param g green | |
-- @param b blue | |
-- @param a alpha | |
-- @return self | |
--------------------------------------- | |
function M:setPenColor(r, g, b, a) | |
a = a or 1 | |
local command = function(self) | |
local red = r * self:getRed() | |
local green = g * self:getGreen() | |
local blue = b * self:getBlue() | |
local alpha = a * self:getAlpha() | |
MOAIGfxDevice.setPenColor(red, green, blue, alpha) | |
end | |
table.insert(self.commands, command) | |
return self | |
end | |
--------------------------------------- | |
-- Set the size of the pen that you specify.<br> | |
-- Will be reflected in the drawing functions. | |
-- @param width width | |
-- @return self | |
--------------------------------------- | |
function M:setPenWidth(width) | |
local command = function(self) | |
MOAIGfxDevice.setPenWidth(width) | |
end | |
table.insert(self.commands, command) | |
return self | |
end | |
--------------------------------------- | |
-- Set the size of the specified point.<br> | |
-- Will be reflected in the drawing functions. | |
-- @param size | |
-- @return self | |
--------------------------------------- | |
function M:setPointSize(size) | |
local command = function(self) | |
MOAIGfxDevice.setPointSize(size) | |
end | |
table.insert(self.commands, command) | |
return self | |
end | |
--------------------------------------- | |
-- Clears the drawing operations. | |
-- @return self | |
--------------------------------------- | |
function M:clear() | |
self.commands = {} | |
return self | |
end | |
return M end) | |
package.preload['hp/display/Group'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This is a class to grouping the DisplayObject. <br> | |
-- Will be used as a dummy MOAIProp. <br> | |
-- Base Classes => DisplayObject, Resizable <br> | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local DisplayObject = require "hp/display/DisplayObject" | |
local Resizable = require "hp/display/Resizable" | |
-- class | |
local super = DisplayObject | |
local M = class(DisplayObject, Resizable) | |
local MOAIPropInterface = MOAIProp.getInterfaceTable() | |
---------------------------------------------------------------- | |
-- The constructor. | |
-- @param params (option)Parameter is set to Object.<br> | |
---------------------------------------------------------------- | |
function M:init(params) | |
super.init(self) | |
params = params or {} | |
self.children = {} | |
self._width = 0 | |
self._height = 0 | |
self:copyParams(params) | |
end | |
---------------------------------------------------------------- | |
-- Returns the bounds of the object. | |
-- @return xMin, yMin, zMin, xMax, yMax, zMax | |
---------------------------------------------------------------- | |
function M:getBounds() | |
local xMin, yMin, zMin = 0, 0, 0 | |
local xMax, yMax, zMax = self:getWidth(), self:getHeight(), 0 | |
return xMin, yMin, zMin, xMax, yMax, zMax | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the width. | |
-- @return width | |
-------------------------------------------------------------------------------- | |
function M:getWidth() | |
return self._width | |
end | |
---------------------------------------------------------------- | |
-- Returns the height. | |
-- @return height | |
---------------------------------------------------------------- | |
function M:getHeight() | |
return self._height | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the width and height. | |
-- @param width width | |
-- @param height height | |
-------------------------------------------------------------------------------- | |
function M:setSize(width, height) | |
self._width = width | |
self._height = height | |
end | |
---------------------------------------------------------------- | |
-- Set the visible. | |
-- @param visible visible | |
---------------------------------------------------------------- | |
function M:setVisible(visible) | |
MOAIPropInterface.setVisible(self, visible) | |
for i, v in ipairs(self:getChildren()) do | |
if v.setVisible then | |
v:setVisible(visible) | |
end | |
end | |
end | |
---------------------------------------------------------------- | |
-- Set the center of the pivot. | |
---------------------------------------------------------------- | |
function M:setCenterPiv() | |
local left, top = self:getPos() | |
local pivX = self:getWidth() / 2 | |
local pivY = self:getHeight() / 2 | |
self:setPiv(pivX, pivY, 0) | |
self:setPos(left, top) | |
end | |
---------------------------------------------------------------- | |
-- Resize based on the location and size of the child elements. | |
---------------------------------------------------------------- | |
function M:resizeForChildren() | |
local maxWidth, maxHeight = 0, 0 | |
for i, child in ipairs(self:getChildren()) do | |
maxWidth = math.max(maxWidth, child:getRight()) | |
maxHeight = math.max(maxHeight, child:getBottom()) | |
end | |
self:setSize(maxWidth, maxHeight) | |
end | |
---------------------------------------------------------------- | |
-- Returns the children object. | |
-- If you want to use this function with caution.<br> | |
-- direct manipulation table against children are not reflected in the Group.<br> | |
-- @return children | |
---------------------------------------------------------------- | |
function M:getChildren() | |
return self.children | |
end | |
---------------------------------------------------------------- | |
-- Returns the children size. | |
-- @return children size. | |
---------------------------------------------------------------- | |
function M:getNumChildren() | |
return #self.children | |
end | |
---------------------------------------------------------------- | |
-- Returns the child object. | |
-- @param i Index. | |
-- @return child | |
---------------------------------------------------------------- | |
function M:getChildAt(i) | |
return self.children[i] | |
end | |
---------------------------------------------------------------- | |
-- Sets the children. | |
-- @param children children | |
---------------------------------------------------------------- | |
function M:setChildren(children) | |
self:removeChildren() | |
self:addChildren(children) | |
end | |
---------------------------------------------------------------- | |
-- Returns the child object by name. | |
-- @param name child.name. | |
-- @return child | |
---------------------------------------------------------------- | |
function M:getChildByName(name) | |
for i, child in ipairs(self:getChildren()) do | |
if child.name == name then | |
return child | |
end | |
if child.getChildByName then | |
local nestedChild = child:getChildByName(name) | |
if nestedChild then | |
return nestedChild | |
end | |
end | |
end | |
end | |
---------------------------------------------------------------- | |
-- Add a child object. <br> | |
-- The child object to duplicate is not added. <br> | |
-- If you have set the Layer to the group, the layer is set to the child. | |
-- @param child Child to inherit the MOAIProp. | |
---------------------------------------------------------------- | |
function M:addChild(child) | |
local index = table.indexOf(self.children, child) | |
if index > 0 then | |
return false | |
end | |
table.insert(self.children, child) | |
child:setParent(self) | |
if self.layer then | |
if child.setLayer then | |
child:setLayer(self.layer) | |
end | |
end | |
return true | |
end | |
---------------------------------------------------------------- | |
-- Add a child object. <br> | |
-- The child object to duplicate is not added. <br> | |
-- If you have set the Layer to the group, the layer is set to the child. | |
-- @param children to inherit the MOAIProp table. | |
---------------------------------------------------------------- | |
function M:addChildren(children) | |
for i, child in ipairs(children) do | |
self:addChild(child) | |
end | |
end | |
---------------------------------------------------------------- | |
-- Remove the child object. <br> | |
-- If you have set the Layer to the group, layer of the child is removed. | |
-- @param child Child to inherit the MOAIProp. | |
---------------------------------------------------------------- | |
function M:removeChild(child) | |
local children = self.children | |
local index = table.indexOf(children, child) | |
if index <= 0 then | |
return | |
end | |
table.remove(children, index) | |
child:setParent(nil) | |
if self.layer then | |
if child.setLayer then | |
child:setLayer(nil) | |
end | |
end | |
end | |
---------------------------------------------------------------- | |
-- Remove the child object. <br> | |
-- If you have set the Layer to the group, layer of the child is removed. | |
-- @param i Children index. | |
---------------------------------------------------------------- | |
function M:removeChildAt(i) | |
local child = self.children[i] | |
if child then | |
self:removeChild(child) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Remove the children object. | |
-------------------------------------------------------------------------------- | |
function M:removeChildren() | |
local children = table.copy(self:getChildren()) | |
for i, child in ipairs(children) do | |
self:removeChild(child) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the layer of the same for children. | |
-- @param layer MOAILayer instance. | |
-------------------------------------------------------------------------------- | |
function M:setLayer(layer) | |
self.layer = layer | |
for i, child in ipairs(self:getChildren()) do | |
if child.setLayer then | |
child:setLayer(layer) | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the layer. | |
-- @return MOAILayer instance. | |
-------------------------------------------------------------------------------- | |
function M:getLayer() | |
return self.layer | |
end | |
-------------------------------------------------------------------------------- | |
-- Dispose resources. | |
-------------------------------------------------------------------------------- | |
function M:dispose() | |
super.dispose(self) | |
for i, child in ipairs(self:getChildren()) do | |
if child.dispose then | |
child:dispose() | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns true if the group.<br> | |
-- Are used in internal decision. | |
-------------------------------------------------------------------------------- | |
function M:isGroup() | |
return true | |
end | |
-------------------------------------------------------------------------------- | |
-- If the object will collide with the screen, it returns true.<br> | |
-- @param screenX x of screen | |
-- @param screenY y of screen | |
-- @param screenZ (option)z of screen | |
-- @return If the object is a true conflict | |
-------------------------------------------------------------------------------- | |
function M:hitTestScreen(screenX, screenY, screenZ) | |
assert(self.layer) | |
screenZ = screenZ or 0 | |
for i, child in ipairs(self:getChildren()) do | |
if child.hitTestScreen then | |
if child:hitTestScreen(screenX, screenY, screenZ) then | |
return true | |
end | |
else | |
local worldX, worldY, worldZ = self.layer:wndToWorld(screenX, screenY, screenZ) | |
if child:inside(worldX, worldY, worldZ) then | |
return true | |
end | |
end | |
end | |
return false | |
end | |
-------------------------------------------------------------------------------- | |
-- If the object will collide with the world, it returns true.<br> | |
-- @param worldX world x of layer | |
-- @param worldY world y of layer | |
-- @param worldZ (option)world z of layer | |
-- @return If the object is a true conflict | |
-------------------------------------------------------------------------------- | |
function M:hitTestWorld(worldX, worldY, worldZ) | |
worldZ = worldZ or 0 | |
for i, child in ipairs(self:getChildren()) do | |
if child.hitTestWorld then | |
if child:hitTestWorld(worldX, worldY, worldZ) then | |
return true | |
end | |
else | |
if child:inside(worldX, worldY, worldZ) then | |
return true | |
end | |
end | |
end | |
return false | |
end | |
return M end) | |
package.preload['hp/display/Layer'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This class inherits the MOAILayer. <br> | |
-- Simplifies the generation of a set of size and layer. <br> | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local Application = require "hp/core/Application" | |
local DisplayObject = require "hp/display/DisplayObject" | |
local Resizable = require "hp/display/Resizable" | |
local TouchProcessor = require "hp/display/TouchProcessor" | |
-- class define | |
local M = class(DisplayObject, Resizable) | |
local MOAILayerInterface = MOAILayer.getInterfaceTable() | |
M.MOAI_CLASS = MOAILayer | |
---------------------------------------------------------------- | |
-- The constructor. | |
-- @param params (option)Parameter is set to Object.<br> | |
---------------------------------------------------------------- | |
function M:init(params) | |
DisplayObject.init(self) | |
self:setTouchEnabled(false) | |
params = params or {} | |
local partition = MOAIPartition.new() | |
self:setPartition(partition) | |
self.partition = partition | |
local viewport = MOAIViewport.new() | |
self:setViewport(viewport) | |
self.viewport = viewport | |
self:setScreenSize(Application.screenWidth, Application.screenHeight) | |
self:setViewSize(Application.viewWidth, Application.viewHeight) | |
self:setOffset(-1, 1) | |
self:copyParams(params) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the size of the layer. | |
-- @param width width of layer. | |
-- @param height height of layer. | |
-------------------------------------------------------------------------------- | |
function M:setSize(width, height) | |
self:setScreenSize(width, height) | |
self:setViewSize(width, height) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the size of the layer on the screen. | |
-- @return Width of screen. | |
-------------------------------------------------------------------------------- | |
function M:getScreenWidth() | |
return self.screenWidth | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the size of the layer on the screen. | |
-- @param width Width of screen. | |
-------------------------------------------------------------------------------- | |
function M:setScreenWidth(width) | |
self:setScreenSize(width, self:getScreenHeight()) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the size of the layer on the screen. | |
-- @return Height of screen. | |
-------------------------------------------------------------------------------- | |
function M:getScreenHeight() | |
return self.screenHeight | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the size of the layer on the screen. | |
-- @param height Height of screen. | |
-------------------------------------------------------------------------------- | |
function M:setScreenHeight(height) | |
self:setScreenSize(self:getScreenHeight(), height) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the size of the layer on the screen. | |
-- @return width | |
-- @return height | |
-------------------------------------------------------------------------------- | |
function M:getScreenSize() | |
return self:getScreenWidth(), self:getScreenHeight() | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the size of the layer on the screen. | |
-- @param width Width of the screen. | |
-- @param height Height of the screen. | |
-------------------------------------------------------------------------------- | |
function M:setScreenSize(width, height) | |
self.screenWidth = width | |
self.screenHeight = height | |
if self.screenWidth and self.screenHeight then | |
self.viewport:setSize(width, height) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the viewport size of the layer. | |
-- @return viewWidth. | |
-------------------------------------------------------------------------------- | |
function M:getViewWidth() | |
return self.viewWidth | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the viewport size of the layer. | |
-- @param width Width of viewport. | |
-------------------------------------------------------------------------------- | |
function M:setViewWidth(width) | |
self:setViewSize(width, self:getViewHeight()) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the viewport size of the layer. | |
-- @return viewHeight. | |
-------------------------------------------------------------------------------- | |
function M:getViewHeight() | |
return self.viewHeight | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the viewport size of the layer. | |
-- @param height height of viewport | |
-------------------------------------------------------------------------------- | |
function M:setViewHeight(height) | |
self:setViewSize(self:getViewWidth(), height) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the viewport size of the layer. | |
-- @return viewWidth | |
-- @return viewHeight | |
-------------------------------------------------------------------------------- | |
function M:getViewSize() | |
return self:getViewWidth(), self:getViewHeight() | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the viewport size of the layer. | |
-- @param width Width of the viewport. | |
-- @param height Height of the viewport. | |
-------------------------------------------------------------------------------- | |
function M:setViewSize(width, height) | |
self.viewWidth = width | |
self.viewHeight = height | |
if self.viewWidth and self.viewHeight then | |
self.viewport:setScale(width, -height) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the offset of the viewport. | |
-- @param offsetX offsetX. | |
-- @param offsetY offsetY. | |
-------------------------------------------------------------------------------- | |
function M:setOffset(offsetX, offsetY) | |
self.offsetX = offsetX | |
self.offsetY = offsetY | |
self.viewport:setOffset(offsetX, offsetY) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the scale of the screen and viewport. | |
-- @return scale | |
-------------------------------------------------------------------------------- | |
function M:getViewScale() | |
return self.screenWidth / self.viewWidth | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns self. | |
-- @return self | |
-------------------------------------------------------------------------------- | |
function M:getLayer() | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the scene.<br> | |
-- By setting the scene, and then draw in the scene. | |
-- @param scene scene. | |
-------------------------------------------------------------------------------- | |
function M:setScene(scene) | |
if self.scene == scene then | |
return | |
end | |
if self.scene then | |
self.scene:removeChild(self) | |
end | |
self.scene = scene | |
if self.scene then | |
self.scene:addChild(self) | |
end | |
if self._touchProcessor then | |
self._touchProcessor:setEventSource(scene) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the scene. | |
-------------------------------------------------------------------------------- | |
function M:getScene() | |
return self.scene | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the props<br> | |
-- @param props props | |
-------------------------------------------------------------------------------- | |
function M:setProps(props) | |
self:clear() | |
for i, prop in ipairs(props) do | |
if prop.setLayer then | |
prop:setLayer(self) | |
else | |
self:insertProp(prop) | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the touch enabled. | |
-- @param value touch enabled. | |
-------------------------------------------------------------------------------- | |
function M:setTouchEnabled(value) | |
if self._touchEnabled == value then | |
return | |
end | |
self._touchEnabled = value | |
if value and not self._touchProcessor then | |
self._touchProcessor = TouchProcessor(self) | |
self._touchProcessor:setEventSource(self:getScene()) | |
end | |
if self._touchProcessor then | |
self._touchProcessor:setEnabled(value) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the TouchProcessor object. | |
-------------------------------------------------------------------------------- | |
function M:setTouchProcessor(value) | |
if self._touchProcessor then | |
self._touchProcessor:dispose(nil) | |
self._touchProcessor = nil | |
end | |
self._touchProcessor = value | |
end | |
-------------------------------------------------------------------------------- | |
-- Dispose resourece. | |
-------------------------------------------------------------------------------- | |
function M:dispose() | |
self:setScene(nil) | |
self:clear() | |
if self._touchProcessor then | |
self._touchProcessor:dispose() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Create and sets camera. | |
-- @param ortho ortho | |
-- @param near near | |
-- @param far far | |
-------------------------------------------------------------------------------- | |
function M:createCamera(ortho, near, far) | |
ortho = ortho ~= nil and ortho or true | |
near = near or 1 | |
far = far or -1 | |
local camera = MOAICamera.new() | |
camera:setOrtho(ortho) | |
camera:setNearPlane(near) | |
camera:setFarPlane(far) | |
self:setCamera(camera) | |
self.camera = camera | |
return camera | |
end | |
return M end) | |
package.preload['hp/display/MapSprite'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This class draws the grid. <br> | |
-- Without the use of MOAITileDeck, use the MOAIGfxQuadDeck2D. <br> | |
-- Corresponding to the format can be flexibility. <br> | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local DisplayObject = require "hp/display/DisplayObject" | |
local TextureDrawable = require "hp/display/TextureDrawable" | |
-- class | |
local M = class(DisplayObject, TextureDrawable) | |
---------------------------------------------------------------- | |
-- The constructor. | |
-- @param params (option)Parameter is set to Object.<br> | |
---------------------------------------------------------------- | |
function M:init(params) | |
DisplayObject.init(self) | |
params = params or {} | |
params = type(params) == "string" and {texture = params} or params | |
local deck = MOAIGfxQuadDeck2D.new() | |
local grid = MOAIGrid.new () | |
self:setDeck(deck) | |
self:setGrid(grid) | |
self.deck = deck | |
self.grid = grid | |
self:copyParams(params) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the data to generate a sheet of tile form. | |
-- @param tileWidth Width of the tile. | |
-- @param tileHeight Height of the tile. | |
-- @param tileX number of tiles in the x-direction. | |
-- @param tileY number of tiles in the y-direction. | |
-- @param spacing (option)Space size of each tile. | |
-- @param margin (option)Margin of tile. | |
-------------------------------------------------------------------------------- | |
function M:setMapSheets(tileWidth, tileHeight, tileX, tileY, spacing, margin) | |
spacing = spacing or 0 | |
margin = margin or 0 | |
local sheets = {} | |
for y = 1, tileY do | |
for x = 1, tileX do | |
local sx = (x - 1) * (tileWidth + spacing) + margin | |
local sy = (y - 1) * (tileHeight + spacing) + margin | |
table.insert(sheets, {x = sx, y = sy, width = tileWidth, height = tileHeight}) | |
end | |
end | |
self:setSheets(sheets) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the data sheet. | |
-- @param sheets Data sheet. | |
-------------------------------------------------------------------------------- | |
function M:setSheets(sheets) | |
assert(self.texture) | |
local tw, th = self.texture:getSize() | |
self.deck:reserve(#sheets) | |
for i, sheet in ipairs(sheets) do | |
local xMin, yMin = sheet.x, sheet.y | |
local xMax = sheet.x + sheet.width | |
local yMax = sheet.y + sheet.height | |
self.deck:setUVRect(i, xMin / tw, yMin / th, xMax / tw, yMax / th) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the map size. | |
-- @param mapWidth Height of the map. | |
-- @param mapHeight Height of the map. | |
-- @param tileWidth Width of the tile. | |
-- @param tileHeight Height of the tile. | |
-------------------------------------------------------------------------------- | |
function M:setMapSize(mapWidth, mapHeight, tileWidth, tileHeight) | |
self.grid:setSize(mapWidth, mapHeight, tileWidth, tileHeight) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the map data. | |
-- @param rows Multiple rows of data. | |
-------------------------------------------------------------------------------- | |
function M:setRows(rows) | |
for i, row in ipairs(rows) do | |
self:setRow(i, table.unpack(row)) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the map data. | |
-- @param ... rows of data. | |
-------------------------------------------------------------------------------- | |
function M:setRow(...) | |
self.grid:setRow(...) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the map value. | |
-- @param x x. | |
-- @param y y. | |
-- @param value value. | |
-------------------------------------------------------------------------------- | |
function M:setTile(x, y, value) | |
self.grid:setTile(x, y, value) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the repeat flag. | |
-- @param repeatX | |
-- @param repeatY | |
-------------------------------------------------------------------------------- | |
function M:setRepeat(repeatX, repeatY) | |
self.grid:setRepeat(repeatX, repeatY) | |
end | |
return M end) | |
package.preload['hp/display/Mesh'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This is a class to draw a gradient mesh. <br> | |
-- This source has been implemented by Nenad Katic. <br> | |
-- Has been partially modified. <br> | |
-------------------------------------------------------------------------------- | |
local table = require("hp/lang/table") | |
local class = require("hp/lang/class") | |
local string = require("hp/lang/string") | |
local DisplayObject = require("hp/display/DisplayObject") | |
local ShaderManager = require("hp/manager/ShaderManager") | |
local Triangulation = require("hp/util/Triangulation") | |
local M = class(DisplayObject) | |
local DEFAULT_COLOR = "#FF00FF" | |
-------------------------------------------------------------------------------- | |
-- Creates and returns a mesh. | |
-------------------------------------------------------------------------------- | |
local function createMesh( vcoords, colors, primType ) | |
primType = primType or MOAIMesh.GL_TRIANGLE_FAN | |
if vcoords and colors then | |
local numVertices = #vcoords | |
local vertexFormat = MOAIVertexFormat.new () | |
vertexFormat:declareCoord ( 1, MOAIVertexFormat.GL_FLOAT, 2 ) | |
-- Commented line below because we're not going to use UV coordinates | |
-- vertexFormat:declareUV ( 2, MOAIVertexFormat.GL_FLOAT, 2 ) | |
vertexFormat:declareColor ( 2, MOAIVertexFormat.GL_UNSIGNED_BYTE ) | |
local vbo = MOAIVertexBuffer.new () | |
vbo:setFormat ( vertexFormat ) | |
vbo:reserveVerts ( #vcoords ) | |
for i=1, numVertices do | |
vbo:writeFloat ( vcoords[i][1], vcoords[i][2] ) -- write vertex position | |
vbo:writeColor32 ( colors[i][1], colors[i][2], colors[i][3] ) -- write RGB value | |
end | |
vbo:bless () | |
local mesh = MOAIMesh.new () | |
mesh:setVertexBuffer ( vbo ) | |
mesh:setPrimType ( primType ) | |
return mesh | |
end | |
return nil | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the color to calculate the gradient. | |
-------------------------------------------------------------------------------- | |
local function calculateGradient( color1, color2, angle, gradAngle ) | |
local perc =.5 * ( 1 + math.cos( math.rad( angle-gradAngle) ) ) | |
local color = {} | |
for i=1,3 do | |
color[i] = color1[i] + perc * ( color2[i] - color1[i] ) | |
end | |
return color | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the color to calculate the gradient. | |
-------------------------------------------------------------------------------- | |
local function calculateDetailedGradient( points, angle, col1, col2 ) | |
local colors = {} | |
local projectedX = {} | |
local ang = math.rad ( angle ) | |
local s = math.sin ( ang ) | |
local c = math.cos ( ang ) | |
local x, y | |
local minX = 0 | |
local maxX = 0 | |
local projX, xprim | |
for i=1, #points do | |
x = points[i][1] | |
y = points[i][2] | |
xprim = ( math.abs( c ) > 0.001 ) and ( x/c ) or 0 | |
-- a little of trigonometry gymnastics | |
projX = xprim + s * ( y - s * xprim ) | |
projectedX[ #projectedX+1 ] = projX | |
if projX < minX then | |
minX = projX | |
elseif projX > maxX then | |
maxX = projX | |
end | |
end | |
-- now calculate percents | |
local perc, color | |
local dX = maxX - minX | |
for i=1, #projectedX do | |
perc = ( projectedX[i] - minX ) / dX | |
color = {} | |
for i=1,3 do | |
color[i] = col1[i] + perc * ( col2[i] - col1[i] ) | |
end | |
colors[#colors+1] = color | |
end | |
return colors | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns an array of colors. | |
-------------------------------------------------------------------------------- | |
local function isColorOrGradient( col ) | |
-- if no argument, just use default color | |
col = col or { DEFAULT_COLOR } | |
-- if a string has been forwaded, convert to table for later use | |
if type(col) == "string" then | |
col = { string.hexToRGB( col, true ) } | |
else | |
col ={ string.hexToRGB( col[1], true ), string.hexToRGB( col[2], true ) , col[3] } | |
end | |
return col | |
end | |
-------------------------------------------------------------------------------- | |
-- Creates and returns a gradient array.<br> | |
-- Example: ( "#003300", "#CCFF00", 90 ) | |
-- @param col1 fromColor. | |
-- @param col2 toColor. | |
-- @param angle gradientAngle. | |
-- @return gradient array | |
-------------------------------------------------------------------------------- | |
function M.newGradient( col1, col2, angle ) | |
angle = angle or 90 | |
return { col1, col2, angle } | |
end | |
-------------------------------------------------------------------------------- | |
-- Creates and returns a mesh of the rectangle.<br> | |
-- Mesh is the class that inherits from the DisplayObject. | |
-- @param left Position of the left. | |
-- @param top Position of the top. | |
-- @param width width. | |
-- @param height height. | |
-- @param col Color of the gradient. | |
-- @return Rectangle object | |
-------------------------------------------------------------------------------- | |
function M.newRect( left, top, width, height, col ) | |
-- Check what's sent for colors argument | |
local colors | |
-- Should we paint every vertice in its own color ? | |
-- To do this, we use a table of 4 elements, like { "#FF0000", "#FFCC00", "#009900", "#0099CC" } | |
local everyVertice = type(col)=="table" and #col == 4 | |
if everyVertice then | |
colors = {} | |
for i=1, 4 do | |
colors[i] = string.hexToRGB( col[i], true ) -- using extended string table, in lang.lua | |
end | |
else | |
-- nope, so it's going to be either solid color or gradient. | |
colors = isColorOrGradient( col ) | |
end | |
local isGradient = ( #colors == 3 ) | |
------------------------------------------------------------ | |
-- Prepare vertex coordinates and vertex colors for vbo | |
------------------------------------------------------------ | |
local vcoords, colorCoords = {}, {} | |
-- vertex coordinates | |
vcoords[1] = { 0, 0 } | |
vcoords[2] = { width, 0 } | |
vcoords[3] = { width, height } | |
vcoords[4] = { 0, height } | |
-- vertex colors | |
if isGradient then | |
colorCoords = calculateDetailedGradient( vcoords, colors[3], colors[1], colors[2] ) | |
elseif everyVertice then | |
-- just assign vertex colors in the same order we forwarded it to the function | |
for i = 1, 4 do | |
colorCoords[i] = colors[i] | |
end | |
else | |
-- if using solid color, just copy it for every vertex | |
for i = 1, 4 do | |
colorCoords[i] = colors[1] | |
end | |
end | |
local prop = M(vcoords, colorCoords, MOAIMesh.GL_TRIANGLE_FAN) | |
prop:setPos(left, top) | |
return prop | |
end | |
-------------------------------------------------------------------------------- | |
-- Creates and returns a mesh of the circle.<br> | |
-- Mesh is the class that inherits from the DisplayObject. | |
-- @param left Position of the left. | |
-- @param top Position of the top. | |
-- @param r Radius. | |
-- @param col color(s). | |
-- @param seg segments. | |
-- @return Circle object | |
-------------------------------------------------------------------------------- | |
function M.newCircle(left, top, r, col, seg) | |
-- Check if we're skipping col argument | |
if type(col) == "number" then | |
seg = col | |
col = nil | |
end | |
-- So what do we have here? | |
local colors = isColorOrGradient( col ) | |
local isGradient = #colors == 3 | |
-- number of segments | |
if not seg then | |
seg = 12 * math.ceil ( r / 20 ) | |
if seg > 128 then | |
seg = 128 | |
end | |
end | |
-- coordinates | |
local vcoords, colorCoords = {}, {} | |
local vx, vy, angle | |
local angleInc = 360 / seg | |
for i=1, seg do | |
angle = angleInc*(i-1) | |
vy = r * math.sin( math.rad( angle ) ) | |
vx = r * math.cos( math.rad( angle ) ) | |
vcoords[i] = { vx, vy } | |
if not isGradient then | |
colorCoords[i] = colors[1] | |
else | |
--colorCoords[i] = calculateGradient( colors[1], colors[2], angle, colors[3] ) | |
end | |
end | |
if isGradient then | |
colorCoords = calculateDetailedGradient( vcoords, colors[3], colors[1], colors[2] ) | |
end | |
local prop = M(vcoords, colorCoords, MOAIMesh.GL_TRIANGLE_FAN) | |
prop:setPos(left, top) | |
return prop | |
end | |
-------------------------------------------------------------------------------- | |
-- Creates and returns a mesh of the polygon.<br> | |
-- Mesh is the class that inherits from the DisplayObject. | |
-- @param left Position of the left. | |
-- @param top Position of the top. | |
-- @param vertices Vertex array. | |
-- @param col Color gradient. | |
-- @return Polygon object | |
-------------------------------------------------------------------------------- | |
function M.newPolygon( left, top, vertices, col ) | |
-- create gradient if needed | |
local colors = isColorOrGradient( col ) | |
local isGradient = #colors == 3 | |
-- get triangulated points | |
local triangulatedPoints = Triangulation.process( vertices ) --delaunay( vertices ) | |
-- get color coordinates | |
local colorCoords = {} | |
if isGradient then | |
colorCoords = calculateDetailedGradient( triangulatedPoints, colors[3], colors[1], colors[2] ) | |
else | |
for i = 1, #triangulatedPoints do | |
colorCoords[ #colorCoords + 1 ] = colors[1] | |
end | |
end | |
local prop = M(triangulatedPoints, colorCoords, MOAIMesh.GL_TRIANGLES) | |
prop:setPos(left, top) | |
return prop | |
end | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-- @param vcoords vcoords | |
-- @param colors colors | |
-- @param primType primType | |
-------------------------------------------------------------------------------- | |
function M:init(vcoords, colors, primType) | |
DisplayObject.init(self) | |
local mesh = createMesh(vcoords, colors, primType) | |
local shader = ShaderManager:getShader(ShaderManager.BASIC_COLOR_SHADER) | |
self:setDeck(mesh) | |
self:setShader(shader) | |
end | |
return M end) | |
package.preload['hp/display/NinePatch'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- NinePatch class is the scale is partially configured. <br> | |
-- When you set the size, scale will be reconfigured dynamically. <br> | |
-- Will help you build a widget. <br> | |
-- Base Classes => DisplayObject, TextureDrawable, Resizable <br> | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require("hp/lang/table") | |
local class = require("hp/lang/class") | |
local DisplayObject = require("hp/display/DisplayObject") | |
local Resizable = require("hp/display/Resizable") | |
local TextureDrawable = require("hp/display/TextureDrawable") | |
-- class | |
local M = class(DisplayObject, TextureDrawable, Resizable) | |
local MOAIPropInterface = MOAIProp.getInterfaceTable() | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-- @param params (option)Parameter is set to Object.<br> | |
-------------------------------------------------------------------------------- | |
function M:init(params) | |
DisplayObject.init(self) | |
params = params or {} | |
params = type(params) == "string" and {texture = params} or params | |
local deck = MOAIStretchPatch2D.new() | |
self:setDeck(deck) | |
self.deck = deck | |
deck:reserveUVRects(1) | |
deck:setUVRect(1, 0, 0, 1, 1) | |
deck:reserveRows(3) | |
deck:setRow(1, 1 / 3, false) | |
deck:setRow(2, 1 / 3, true) | |
deck:setRow(3, 1 / 3, false) | |
deck:reserveColumns(3) | |
deck:setColumn(1, 1 / 3, false) | |
deck:setColumn(2, 1 / 3, true) | |
deck:setColumn(3, 1 / 3, false) | |
self.setOrignScl = assert(MOAIPropInterface.setScl) | |
self.getOrignScl = assert(MOAIPropInterface.getScl) | |
self.seekOrignScl = assert(MOAIPropInterface.seekScl) | |
self._width = 0 | |
self._height = 0 | |
self._sclX = 1 | |
self._sclY = 1 | |
self._sclZ = 1 | |
self:copyParams(params) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the size.<br> | |
-- When you set the size, set by calculating the scale. | |
-- @param width width. | |
-- @param height height. | |
-------------------------------------------------------------------------------- | |
function M:setSize(width, height) | |
assert(self.texture) | |
local tw, th = self.texture:getSize() | |
local left, top = self:getPos() | |
local sclX, sclY, sclZ = self:getScl() | |
local bSclX, bSclY, bSclZ = width / tw, height / th, 1 -- TODO:sclZ | |
local oSclX, oSclY, oSclZ = sclX * bSclX, sclY * bSclY, sclZ * bSclZ | |
self._width = width | |
self._height = height | |
self.deck:setRect(-tw / 2, -th / 2, tw / 2, th / 2) | |
self:setOrignScl(oSclX, oSclY, oSclZ) | |
self:setPos(left, top) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the virtual scale.<br> | |
-- Value to be set will vary.<br> | |
-- TODO:Can not cope with if you want to move dynamically. | |
-- @param x scaleX. | |
-- @param y scaleY. | |
-- @param z scaleZ. | |
-------------------------------------------------------------------------------- | |
function M:setScl(x, y, z) | |
local internal = self:getInternal() | |
internal.sclX = x | |
internal.sclY = y | |
internal.sclZ = z | |
local sclX, sclY, sclZ = self:getOrignScl() | |
sclX, sclY, sclZ = sclX * x, sclY * y, sclZ * z | |
self:setOrignScl(sclX, sclY, sclZ) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns a virtual scale.<br> | |
-- TODO:Can not cope with if you want to move dynamically.<br> | |
-- @return scaleX, scaleY, scaleZ. | |
-------------------------------------------------------------------------------- | |
function M:getScl() | |
return self._sclX, self._sclY, self._sclZ | |
end | |
-------------------------------------------------------------------------------- | |
-- Seek a virtual scale.<br> | |
-- TODO:Does not work | |
-- @param x X of scale. | |
-- @param y Y of scale. | |
-- @param z Z of scale. | |
-- @param sec seconds. | |
-- @param mode MOAIEaseType. | |
-- @return MOAIEase | |
-------------------------------------------------------------------------------- | |
function M:seekScl(x, y, z, sec, mode) | |
local sclX, sclY, sclZ = self:getOrignScl() | |
sclX, sclY, sclZ = sclX * x, sclY * y, sclZ * z | |
return self:seekScl(sclX, sclY, sclZ, sec, mode) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the ratio of the columns. | |
-- @param col1 Fixed ratio of the column. | |
-- @param col2 Dynamic ratio of the column. | |
-- @param col3 Fixed ratio of the column. | |
-------------------------------------------------------------------------------- | |
function M:setStretchColumns(col1, col2, col3) | |
self.deck:setColumn ( 1, col1, false ) | |
self.deck:setColumn ( 2, col2, true ) | |
self.deck:setColumn ( 3, col3, false ) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the ratio of the rows. | |
-- @param row1 Fixed ratio of the row. | |
-- @param row2 Dynamic ratio of the row. | |
-- @param row3 Fixed ratio of the row. | |
-------------------------------------------------------------------------------- | |
function M:setStretchRows(row1, row2, row3) | |
self.deck:setRow ( 1, row1, false ) | |
self.deck:setRow ( 2, row2, true ) | |
self.deck:setRow ( 3, row3, false ) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the boundary position. | |
-- @return xMin, yMin, zMin, xMax, yMax, zMax | |
-------------------------------------------------------------------------------- | |
function M:getBounds() | |
local width, height = self._width, self._height | |
local xMin, yMin, zMin = -width / 2, -height / 2, 0 | |
local xMax, yMax, zMax = width / 2, height / 2, 0 | |
return xMin, yMin, zMin, xMax, yMax, zMax | |
end | |
return M end) | |
package.preload['hp/display/Particles'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This is a class to draw the texture. <br> | |
-- Base Classes => DisplayObject, TextureDrawable, Resizable <br> | |
-------------------------------------------------------------------------------- | |
local table = require("hp/lang/table") | |
local class = require("hp/lang/class") | |
local DisplayObject = require("hp/display/DisplayObject") | |
local TextureDrawable = require("hp/display/TextureDrawable") | |
local ResourceManager = require("hp/manager/ResourceManager") | |
local M = class(DisplayObject, TextureDrawable) | |
M.MOAI_CLASS = MOAIParticleSystem | |
function M.fromPex(particleName) | |
local filePath = ResourceManager:getFilePath(particleName) | |
local plugin = MOAIParticlePexPlugin.load(filePath) | |
local self = M(plugin:getTextureName()) | |
self:reserveParticles(plugin:getMaxParticles(), plugin:getSize()) | |
self:reserveSprites(plugin:getMaxParticles()) | |
self:reserveStates(1) | |
self:setBlendMode(plugin:getBlendMode()) | |
local state = MOAIParticleState.new() | |
state:setTerm(plugin:getLifespan()) | |
state:setPlugin(plugin) | |
local emitter = MOAIParticleTimedEmitter.new() | |
emitter:setLoc(0, 0) | |
emitter:setSystem(self) | |
emitter:setEmission(plugin:getEmission()) | |
emitter:setFrequency(plugin:getFrequency()) | |
emitter:setRect(plugin:getRect()) | |
local timer = MOAITimer.new() | |
timer:setSpan(plugin:getDuration()) | |
timer:setMode(MOAITimer.NORMAL) | |
timer:setListener(MOAIAction.EVENT_STOP, function() self:stopParticle() end) | |
self.plugin = plugin | |
self.emitter = emitter | |
self.state = state | |
self.timer = timer | |
self:setState(1, state) | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-- @param params (option)Parameter is set to Object.<br> | |
-------------------------------------------------------------------------------- | |
function M:init(params) | |
DisplayObject.init(self) | |
params = params or {} | |
params = type(params) == "string" and {texture = params} or params | |
local deck = MOAIGfxQuad2D.new() | |
deck:setUVRect(0, 0, 1, 1) | |
deck:setRect(-0.5, -0.5, 0.5, 0.5) | |
self:setDeck(deck) | |
self.deck = deck | |
self:copyParams(params) | |
end | |
function M:startParticle() | |
self.emitter:start() | |
if self.plugin:getDuration() > -1 then | |
self.timer:start() | |
end | |
end | |
function M:stopParticle() | |
self.emitter:stop() | |
if self.plugin:getDuration() > -1 then | |
self.timer:stop() | |
end | |
end | |
return M end) | |
package.preload['hp/display/Resizable'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- Is the module object can be resized to be implemented.<br> | |
-- TODO:In the future, there is likely to change in order to unify the origin of the position. | |
-------------------------------------------------------------------------------- | |
local M = {} | |
-------------------------------------------------------------------------------- | |
-- Set the width.<br> | |
-- @param width width | |
-------------------------------------------------------------------------------- | |
function M:setWidth(width) | |
self:setSize(width, self:getHeight()) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the height<br> | |
-- @param height height | |
-------------------------------------------------------------------------------- | |
function M:setHeight(height) | |
self:setSize(self:getWidth(), height) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the height and width.<br> | |
-- If the argument is not set the size of the texture will be set. | |
-- TODO:In the future, there is likely to change in order to unify the origin of the position. | |
-- @param width width | |
-- @param height height | |
-------------------------------------------------------------------------------- | |
function M:setSize(width, height) | |
if self.texture then | |
local tw, th = self.texture:getSize() | |
width = width or tw | |
height = height or th | |
end | |
width = width or self:getWidth() | |
height = height or self:getHeight() | |
local left, top = self:getPos() | |
self.deck:setRect(-width / 2, -height / 2, width / 2, height / 2) | |
self:setPos(left, top) | |
end | |
-------------------------------------------------------------------------------- | |
-- Function indicating that it is possible to resize.<br> | |
-- @return true | |
-------------------------------------------------------------------------------- | |
function M:isResizable() | |
return true | |
end | |
return M end) | |
package.preload['hp/display/Scene'] = (function (...) | |
---------------------------------------------------------------- | |
-- This class is a top-level container to build a scene graph. | |
-- Use this class to build a game scene. | |
-- <br> | |
-- Scene is managed by the SceneManager. | |
-- Use by specifying the module from the SceneManager. | |
-- Scene will be generated internally. | |
-- <br> | |
-- The Scene is the life cycle exists. | |
-- It is important to understand the life cycle. | |
-- <br> | |
-- 1. onCreate(params)<br> | |
-- Called when created.<br> | |
-- Initializes the scene graph in this function.<br> | |
-- 2. onStart()<br> | |
-- Called when started.<br> | |
-- Called after the animation is complete.<br> | |
-- 3. onResume()<br> | |
-- Called when resumed. | |
-- 4. onPause()<br> | |
-- Called when paused.<br> | |
-- 5. onStop()<br> | |
-- Called when the stoped.<br> | |
-- 6. onDestroy()<br> | |
-- Called when destroyed.<br> | |
---------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local Group = require "hp/display/Group" | |
local Event = require "hp/event/Event" | |
local EventDispatcher = require "hp/event/EventDispatcher" | |
local Application = require "hp/core/Application" | |
local Logger = require "hp/util/Logger" | |
-- class | |
local M = class(Group) | |
-- events | |
M.EVENT_ENTER_FRAME = "enterFrame" | |
M.EVENT_CREATE = "create" | |
M.EVENT_START = "start" | |
M.EVENT_RESUME = "resume" | |
M.EVENT_PAUSE = "pause" | |
M.EVENT_STOP = "stop" | |
M.EVENT_DESTROY = "destroy" | |
M.EVENT_TOUCH_DOWN = "touchDown" | |
M.EVENT_TOUCH_UP = "touchUp" | |
M.EVENT_TOUCH_MOVE = "touchMove" | |
M.EVENT_TOUCH_CANCEL = "touchCancel" | |
M.EVENT_KEY_DOWN = "keyDown" | |
M.EVENT_KEY_UP = "keyUp" | |
-- local functions | |
local function destroyModule(m) | |
if m and m._M and m._NAME then | |
package.loaded[m._NAME] = nil | |
_G[m._NAME] = nil | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-------------------------------------------------------------------------------- | |
function M:init() | |
Group.init(self) | |
self:setSize(Application.screenWidth, Application.screenHeight) | |
self.name = "" | |
self.visible = true | |
self.sceneManager = require("hp/manager/SceneManager") | |
self.sceneHandler = {} | |
self.touchDownFlag = false | |
self:setCenterPiv() | |
self:setPos(0, 0) | |
end | |
---------------------------------------------------------------- | |
-- Add a child object. <br> | |
-- @param child Child to inherit the MOAILayer. | |
---------------------------------------------------------------- | |
function M:addChild(child) | |
Group.addChild(self, child) | |
self.sceneManager:updateRender() | |
end | |
---------------------------------------------------------------- | |
-- Remove the child object. <br> | |
-- @param child Child to inherit the MOAILayer. | |
---------------------------------------------------------------- | |
function M:removeChild(child) | |
Group.removeChild(self, child) | |
self.sceneManager:updateRender() | |
end | |
---------------------------------------------------------------- | |
-- Sets the visible.<br> | |
-- If set to false, excluded from the target rendering.<br> | |
-- @param value visible. | |
---------------------------------------------------------------- | |
function M:setVisible(value) | |
self.visible = value | |
self.sceneManager:updateRender() | |
end | |
---------------------------------------------------------------- | |
-- Returns the visible. | |
-- @return visible. | |
---------------------------------------------------------------- | |
function M:getVisible() | |
return self.visible | |
end | |
--------------------------------------- | |
-- Display to the front Scene. | |
--------------------------------------- | |
function M:orderToFront() | |
self.sceneManager:orderToFront(self) | |
end | |
--------------------------------------- | |
-- Display to the back Scene. | |
--------------------------------------- | |
function M:orderToBack() | |
self.sceneManager:orderToBack(self) | |
end | |
--------------------------------------- | |
-- Returns the rendering table.<br> | |
-- @return renderTable. | |
--------------------------------------- | |
function M:getRenderTable() | |
local renderTable = {} | |
for i, v in ipairs(self.children) do | |
if v.getRenderTable then | |
table.insert(renderTable, v:getRenderTable()) | |
else | |
table.insert(renderTable, v) | |
end | |
end | |
return renderTable | |
end | |
--------------------------------------- | |
-- Called when it is created. | |
--------------------------------------- | |
function M:onCreate(params) | |
if self.sceneHandler.onCreate then | |
self.sceneHandler.onCreate(params) | |
end | |
self:dispatchEvent(M.EVENT_CREATE, params) | |
end | |
--------------------------------------- | |
-- Called when it is started. | |
--------------------------------------- | |
function M:onStart() | |
if self.sceneHandler.onStart then | |
self.sceneHandler.onStart() | |
end | |
self:dispatchEvent(M.EVENT_START) | |
end | |
--------------------------------------- | |
-- Called when resumed. | |
--------------------------------------- | |
function M:onResume() | |
if self.sceneHandler.onResume then | |
self.sceneHandler.onResume() | |
end | |
self:dispatchEvent(M.EVENT_RESUME) | |
end | |
--------------------------------------- | |
-- Called when paused. | |
--------------------------------------- | |
function M:onPause() | |
if self.sceneHandler.onPause then | |
self.sceneHandler.onPause() | |
end | |
self:dispatchEvent(M.EVENT_PAUSE) | |
end | |
--------------------------------------- | |
-- Called when stoped. | |
--------------------------------------- | |
function M:onStop() | |
if self.sceneHandler.onStop then | |
self.sceneHandler.onStop() | |
end | |
self:dispatchEvent(M.EVENT_STOP) | |
end | |
--------------------------------------- | |
-- Called when destroyed. | |
--------------------------------------- | |
function M:onDestroy() | |
if self.sceneHandler.onDestroy then | |
self.sceneHandler.onDestroy() | |
end | |
self:dispatchEvent(M.EVENT_DESTROY) | |
self:dispose() | |
destroyModule(self.sceneHandler) | |
end | |
--------------------------------------- | |
-- Called when updated. | |
--------------------------------------- | |
function M:onEnterFrame() | |
if self.sceneHandler.onEnterFrame then | |
self.sceneHandler.onEnterFrame() | |
end | |
self:dispatchEvent(M.EVENT_ENTER_FRAME) | |
end | |
--------------------------------------- | |
-- Called when keyboard input. | |
-- @param event Keybord event. | |
--------------------------------------- | |
function M:onKeyDown(event) | |
local target = event.target | |
self:dispatchEvent(event) | |
event.target = target | |
if not event.stoped and self.sceneHandler.onKeyDown then | |
self.sceneHandler.onKeyDown(event) | |
end | |
end | |
--------------------------------------- | |
-- Called when keyboard input. | |
-- @param event Keybord event. | |
--------------------------------------- | |
function M:onKeyUp(event) | |
local target = event.target | |
self:dispatchEvent(event) | |
event.target = target | |
if not event.stoped and self.sceneHandler.onKeyUp then | |
self.sceneHandler.onKeyUp(event) | |
end | |
end | |
--------------------------------------- | |
-- Called when screen touched. | |
-- @param event Event. | |
--------------------------------------- | |
function M:onTouchDown(event) | |
local target = event.target | |
self:dispatchEvent(event) | |
event.target = target | |
if not event.stoped and self.sceneHandler.onTouchDown then | |
self.sceneHandler.onTouchDown(event) | |
end | |
end | |
--------------------------------------- | |
-- Called when screen touched. | |
-- @param event Event. | |
--------------------------------------- | |
function M:onTouchUp(event) | |
local target = event.target | |
self:dispatchEvent(event) | |
event.target = target | |
if not event.stoped and self.sceneHandler.onTouchUp then | |
self.sceneHandler.onTouchUp(event) | |
end | |
end | |
--------------------------------------- | |
-- Called when screen touched. | |
-- @param event Event. | |
--------------------------------------- | |
function M:onTouchMove(event) | |
local target = event.target | |
self:dispatchEvent(event) | |
event.target = target | |
if not event.stoped and self.sceneHandler.onTouchMove then | |
self.sceneHandler.onTouchMove(event) | |
end | |
end | |
--------------------------------------- | |
-- Called when screen touched. | |
-- @param event Event. | |
--------------------------------------- | |
function M:onTouchCancel(event) | |
local target = event.target | |
self:dispatchEvent(event) | |
event.target = target | |
if not event.stoped and self.sceneHandler.onTouchCancel then | |
self.sceneHandler.onTouchCancel(event) | |
end | |
end | |
return M end) | |
package.preload['hp/display/SceneAnimation'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This module to animate the Scene. <br> | |
-- You are not required to refer to the function is not available. <br> | |
-- Animation is possible with the function name specified in the SceneManager. <br> | |
-------------------------------------------------------------------------------- | |
local Animation = require "hp/display/Animation" | |
local Graphics = require "hp/display/Graphics" | |
local Layer = require "hp/display/Layer" | |
local M = {} | |
local POPUP_LAYER = "SceneAnimationPopUpLayer" | |
local defaultSecond = 0.4 | |
local function createShowAnimation(scene, sec) | |
return Animation({scene}, sec) | |
:setColor(1, 1, 1, 1):setVisible(true) | |
:setLeft(0):setTop(0):setScl(1, 1, 1):setRot(0, 0, 0) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the default animation second. | |
-------------------------------------------------------------------------------- | |
function M.setDefaultSecond(sec) | |
defaultSecond = sec | |
end | |
-------------------------------------------------------------------------------- | |
-- The displayed immediately. | |
-------------------------------------------------------------------------------- | |
function M.changeNow(currentScene, nextScene, params) | |
return Animation():parallel( | |
Animation({currentScene}, 0):setVisible(false), | |
createShowAnimation(nextScene, 0) | |
) | |
end | |
-------------------------------------------------------------------------------- | |
-- The pop-up display. | |
-------------------------------------------------------------------------------- | |
function M.popIn(currentScene, nextScene, params) | |
local sec = params.sec and params.sec or defaultSecond | |
local layer = Layer {scene = currentScene} | |
layer.name = POPUP_LAYER | |
layer:setColor(0, 0, 0, 0) | |
local g = Graphics {layer = layer, width = layer:getViewWidth() + 1, height = layer:getViewHeight() + 1} | |
g:setPenColor(0, 0, 0, 1):fillRect() | |
return Animation():parallel( | |
Animation(layer, sec) | |
:seekColor(0.5, 0.5, 0.5, 0.5), | |
createShowAnimation(nextScene, sec):parallel( | |
Animation(nextScene, sec):setColor(0, 0, 0, 0):seekColor(1, 1, 1, 1), | |
Animation(nextScene, sec):setScl(0.5, 0.5, 1):seekScl(1, 1, 1) | |
) | |
) | |
end | |
-------------------------------------------------------------------------------- | |
-- Close the pop-up display. <br> | |
-- Valid only for scene that displays pop-up. | |
-------------------------------------------------------------------------------- | |
function M.popOut(currentScene, nextScene, params) | |
local sec = params.sec and params.sec or defaultSecond | |
local layer = nextScene:getChildByName(POPUP_LAYER) | |
return Animation():parallel( | |
Animation(currentScene, sec):parallel( | |
Animation(currentScene, sec):seekColor(0, 0, 0, 0):setVisible(false), | |
Animation(currentScene, sec):seekScl(0.5, 0.5, 1) | |
), | |
Animation(layer, sec):seekColor(0, 0, 0, 0):callFunc(function() nextScene:removeChild(layer) end) | |
) | |
end | |
-------------------------------------------------------------------------------- | |
-- order to run fadeOut, fadeIn. | |
-------------------------------------------------------------------------------- | |
function M.fade(currentScene, nextScene, params) | |
local sec = params.sec and params.sec or M.defaultSecond | |
return Animation():sequence( | |
Animation({nextScene}, sec):setColor(0, 0, 0, 0), | |
Animation({currentScene}, sec):setVisible(true):fadeOut():setVisible(false), | |
createShowAnimation(nextScene, sec):fadeIn() | |
) | |
end | |
-------------------------------------------------------------------------------- | |
-- The parallel execution fadeOut, fadeIn. | |
-------------------------------------------------------------------------------- | |
function M.crossFade(currentScene, nextScene, params) | |
local sec = params.sec and params.sec or defaultSecond | |
return Animation():parallel( | |
Animation({currentScene}, sec):setVisible(true):fadeOut():setVisible(false), | |
createShowAnimation(nextScene, sec):fadeIn() | |
) | |
end | |
-------------------------------------------------------------------------------- | |
-- Slide the top. | |
-------------------------------------------------------------------------------- | |
function M.slideToTop(currentScene, nextScene, params) | |
local sec = params.sec and params.sec or defaultSecond | |
local sw, sh = currentScene:getWidth(), currentScene:getHeight() | |
return Animation():parallel( | |
Animation({currentScene}, sec) | |
:setVisible(true) | |
:moveLoc(0, -sh, 0) | |
:setVisible(false), | |
createShowAnimation(nextScene, sec) | |
:setLeft(0):setTop(sh) | |
:moveLoc(0, -sh, 0) | |
:setTop(0) | |
) | |
end | |
-------------------------------------------------------------------------------- | |
-- Slide the bottom. | |
-------------------------------------------------------------------------------- | |
function M.slideToBottom(currentScene, nextScene, params) | |
local sec = params.sec and params.sec or defaultSecond | |
local sw, sh = currentScene:getWidth(), currentScene:getHeight() | |
return Animation():parallel( | |
Animation({currentScene}, sec) | |
:moveLoc(0, sh, 0) | |
:setVisible(false), | |
createShowAnimation(nextScene, sec) | |
:setLeft(0):setTop(-sh) | |
:moveLoc(0, sh, 0) | |
:setTop(0) | |
) | |
end | |
-------------------------------------------------------------------------------- | |
-- Slide the left. | |
-------------------------------------------------------------------------------- | |
function M.slideToLeft(currentScene, nextScene, params) | |
local sec = params.sec and params.sec or defaultSecond | |
local sw, sh = currentScene:getWidth(), currentScene:getHeight() | |
return Animation():parallel( | |
Animation({currentScene}, sec) | |
:setLeft(0):setTop(0) | |
:moveLoc(-sw, 0, 0) | |
:setVisible(false), | |
createShowAnimation(nextScene, sec) | |
:setLeft(sw):setTop(0) | |
:moveLoc(-sw, 0, 0) | |
:setLeft(0) | |
) | |
end | |
-------------------------------------------------------------------------------- | |
-- Slide the right. | |
-------------------------------------------------------------------------------- | |
function M.slideToRight(currentScene, nextScene, params) | |
local sec = params.sec and params.sec or defaultSecond | |
local sw, sh = currentScene:getWidth(), currentScene:getHeight() | |
return Animation():parallel( | |
Animation({currentScene}, sec) | |
:setLeft(0):setTop(0) | |
:moveLoc(sw, 0, 0) | |
:setVisible(false), | |
createShowAnimation(nextScene, sec) | |
:setLeft(-sw):setTop(0) | |
:moveLoc(sw, 0, 0) | |
:setLeft(0) | |
) | |
end | |
return M end) | |
package.preload['hp/display/Sprite'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This is a class to draw the texture. <br> | |
-- Base Classes => DisplayObject, TextureDrawable, Resizable <br> | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local DisplayObject = require "hp/display/DisplayObject" | |
local TextureDrawable = require "hp/display/TextureDrawable" | |
local Resizable = require "hp/display/Resizable" | |
-- class | |
local M = class(DisplayObject, TextureDrawable, Resizable) | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-- @param params (option)Parameter is set to Object.<br> | |
-------------------------------------------------------------------------------- | |
function M:init(params) | |
DisplayObject.init(self) | |
params = params or {} | |
params = type(params) == "string" and {texture = params} or params | |
local deck = MOAIGfxQuad2D.new() | |
deck:setUVRect(0, 0, 1, 1) | |
self:setDeck(deck) | |
self.deck = deck | |
self:copyParams(params) | |
end | |
return M end) | |
package.preload['hp/display/SpriteSheet'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This is a class to draw the sheet switching. <br> | |
-- Sheet can be defined in any shape. <br> | |
-- <br> | |
-- Base Classes => DisplayObject, TextureDrawable<br> | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local DisplayObject = require "hp/display/DisplayObject" | |
local TextureDrawable = require "hp/display/TextureDrawable" | |
-- class | |
local M = class(DisplayObject, TextureDrawable) | |
-------------------------------------------------------------------------------- | |
-- The constructor.<br> | |
-- @param params (option)Parameter is set to Object.<br> | |
-- params:<br> | |
-- texture:Path of the texture. Or, MOAITexture instance.<br> | |
-- sheets:See setSheets function.<br> | |
-- sheetAnims = See setSheetAnims function.<br> | |
-- @return instance | |
-------------------------------------------------------------------------------- | |
function M:init(params) | |
DisplayObject.init(self) | |
params = params or {} | |
params = type(params) == "string" and {texture = params} or params | |
local deck = MOAIGfxQuadDeck2D.new() | |
self:setDeck(deck) | |
self.deck = deck | |
self.animTable = {} | |
self.currentAnim = nil | |
self.sheetSize = 0 | |
self:copyParams(params) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the sheet data in the form of tiles. | |
-- @param tileWidth The width of the tile. | |
-- @param tileHeight The height of the tile. | |
-- @param tileX (option)number of tiles in the x-direction. | |
-- @param tileY (option)number of tiles in the y-direction. | |
-- @param spacing (option)Spaces between tiles. | |
-- @param margin (option)Margins of the Start position | |
-------------------------------------------------------------------------------- | |
function M:setTiledSheets(tileWidth, tileHeight, tileX, tileY, spacing, margin) | |
assert(self.texture) | |
assert(tileWidth) | |
assert(tileHeight) | |
spacing = spacing or 0 | |
margin = margin or 0 | |
local tw, th = self.texture:getSize() | |
tileX = tileX or math.floor((tw - margin) / (tileWidth + spacing)) | |
tileY = tileY or math.floor((th - margin) / (tileHeight + spacing)) | |
local sheets = {} | |
for y = 1, tileY do | |
for x = 1, tileX do | |
local sx = (x - 1) * (tileWidth + spacing) + margin | |
local sy = (y - 1) * (tileHeight + spacing) + margin | |
table.insert(sheets, {x = sx, y = sy, width = tileWidth, height = tileHeight}) | |
end | |
end | |
self:setSheets(sheets) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the tile size. | |
-- @param tileX number of tiles in the x-direction. | |
-- @param tileY number of tiles in the y-direction. | |
-------------------------------------------------------------------------------- | |
function M:setTileSize(tileX, tileY) | |
assert(self.texture) | |
local tw, th = self.texture:getSize() | |
local w, h = tw / tileX, th / tileY | |
self:setTiledSheets(w, h, tileX, tileY) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the data sheet.<br> | |
-- Sheet in accordance with the following format: Please.<br> | |
-- {x = Start position, y = Start position, width = The width of the sheet, height = The height of the sheet} <br> | |
-- TODO:Setting of the flip. | |
-- @param sheets sheet data | |
-------------------------------------------------------------------------------- | |
function M:setSheets(sheets) | |
assert(self.texture) | |
local tw, th = self.texture:getSize() | |
self.deck:reserve(#sheets) | |
self.sheetSize = #sheets | |
for i, sheet in ipairs(sheets) do | |
local xMin, yMin = sheet.x, sheet.y | |
local xMax = sheet.x + sheet.width | |
local yMax = sheet.y + sheet.height | |
self.deck:setRect(i, -sheet.width / 2, -sheet.height / 2, sheet.width / 2, sheet.height / 2) | |
self.deck:setUVRect(i, xMin / tw, yMin / th, xMax / tw, yMax / th) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the data to move the key frame animations.<br> | |
-- See M:setSheetAnim function.<br> | |
-- @param sheetAnims table is set to setSheetAnim. | |
-------------------------------------------------------------------------------- | |
function M:setSheetAnims(sheetAnims) | |
for i, v in ipairs(sheetAnims) do | |
local name = v.name or i | |
self:setSheetAnim(name, v.indexes, v.sec, v.mode) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the data to move the key frame animation.<br> | |
-- @param name Animation name. | |
-- @param indexes Key sequence. | |
-- @param sec Seconds to move the key. | |
-- @param mode (option)Mode is set to MOAIAnim.(The default is MOAITimer.LOOP) | |
-------------------------------------------------------------------------------- | |
function M:setSheetAnim(name, indexes, sec, mode) | |
local curve = MOAIAnimCurve.new() | |
local anim = MOAIAnim.new() | |
curve:reserveKeys(#indexes) | |
for i = 1, #indexes do | |
curve:setKey(i, sec * (i - 1), indexes[i], MOAIEaseType.FLAT ) | |
end | |
local mode = mode or MOAITimer.LOOP | |
anim:reserveLinks(1) | |
anim:setMode(mode) | |
anim:setLink(1, curve, self, MOAIProp.ATTR_INDEX ) | |
anim:setCurve(curve) | |
self.animTable[name] = anim | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the animation data with the specified name. | |
-- @param name Animation name. | |
-- @return MOAIAnim instance | |
-------------------------------------------------------------------------------- | |
function M:getSheetAnim(name) | |
return self.animTable[name] | |
end | |
-------------------------------------------------------------------------------- | |
-- Start the animation. | |
-------------------------------------------------------------------------------- | |
function M:playAnim(name) | |
local currentAnim = self.currentAnim | |
local animTable = self.animTable | |
if currentAnim and currentAnim:isBusy() then | |
currentAnim:stop() | |
end | |
if animTable[name] then | |
currentAnim = animTable[name] | |
self.currentAnim = currentAnim | |
end | |
if currentAnim then | |
currentAnim:start() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Stop the animation. | |
-------------------------------------------------------------------------------- | |
function M:stopAnim() | |
if self.currentAnim then | |
self.currentAnim:stop() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Check the current animation with the specified name.<br> | |
-- @param name Animation name. | |
-- @return If the current animation is true. | |
-------------------------------------------------------------------------------- | |
function M:isCurrentAnim(name) | |
return self.currentAnim == self.animTable[name] | |
end | |
return M end) | |
package.preload['hp/display/TextLabel'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This is a class to draw the text. | |
-- See MOAITextBox.<br> | |
-- Base Classes => DisplayObject, Resizable | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require("hp/lang/table") | |
local class = require("hp/lang/class") | |
local DisplayObject = require("hp/display/DisplayObject") | |
local Resizable = require("hp/display/Resizable") | |
local FontManager = require("hp/manager/FontManager") | |
-- class | |
local M = class(DisplayObject, Resizable) | |
local MOAITextBoxInterface = MOAITextBox.getInterfaceTable() | |
M.MOAI_CLASS = MOAITextBox | |
-- constraints | |
M.DEFAULT_FONT = "fonts/VL-PGothic.ttf" | |
M.DEFAULT_CHARCODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,:;!?()&/-" | |
M.DEFAULT_TEXT_SIZE = 24 | |
M.DEFAULT_COLOR = {1, 1, 1, 1} | |
M.HORIZOTAL_ALIGNS = { | |
left = MOAITextBox.LEFT_JUSTIFY, | |
center = MOAITextBox.CENTER_JUSTIFY, | |
right = MOAITextBox.RIGHT_JUSTIFY, | |
} | |
M.VERTICAL_ALIGNS = { | |
top = MOAITextBox.LEFT_JUSTIFY, | |
center = MOAITextBox.CENTER_JUSTIFY, | |
bottom = MOAITextBox.RIGHT_JUSTIFY, | |
} | |
--- Max width for fit size. | |
M.MAX_FIT_WIDTH = 10000000 | |
--- Max height for fit size. | |
M.MAX_FIT_HEIGHT = 10000000 | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-- @param params (option)Parameter is set to Object.<br> | |
-------------------------------------------------------------------------------- | |
function M:init(params) | |
DisplayObject.init(self) | |
params = params or {} | |
params = type(params) == "string" and {text = params} or params | |
self:setFont(M.DEFAULT_FONT) | |
self:setTextSize(M.DEFAULT_TEXT_SIZE) | |
self:setColor(unpack(M.DEFAULT_COLOR)) | |
self:copyParams(params) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the text size. | |
-- @param width | |
-- @param height | |
-------------------------------------------------------------------------------- | |
function M:setSize(width, height) | |
width = width or self:getWidth() | |
height = height or self:getHeight() | |
local left, top = self:getPos() | |
self:setRect(-width / 2, -height / 2, width / 2, height / 2) | |
self:setPos(left, top) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the text size. | |
-- @param points size. | |
-- @param dpi (deprecated)Resolution. | |
-------------------------------------------------------------------------------- | |
function M:setTextSize(points, dpi) | |
self._textSizePoints = points | |
self._textSizeDpi = dpi | |
MOAITextBoxInterface.setTextSize(self, points, dpi) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the text size. | |
-- @return points, dpi | |
-------------------------------------------------------------------------------- | |
function M:getTextSize() | |
return self._textSizePoints, self._textSizeDpi | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the text. | |
-- @param text text. | |
-------------------------------------------------------------------------------- | |
function M:setText(text) | |
self:setString(text) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the font. | |
-- @param font font. | |
-------------------------------------------------------------------------------- | |
function M:setFont(font) | |
if type(font) == "string" then | |
font = FontManager:request(font, self._textSizePoints or M.DEFAULT_TEXT_SIZE, M.DEFAULT_CHARCODES, self._textSizeDpi) | |
end | |
MOAITextBoxInterface.setFont(self, font) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the Alignments. | |
-------------------------------------------------------------------------------- | |
function M:setAlign(horizotalAlign, verticalAlign) | |
local h, v = M.HORIZOTAL_ALIGNS[horizotalAlign], M.VERTICAL_ALIGNS[verticalAlign] | |
self:setAlignment(h, v) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the fit size. | |
-- @param lenfth (Option)Length of the text. | |
-------------------------------------------------------------------------------- | |
function M:fitSize(length) | |
self:setRect(0, 0, M.MAX_FIT_WIDTH, M.MAX_FIT_HEIGHT) | |
length = length or 1000000 | |
local padding = 2 | |
local left, top, right, bottom = self:getStringBounds(1, length) | |
local width, height = right - left + padding, bottom - top + padding | |
width = width % 2 == 0 and width or width + 1 | |
height = height % 2 == 0 and height or height + 1 | |
self:setSize(width, height) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the fit height. | |
-- @param lenfth (Option)Length of the text. | |
-------------------------------------------------------------------------------- | |
function M:fitHeight(length) | |
local w, h, d = self:getDims() | |
self:setRect(0, 0, w, M.MAX_FIT_HEIGHT) | |
length = length or 1000000 | |
local padding = 2 | |
local left, top, right, bottom = self:getStringBounds(1, length) | |
local width, height = right - left + padding, bottom - top + padding | |
width = width % 2 == 0 and width or width + 1 | |
height = height % 2 == 0 and height or height + 1 | |
self:setHeight(height) | |
end | |
return M end) | |
package.preload['hp/display/TextureDrawable'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This module object on which to draw the texture to be implemented. <br> | |
-- This module by itself can not be used.<br> | |
-------------------------------------------------------------------------------- | |
local TextureManager = require("hp/manager/TextureManager") | |
local M = {} | |
-------------------------------------------------------------------------------- | |
-- Set the Texture to self.deck. | |
-- @param texture Path or texture. | |
-------------------------------------------------------------------------------- | |
function M:setTexture(texture) | |
assert(texture, "texture nil value!") | |
if type(texture) == "string" then | |
texture = TextureManager:request(texture) | |
end | |
if self.texture == texture then | |
return | |
end | |
local left, top = self:getPos() | |
local resize = self.texture == nil and self.setSize ~= nil | |
self.texture = texture | |
self.deck:setTexture(texture) | |
self:setPos(left, top) | |
if resize then | |
local w, h = texture:getSize() | |
self:setSize(w, h) | |
end | |
end | |
return M end) | |
package.preload['hp/display/TouchProcessor'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This class inherits the MOAILayer. <br> | |
-- Simplifies the generation of a set of size and layer. <br> | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local Event = require "hp/event/Event" | |
local InputManager = require "hp/manager/InputManager" | |
-- class define | |
local M = class() | |
-- event cache | |
local EVENT_TOUCH_DOWN = Event(Event.TOUCH_DOWN) | |
local EVENT_TOUCH_UP = Event(Event.TOUCH_UP) | |
local EVENT_TOUCH_MOVE = Event(Event.TOUCH_MOVE) | |
local EVENT_TOUCH_CANCEL = Event(Event.TOUCH_CANCEL) | |
-- | |
local function getPointByCache(self, e) | |
for i, p in ipairs(self._touchPoints) do | |
if p.idx == e.idx then | |
return p | |
end | |
end | |
end | |
-- | |
local function getPointByEvent(self, e) | |
local layer = self._touchLayer | |
local p = getPointByCache(self, e) or {} | |
p.idx = e.idx | |
p.tapCount = e.tapCount | |
p.oldX, p.oldY = p.x, p.y | |
p.x, p.y = layer:wndToWorld(e.x, e.y, 0) | |
p.screenX, p.screenY = e.x, e.y | |
if p.oldX and p.oldY then | |
p.moveX = p.x - p.oldX | |
p.moveY = p.y - p.oldY | |
else | |
p.oldX, p.oldY = p.x, p.y | |
p.moveX, p.moveY = 0, 0 | |
end | |
return p | |
end | |
local function eventHandle(self, e, o) | |
local layer = self._touchLayer | |
while o do | |
if o.isTouchEnabled and not o:isTouchEnabled() then | |
break | |
end | |
if o.dispatchEvent then | |
o:dispatchEvent(e) | |
end | |
if o.getParent then | |
o = o:getParent() | |
else | |
o = nil | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-- @param layer (option)Parameter is set to Object.<br> | |
-------------------------------------------------------------------------------- | |
function M:init(layer) | |
self._touchLayer = assert(layer) | |
self._touchPoints = {} | |
self._eventSource = nil | |
self._enabled = true | |
end | |
-------------------------------------------------------------------------------- | |
-- イベント発生元を設定します. | |
-- 典型的には、Sceneインスタンスが設定されます. | |
-------------------------------------------------------------------------------- | |
function M:setEventSource(eventSource) | |
if self._eventSource then | |
self._eventSource:removeEventListener(Event.TOUCH_DOWN, self.touchDownHandler, self) | |
self._eventSource:removeEventListener(Event.TOUCH_UP, self.touchUpHandler, self) | |
self._eventSource:removeEventListener(Event.TOUCH_MOVE, self.touchMoveHandler, self) | |
self._eventSource:removeEventListener(Event.TOUCH_CANCEL, self.touchCancelHandler, self) | |
end | |
self._eventSource = eventSource | |
if self._eventSource then | |
self._eventSource:addEventListener(Event.TOUCH_DOWN, self.touchDownHandler, self) | |
self._eventSource:addEventListener(Event.TOUCH_UP, self.touchUpHandler, self) | |
self._eventSource:addEventListener(Event.TOUCH_MOVE, self.touchMoveHandler, self) | |
self._eventSource:addEventListener(Event.TOUCH_CANCEL, self.touchCancelHandler, self) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- イベントソースに対する参照を削除します. | |
-------------------------------------------------------------------------------- | |
function M:dispose() | |
self:setEventSource(nil) | |
end | |
-------------------------------------------------------------------------------- | |
-- プロセッサーが有効かどうか設定します. | |
-------------------------------------------------------------------------------- | |
function M:setEnabled(value) | |
self._enabled = value | |
end | |
-------------------------------------------------------------------------------- | |
-- プロセッサーが有効かどうか返します. | |
-------------------------------------------------------------------------------- | |
function M:isEnabled() | |
return self._enabled | |
end | |
-------------------------------------------------------------------------------- | |
-- タッチした時のイベント処理を行います. | |
-------------------------------------------------------------------------------- | |
function M:touchDownHandler(e) | |
if not self:isEnabled() then | |
return | |
end | |
local layer = self._touchLayer | |
local p = getPointByEvent(self, e) | |
p.touchingProp = layer:getPartition():propForPoint(p.x, p.y, 0) | |
table.insertElement(self._touchPoints, p) | |
local te = table.copy(p, EVENT_TOUCH_DOWN) | |
te.points = self._touchPoints | |
if p.touchingProp then | |
eventHandle(self, te, p.touchingProp) | |
end | |
if not te.stoped then | |
layer:dispatchEvent(te) | |
end | |
if te.stoped then | |
e:stop() | |
end | |
end | |
---------------------------------------------------------------- | |
-- タッチした時のイベント処理を行います. | |
---------------------------------------------------------------- | |
function M:touchUpHandler(e) | |
if not self:isEnabled() then | |
return | |
end | |
local layer = self._touchLayer | |
local p = getPointByEvent(self, e) | |
local te = table.copy(p, EVENT_TOUCH_UP) | |
if p.touchingProp then | |
eventHandle(self, te, p.touchingProp) | |
end | |
local o = layer:getPartition():propForPoint(p.x, p.y, 0) | |
if o and o ~= p.touchingProp then | |
eventHandle(self, te, o) | |
end | |
if not te.stoped then | |
layer:dispatchEvent(te) | |
end | |
if te.stoped then | |
e:stop() | |
end | |
table.removeElement(self._touchPoints, p) | |
end | |
---------------------------------------------------------------- | |
-- タッチした時のイベント処理を行います. | |
---------------------------------------------------------------- | |
function M:touchMoveHandler(e) | |
if not self:isEnabled() then | |
return | |
end | |
local layer = self._touchLayer | |
local p = getPointByEvent(self, e) | |
local te = table.copy(p, EVENT_TOUCH_MOVE) | |
if p.touchingProp then | |
eventHandle(self, te, p.touchingProp) | |
end | |
local o = layer:getPartition():propForPoint(p.x, p.y, 0) | |
if o and o ~= p.touchingProp then | |
eventHandle(self, te, o) | |
end | |
if not te.stoped then | |
layer:dispatchEvent(te) | |
end | |
if te.stoped then | |
e:stop() | |
end | |
end | |
---------------------------------------------------------------- | |
-- タッチした時のイベント処理を行います. | |
---------------------------------------------------------------- | |
function M:touchCancelHandler(e) | |
if not self:isEnabled() then | |
return | |
end | |
local layer = self._touchLayer | |
local p = getPointByEvent(self, e) | |
local te = table.copy(p, EVENT_TOUCH_CANCEL) | |
if p.touchingProp then | |
eventHandle(self, te, p.touchingProp) | |
end | |
local o = layer:propForPoint(p.x, p.y, 0) | |
if o and o ~= p.touchingProp then | |
eventHandle(self, te, o) | |
end | |
if not te.stoped then | |
layer:dispatchEvent(te) | |
end | |
if te.stoped then | |
e:stop() | |
end | |
table.removeElement(self._touchPoints, p) | |
end | |
return M end) | |
package.preload['hp/event/Event'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- The base class Event. <br> | |
-- Holds the data of the Event. <br> | |
-------------------------------------------------------------------------------- | |
local class = require("hp/lang/class") | |
local M = class() | |
M.OPEN = "open" | |
M.CLOSE = "close" | |
M.ACTIVATE = "activate" | |
M.DEACTIVATE = "deactivate" | |
M.DOWN = "down" | |
M.UP = "up" | |
M.MOVE = "move" | |
M.CLICK = "click" | |
M.CANCEL = "cancel" | |
M.KEY_DOWN = "keyDown" | |
M.KEY_UP = "keyUp" | |
M.COMPLETE = "complete" | |
M.TOUCH_DOWN = "touchDown" | |
M.TOUCH_UP = "touchUp" | |
M.TOUCH_MOVE = "touchMove" | |
M.TOUCH_CANCEL = "touchCancel" | |
M.BUTTON_DOWN = "buttonDown" | |
M.BUTTON_UP = "buttonUp" | |
M.MOVE_STARTED = "moveStarted" | |
M.MOVE_FINISHED = "moveFinished" | |
M.MOVE_COLLISION = "moveCollision" | |
M.COLLISION = "collision" | |
M.PRIORITY_MIN = 0 | |
M.PRIORITY_DEFAULT = 1000 | |
M.PRIORITY_MAX = 10000000 | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-- @param eventType (option)The type of event. | |
-------------------------------------------------------------------------------- | |
function M:init(eventType) | |
self.type = eventType | |
self.stoped = false | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the event listener by EventDispatcher. <br> | |
-- Please do not accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:setListener(callback, source) | |
self.callback = callback | |
self.source = source | |
end | |
-------------------------------------------------------------------------------- | |
--Stop the propagation of the event. | |
-------------------------------------------------------------------------------- | |
function M:stop() | |
self.stoped = true | |
end | |
return M end) | |
package.preload['hp/event/EventDispatcher'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This class is has a function of event notification. | |
-- | |
-------------------------------------------------------------------------------- | |
local class = require("hp/lang/class") | |
local Event = require("hp/event/Event") | |
local EventListener = require("hp/event/EventListener") | |
local M = class() | |
local EVENT_CACHE = {} | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-- @param eventType (option)The type of event. | |
-------------------------------------------------------------------------------- | |
function M:init() | |
self.eventlisteners = {} | |
end | |
-------------------------------------------------------------------------------- | |
-- Adds an event listener. <br> | |
-- will now catch the events that are sent in the dispatchEvent. <br> | |
-- @param eventType Target event type. | |
-- @param callback The callback function. | |
-- @param source (option)The first argument passed to the callback function. | |
-- @param priority (option)Notification order. | |
-------------------------------------------------------------------------------- | |
function M:addEventListener(eventType, callback, source, priority) | |
assert(eventType) | |
assert(callback) | |
if self:hasEventListener(eventType, callback, source) then | |
return false | |
end | |
local listener = EventListener(eventType, callback, source, priority) | |
for i, v in ipairs(self.eventlisteners) do | |
if listener.priority < v.priority then | |
table.insert(self.eventlisteners, i, listener) | |
return true | |
end | |
end | |
table.insert(self.eventlisteners, listener) | |
return true | |
end | |
-------------------------------------------------------------------------------- | |
-- Removes an event listener. | |
-------------------------------------------------------------------------------- | |
function M:removeEventListener(eventType, callback, source) | |
assert(eventType) | |
assert(callback) | |
for key, obj in ipairs(self.eventlisteners) do | |
if obj.type == eventType and obj.callback == callback and obj.source == source then | |
table.remove(self.eventlisteners, key) | |
return true | |
end | |
end | |
return false | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns true if you have an event listener. <br> | |
-- @return Returns true if you have an event listener. | |
-------------------------------------------------------------------------------- | |
function M:hasEventListener(eventType, callback, source) | |
assert(eventType) | |
for key, obj in ipairs(self.eventlisteners) do | |
if obj.type == eventType then | |
if callback or source then | |
if obj.callback == callback and obj.source == source then | |
return true | |
end | |
else | |
return true | |
end | |
end | |
end | |
return false | |
end | |
-------------------------------------------------------------------------------- | |
-- Dispatches the event. | |
-------------------------------------------------------------------------------- | |
function M:dispatchEvent(event, data) | |
local eventName = type(event) == "string" and event | |
if eventName then | |
event = EVENT_CACHE[eventName] or Event(eventName) | |
EVENT_CACHE[eventName] = nil | |
end | |
assert(event.type) | |
event.data = data or event.data | |
event.stoped = false | |
event.target = self.eventTarget or self | |
for key, obj in ipairs(self.eventlisteners) do | |
if obj.type == event.type then | |
event:setListener(obj.callback, obj.source) | |
obj:call(event) | |
if event.stoped == true then | |
break | |
end | |
end | |
end | |
if eventName then | |
EVENT_CACHE[eventName] = event | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Remove all event listeners. | |
-------------------------------------------------------------------------------- | |
function M:clearEventListeners() | |
self.eventlisteners = {} | |
end | |
return M end) | |
package.preload['hp/event/EventListener'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This class is an event listener. | |
-- Framework will be used internally. | |
-------------------------------------------------------------------------------- | |
local class = require("hp/lang/class") | |
local Event = require("hp/event/Event") | |
local M = class() | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-------------------------------------------------------------------------------- | |
function M:init(eventType, callback, source, priority) | |
self.type = eventType | |
self.callback = callback | |
self.source = source | |
self.priority = priority and priority or Event.PRIORITY_DEFAULT | |
end | |
-------------------------------------------------------------------------------- | |
-- Call source function | |
-------------------------------------------------------------------------------- | |
function M:call(event) | |
if self.source then | |
self.callback(self.source, event) | |
else | |
self.callback(event) | |
end | |
end | |
return M | |
end) | |
package.preload['hp/factory/SceneFactory'] = (function (...) | |
---------------------------------------------------------------- | |
-- Sceneを生成するファクトリークラスです. | |
-- SceneManagerにより使用されます. | |
---------------------------------------------------------------- | |
-- import | |
local Scene = require("hp/display/Scene") | |
-- class | |
local M = {} | |
--------------------------------------- | |
-- シーンを生成します. | |
-- この関数の動作を変更する事で、 | |
-- 任意のロジックでシーンを生成する事が可能です. | |
-- @param name シーン名です. | |
-- シーン名をもとに、モジュールを参照して、 | |
-- sceneHandlerを生成します. | |
-- ただし、params.handlerが指定された場合、 | |
-- そのhandlerを使用します. | |
-- @param params パラメータです. | |
-- sceneClassがある場合、同クラスを生成します. | |
-- handlerがある場合、sceneHandlerに設定されます. | |
--------------------------------------- | |
function M.createScene(name, params) | |
assert(name, "name is nil!") | |
local sceneClass = params.sceneClass or Scene | |
local scene = sceneClass:new() | |
scene.sceneHandler = params.handler or require(name) | |
scene.name = name | |
scene.sceneHandler.scene = scene | |
params.scene = scene | |
return scene | |
end | |
return M end) | |
package.preload['hp/gui/Button'] = (function (...) | |
---------------------------------------------------------------- | |
-- This class is a general button. | |
---------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local Event = require "hp/event/Event" | |
local Component = require "hp/gui/Component" | |
-- class define | |
local M = class(Component) | |
local super = Component | |
-- States | |
M.STATE_NORMAL = "normal" | |
M.STATE_SELECTED = "selected" | |
M.STATE_OVER = "over" | |
M.STATE_DISABLED = "disabled" | |
-- Events | |
M.EVENT_CLICK = "click" | |
M.EVENT_CANCEL = "cancel" | |
M.EVENT_BUTTON_UP = "buttonUp" | |
M.EVENT_BUTTON_DOWN = "buttonDown" | |
-------------------------------------------------------------------------------- | |
-- Initializes the internal variables. | |
-------------------------------------------------------------------------------- | |
function M:initInternal() | |
super.initInternal(self) | |
self._selected = false | |
self._touching = false | |
self._touchIndex = nil | |
self._toggle = false | |
self._themeName = "Button" | |
self._skinResizable = true | |
self._firstUpdated = false | |
end | |
-------------------------------------------------------------------------------- | |
-- Create a child objects. | |
-------------------------------------------------------------------------------- | |
function M:createChildren() | |
local skinClass = self:getStyle("skinClass") | |
self._skinClass = skinClass | |
self._background = skinClass(self:getStyle("skin")) | |
self._label = TextLabel() | |
self._label:setAlignment(MOAITextBox.CENTER_JUSTIFY, MOAITextBox.CENTER_JUSTIFY) | |
self._label:setSize(self._background:getSize()) | |
self:addChild(self._background) | |
self:addChild(self._label) | |
self:setSize(self._background:getSize()) | |
end | |
-------------------------------------------------------------------------------- | |
-- Update the display. | |
-------------------------------------------------------------------------------- | |
function M:updateDisplay() | |
local background = self._background | |
background:setColor(unpack(self:getStyle("skinColor"))) | |
background:setTexture(self:getStyle("skin")) | |
local label = self._label | |
label:setColor(unpack(self:getStyle("textColor"))) | |
label:setTextSize(self:getStyle("textSize")) | |
label:setFont(self:getStyle("font")) | |
if not self._skinResizable then | |
local tw, th = background.texture:getSize() | |
self:setSize(tw, th) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Up the button. | |
-- There is no need to call directly to the basic. | |
-- @param idx Touch index | |
-------------------------------------------------------------------------------- | |
function M:doUpButton() | |
if not self:isSelected() then | |
return | |
end | |
self._selected = false | |
self:setCurrentState(M.STATE_NORMAL) | |
self:dispatchEvent(M.EVENT_BUTTON_UP) | |
end | |
-------------------------------------------------------------------------------- | |
-- Down the button. | |
-- There is no need to call directly to the basic. | |
-------------------------------------------------------------------------------- | |
function M:doDownButton() | |
if self:isSelected() then | |
return | |
end | |
self._selected = true | |
self:setCurrentState(M.STATE_SELECTED) | |
self:dispatchEvent(M.EVENT_BUTTON_DOWN) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the text. | |
-- @param text text | |
-------------------------------------------------------------------------------- | |
function M:setText(text) | |
self._text = text | |
self._label:setText(text) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the text. | |
-- @param text text | |
-------------------------------------------------------------------------------- | |
function M:getText() | |
return self._text | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets whether a toggle button. | |
-- @param value toggle | |
-------------------------------------------------------------------------------- | |
function M:setToggle(value) | |
self._toggle = value | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns whether a toggle button. | |
-- @return toggle | |
-------------------------------------------------------------------------------- | |
function M:isToggle() | |
return self._toggle | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns whether the button is selected. | |
-- @return selected | |
-------------------------------------------------------------------------------- | |
function M:isSelected() | |
return self._selected | |
end | |
-------------------------------------------------------------------------------- | |
-- Set skin whether you can resize. | |
-------------------------------------------------------------------------------- | |
function M:setSkinResizable(value) | |
self._skinResizable = value | |
if not self._skinResizable then | |
self:invalidateDisplay() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the event listener that is called when the user click the button. | |
-- @param func click event handler | |
-------------------------------------------------------------------------------- | |
function M:setOnClick(func) | |
self:setEventListener(M.EVENT_CLICK, func) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the event listener that is called when the user pressed the button. | |
-- @param func button down event handler | |
-------------------------------------------------------------------------------- | |
function M:setOnButtonDown(func) | |
self:setEventListener(M.EVENT_BUTTON_DOWN, func) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the event listener that is called when the user released the button. | |
-- @param func button up event handler | |
-------------------------------------------------------------------------------- | |
function M:setOnButtonUp(func) | |
self:setEventListener(M.EVENT_BUTTON_UP, func) | |
end | |
-------------------------------------------------------------------------------- | |
-- Event Handler | |
-------------------------------------------------------------------------------- | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when touched. | |
-- @param e Touch Event | |
-------------------------------------------------------------------------------- | |
function M:touchDownHandler(e) | |
if self._touching then | |
return | |
end | |
e:stop() | |
self._touchIndex = e.idx | |
self._touching = true | |
if self:isToggle() and self:isButtonDown() then | |
self:doUpButton() | |
else | |
self:doDownButton() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when the button is released. | |
-- @param e Touch Event | |
-------------------------------------------------------------------------------- | |
function M:touchUpHandler(e) | |
if e.idx ~= self._touchIndex then | |
return | |
end | |
e:stop() | |
if self._touching and not self:isToggle() then | |
self._touching = false | |
self._touchIndex = nil | |
self:doUpButton() | |
self:dispatchEvent(M.EVENT_CLICK) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you move on the button. | |
-- @param e Touch Event | |
-------------------------------------------------------------------------------- | |
function M:touchMoveHandler(e) | |
if e.idx ~= self._touchIndex then | |
return | |
end | |
e:stop() | |
if self._touching and not self:hitTestWorld(e.x, e.y) then | |
self._touching = false | |
self._touchIndex = nil | |
if not self:isToggle() then | |
self:doUpButton() | |
self:dispatchEvent(M.EVENT_CANCEL) | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you move on the button. | |
-- @param e Touch Event | |
-------------------------------------------------------------------------------- | |
function M:touchCancelHandler(e) | |
if not self:isToggle() then | |
self._touching = false | |
self._touchIndex = nil | |
self:doUpButton() | |
self:dispatchEvent(M.EVENT_CANCEL) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when resizing. | |
-- @param e resize event | |
-------------------------------------------------------------------------------- | |
function M:resizeHandler(e) | |
local background = self._background | |
background:setSize(self:getWidth(), self:getHeight()) | |
local textPadding = self:getStyle("textPadding") | |
local paddingLeft, paddingTop, paddingRight, paddingBottom = unpack(textPadding) | |
local label = self._label | |
label:setSize(self:getWidth() - paddingLeft - paddingRight, self:getHeight() - paddingTop - paddingBottom) | |
label:setPos(paddingLeft, paddingTop) | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when the enabled state changes. | |
-- @param e event | |
-------------------------------------------------------------------------------- | |
function M:enabledChangedHandler(e) | |
if not self:isEnabled() then | |
self._touching = false | |
self._touchIndex = 0 | |
end | |
end | |
return M end) | |
package.preload['hp/gui/Component'] = (function (...) | |
---------------------------------------------------------------------------------------------------- | |
-- This class defines the common behavior of the GUI. | |
---------------------------------------------------------------------------------------------------- | |
-- imports | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local Group = require "hp/display/Group" | |
local Graphics = require "hp/display/Graphics" | |
local Event = require "hp/event/Event" | |
local Executors = require "hp/util/Executors" | |
local ThemeManager = require "hp/manager/ThemeManager" | |
local FocusManager = require "hp/manager/FocusManager" | |
local LayoutManager = require "hp/manager/LayoutManager" | |
-- class define | |
local super = Group | |
local M = class(super) | |
local MOAIPropInterface = MOAIProp.getInterfaceTable() | |
-- Events | |
M.EVENT_TOUCH_DOWN = "touchDown" | |
M.EVENT_TOUCH_MOVE = "touchMove" | |
M.EVENT_TOUCH_CANCEL = "touchCancel" | |
M.EVENT_TOUCH_UP = "touchUp" | |
M.EVENT_RESIZE = "resize" | |
M.EVENT_FOCUS_IN = "focusIn" | |
M.EVENT_FOCUS_OUT = "focusOut" | |
M.EVENT_ENABLED_CHANGED = "enabledChanged" | |
M.EVENT_STATE_CHANGED = "stateChanged" | |
M.EVENT_ADDED = "added" | |
M.EVENT_REMOVED = "removed" | |
M.EVENT_CHILD_ADDED = "childAdded" | |
M.EVENT_CHILD_REMOVED = "childRemoved" | |
-- States | |
M.STATE_NORMAL = "normal" | |
M.STATE_DISABLED = "disabled" | |
local function dummeyIsIncludeLayout() return false end | |
-------------------------------------------------------------------------------- | |
-- Constructor. | |
-- Please do not inherit this constructor. | |
-- Please have some template functions are inherited. | |
-- @param params Parameter table | |
-------------------------------------------------------------------------------- | |
function M:init(params) | |
super.init(self) | |
self:initInternal() | |
self:initEventListeners() | |
self:initComponent(params) | |
end | |
-------------------------------------------------------------------------------- | |
-- Initialization is the process of internal variables. | |
-- Please to inherit this function if the definition of the variable. | |
-------------------------------------------------------------------------------- | |
function M:initInternal() | |
self._enabled = true | |
self._theme = nil | |
self._themeName = "Component" | |
self._styles = {} | |
self._layout = nil | |
self._includeLayout = true | |
self._initialized = false | |
self._invalidDisplayFlag = false | |
self._invalidLayoutFlag = false | |
self._currentState = M.STATE_NORMAL | |
self._graphics = Graphics {parent = self} | |
self._graphics.isIncludeLayout = dummeyIsIncludeLayout | |
end | |
-------------------------------------------------------------------------------- | |
-- Performing the initialization processing of the event listener. | |
-- Please to inherit this function if you want to initialize the event listener. | |
-------------------------------------------------------------------------------- | |
function M:initEventListeners() | |
self:addEventListener(M.EVENT_TOUCH_DOWN, self.touchDownHandler, self) | |
self:addEventListener(M.EVENT_TOUCH_MOVE, self.touchMoveHandler, self) | |
self:addEventListener(M.EVENT_TOUCH_CANCEL, self.touchCancelHandler, self) | |
self:addEventListener(M.EVENT_TOUCH_UP, self.touchUpHandler, self) | |
self:addEventListener(M.EVENT_RESIZE, self.resizeHandler, self) | |
self:addEventListener(M.EVENT_STATE_CHANGED, self.stateChangedHandler, self) | |
self:addEventListener(M.EVENT_ENABLED_CHANGED, self.enabledChangedHandler, self) | |
end | |
-------------------------------------------------------------------------------- | |
-- Performing the initialization processing of the component. | |
-- Please to inherit this function if you want to change the behavior of the component. | |
-- @param params Parameter table | |
-------------------------------------------------------------------------------- | |
function M:initComponent(params) | |
if self._initialized then | |
return | |
end | |
self:initTheme(params) | |
self:initStyles(params) | |
self:createChildren() | |
self:copyParams(params) | |
self:invalidateAll() | |
self._initialized = true | |
end | |
-------------------------------------------------------------------------------- | |
-- Theme initialization process is performed. | |
-- @param params Parameter table | |
-------------------------------------------------------------------------------- | |
function M:initTheme(params) | |
if params and params.themeName then | |
if type(params.themeName) == "table" then | |
self:setThemeName(unpack(params.themeName)) | |
else | |
self:setThemeName(params.themeName) | |
end | |
end | |
local theme = ThemeManager:getComponentTheme(self:getThemeName()) or {} | |
self:setTheme(theme) | |
end | |
-------------------------------------------------------------------------------- | |
-- It is a component-specific style initialization process. | |
-- @param params Parameter table | |
-------------------------------------------------------------------------------- | |
function M:initStyles(params) | |
if params and params.styles then | |
if type(params.styles) == "table" then | |
self:setStyles(unpack(params.styles)) | |
else | |
self:setStyles(params.styles) | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- To create a child components. | |
-- Please be inherited as necessary. | |
-------------------------------------------------------------------------------- | |
function M:createChildren() | |
end | |
-------------------------------------------------------------------------------- | |
-- Scheduling the update process of the component. | |
-------------------------------------------------------------------------------- | |
function M:invalidateAll() | |
self:invalidateDisplay() | |
self:invalidateLayout() | |
end | |
-------------------------------------------------------------------------------- | |
-- Scheduling the process of updating the display. | |
-------------------------------------------------------------------------------- | |
function M:invalidateDisplay() | |
self._invalidDisplayFlag = true | |
LayoutManager:invalidateDisplay(self) | |
end | |
-------------------------------------------------------------------------------- | |
-- Scheduling the process of updating the layout. | |
-------------------------------------------------------------------------------- | |
function M:invalidateLayout() | |
local parent = self:getParent() | |
if parent and parent.isComponent then | |
parent:invalidateLayout() | |
end | |
LayoutManager:invalidateLayout(self) | |
self._invalidLayoutFlag = true | |
end | |
-------------------------------------------------------------------------------- | |
-- Validation of the component. | |
-- This process is heavy. | |
-- Use when you want to determine the size and layout of the component. | |
-------------------------------------------------------------------------------- | |
function M:validateAll() | |
self:validateDisplay() | |
self:validateLayout() | |
end | |
-------------------------------------------------------------------------------- | |
-- Validation of the display. | |
-- This process is heavy. | |
-- Use when you want to determine the size and layout of the component. | |
-------------------------------------------------------------------------------- | |
function M:validateDisplay(updateChildrenFlag) | |
if updateChildrenFlag then | |
for i, child in ipairs(self:getChildren()) do | |
if child.validateDisplay then | |
child:validateDisplay() | |
end | |
end | |
end | |
if self._invalidDisplayFlag then | |
self:updateDisplay() | |
self._invalidDisplayFlag = false | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Validation of the layout. | |
-- This process is heavy. | |
-- Use when you want to determine the size and layout of the component. | |
-- @param updateChildrenFlag Children are also updated | |
-------------------------------------------------------------------------------- | |
function M:validateLayout(updateChildrenFlag) | |
if updateChildrenFlag then | |
for i, child in ipairs(self:getChildren()) do | |
if child.validateLayout then | |
child:validateLayout() | |
end | |
end | |
end | |
if self._invalidLayoutFlag then | |
self:updateLayout() | |
self._invalidLayoutFlag = false | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Update the component. | |
-- You do not need to be called directly update process. | |
-------------------------------------------------------------------------------- | |
function M:updateComponent() | |
self:updateDisplay() | |
self:updateLayout() | |
end | |
-------------------------------------------------------------------------------- | |
-- Update the display. | |
-- This method is called at the time you need to update the display. | |
-------------------------------------------------------------------------------- | |
function M:updateDisplay() | |
end | |
-------------------------------------------------------------------------------- | |
-- Update the layout. | |
-------------------------------------------------------------------------------- | |
function M:updateLayout() | |
if self._layout then | |
self._layout:update(self) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Add the child component. | |
-- After adding performs scheduling of the layout. | |
-- @param child the child component | |
-------------------------------------------------------------------------------- | |
function M:addChild(child) | |
if super.addChild(self, child) then | |
child:dispatchEvent(M.EVENT_ADDED) | |
self:dispatchEvent(M.EVENT_CHILD_ADDED) | |
self:invalidateLayout() | |
return true | |
end | |
return false | |
end | |
-------------------------------------------------------------------------------- | |
-- Remove the child component. | |
-- @param child the child component | |
-------------------------------------------------------------------------------- | |
function M:removeChild(child) | |
if child == self._graphics then | |
return false | |
end | |
if super.removeChild(self, child) then | |
child:dispatchEvent(M.EVENT_REMOVED) | |
self:dispatchEvent(M.EVENT_CHILD_REMOVED) | |
self:invalidateLayout() | |
return true | |
end | |
return false | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the state of the component. | |
-- To update the display by the state. | |
-- @param state state | |
-------------------------------------------------------------------------------- | |
function M:setCurrentState(state) | |
if self:getCurrentState() ~= state then | |
self._currentState = state | |
local e = Event(M.EVENT_STATE_CHANGED) | |
e.state = state | |
self:dispatchEvent(e) | |
self:invalidateDisplay() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the state of the component. | |
-- @return state | |
-------------------------------------------------------------------------------- | |
function M:getCurrentState() | |
return self._currentState | |
end | |
-------------------------------------------------------------------------------- | |
-- The function to be performed asynchronously. | |
-- @param func function | |
-- @param ... args | |
-------------------------------------------------------------------------------- | |
function M:callLater(func, ...) | |
Executors.callLater(func, ...) | |
end | |
---------------------------------------------------------------------------------------------------- | |
-- Properties | |
---------------------------------------------------------------------------------------------------- | |
-------------------------------------------------------------------------------- | |
-- Set the enabled state. | |
-- @param value enabled | |
-------------------------------------------------------------------------------- | |
function M:setEnabled(value) | |
if self:isEnabled() ~= value then | |
self._enabled = value | |
self:dispatchEvent(M.EVENT_ENABLED_CHANGED) | |
if value then | |
self:setCurrentState(M.STATE_NORMAL) | |
else | |
self:setCurrentState(M.STATE_DISABLED) | |
end | |
self:invalidateDisplay() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the enabled. | |
-- @return enabled | |
-------------------------------------------------------------------------------- | |
function M:isEnabled() | |
return self._enabled | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns whether the component can touch. | |
-------------------------------------------------------------------------------- | |
function M:isTouchEnabled() | |
return self._touchEnabled and self._enabled | |
end | |
-------------------------------------------------------------------------------- | |
-- To set the focus. | |
-- TODO:Focus does not function. | |
-- @param value focus | |
-------------------------------------------------------------------------------- | |
function M:setFocus(value) | |
value = value or true | |
local focusManager = self:getFocusManager() | |
if focusManager then | |
focusManager:setFocus(value and self or nil) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- If the component has the focus, returns true. | |
-- TODO:Focus does not function. | |
-- @return focus | |
-------------------------------------------------------------------------------- | |
function M:isFocus() | |
local focusManager = self:getFocusManager() | |
if focusManager then | |
return focusManager:getFocus() == self | |
end | |
return false | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the FocusManager | |
-- TODO:Focus does not function. | |
-------------------------------------------------------------------------------- | |
function M:getFocusManager() | |
return FocusManager | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the focus enabled. | |
-- TODO:Focus does not function. | |
-- @return focus enabled | |
-------------------------------------------------------------------------------- | |
function M:isFocusEnabled() | |
return self._focusEnabled | |
end | |
-------------------------------------------------------------------------------- | |
-- Set whether you can set focus. | |
-- @param Whether you can set focus | |
-------------------------------------------------------------------------------- | |
function M:setFocusEnabled(value) | |
self._focusEnabled = value | |
if value == false and self:isFocus() then | |
self:getFocusManager():setFocus(nil) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the layout. | |
-- When you set the layout, the update process of layout class is called when resizing. | |
-- The position of the component is automatically updated. | |
-- @param value layout object | |
-------------------------------------------------------------------------------- | |
function M:setLayout(value) | |
self._layout = value | |
self:invalidateLayout() | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns a layout. | |
-- @return layout object | |
-------------------------------------------------------------------------------- | |
function M:getLayout() | |
return self._layout | |
end | |
-------------------------------------------------------------------------------- | |
-- Set whether you want to update the position by the layout class. | |
-------------------------------------------------------------------------------- | |
function M:setIncludeLayout(value) | |
self._includeLayout = value | |
self:invalidateLayout() | |
end | |
-------------------------------------------------------------------------------- | |
-- Return whether or not to set the layout automatically. | |
-------------------------------------------------------------------------------- | |
function M:isIncludeLayout() | |
return self._includeLayout | |
end | |
-------------------------------------------------------------------------------- | |
-- Change the size of the component. | |
-- Not be reflected in all objects immediately after the change. | |
-- be reflected to call updateSize. | |
-- @param width width | |
-- @param height height | |
-------------------------------------------------------------------------------- | |
function M:setSize(width, height) | |
width = width < 0 and 0 or width | |
height = height < 0 and 0 or height | |
local oldWidth, oldHeight = self:getWidth(), self:getHeight() | |
if oldWidth ~= width or oldHeight ~= height then | |
super.setSize(self, width, height) | |
local e = Event(M.EVENT_RESIZE) | |
e.oldWidth, e.oldHeight = oldWidth, oldHeight | |
e.newWidth, e.newHeight = width, height | |
self:dispatchEvent(e) | |
self:invalidateDisplay() | |
self:invalidateLayout() | |
self._graphics:setSize(width, height) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the theme of the component. | |
-- @return theme | |
-------------------------------------------------------------------------------- | |
function M:getTheme() | |
return self._theme | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the theme of the component. | |
-- @param value theme | |
-------------------------------------------------------------------------------- | |
function M:setTheme(value) | |
if self._theme ~= value then | |
self._theme = value | |
self:invalidateDisplay() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the name of the theme of the component. | |
-- @return theme name | |
-------------------------------------------------------------------------------- | |
function M:getThemeName() | |
return self._themeName | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the name of the theme of the component. | |
-- @param value theme name | |
-------------------------------------------------------------------------------- | |
function M:setThemeName(value) | |
if self._themeName ~= value then | |
self._themeName = value | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the component has all the styles. | |
-- @param styles styles | |
-------------------------------------------------------------------------------- | |
function M:setStyles(styles) | |
if self._styles ~= styles then | |
self._styles = assert(styles) | |
self:invalidateDisplay() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the style of the current state. | |
-- @param name style name | |
-- @param state (option)state name | |
-------------------------------------------------------------------------------- | |
function M:getStyle(name, state) | |
state = state or self:getCurrentState() | |
local theme = self:getTheme() | |
local componentStyles = self._styles[state] | |
local currentStyles = theme[state] | |
local normalStyles = theme["normal"] | |
if componentStyles and componentStyles[name] ~= nil then | |
return componentStyles[name] | |
end | |
if currentStyles and currentStyles[name] ~= nil then | |
return currentStyles[name] | |
end | |
if normalStyles and normalStyles[name] ~= nil then | |
return normalStyles[name] | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the style of the component. | |
-- @param state state name | |
-- @param name style name | |
-- @param value style value | |
-------------------------------------------------------------------------------- | |
function M:setStyle(state, name, value) | |
self._styles[state] = self._styles[state] or {} | |
local stateStyles = self._styles[state] | |
stateStyles[name] = value | |
self:invalidateDisplay() | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the event listener. | |
-- Event listener that you set in this function is one. | |
-- @param eventName event name | |
-- @param func event listener | |
-------------------------------------------------------------------------------- | |
function M:setEventListener(eventName, func) | |
local propertyName = "_event_" .. eventName | |
if self[propertyName] == func then | |
return | |
end | |
if self[propertyName] then | |
self:removeEventListener(eventName, self[propertyName]) | |
end | |
self[propertyName] = func | |
if self[propertyName] then | |
self:addEventListener(eventName, self[propertyName]) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- It is a function to determine whether the component. | |
-- @return true | |
-------------------------------------------------------------------------------- | |
function M:isComponent() | |
return true | |
end | |
---------------------------------------------------------------------------------------------------- | |
-- Event Handler | |
---------------------------------------------------------------------------------------------------- | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you touch the component. | |
-- @param e touch event | |
-------------------------------------------------------------------------------- | |
function M:touchDownHandler(e) | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you touch the component. | |
-- @param e touch event | |
-------------------------------------------------------------------------------- | |
function M:touchUpHandler(e) | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you touch the component. | |
-- @param e touch event | |
-------------------------------------------------------------------------------- | |
function M:touchMoveHandler(e) | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you touch the component. | |
-- @param e touch event | |
-------------------------------------------------------------------------------- | |
function M:touchCancelHandler(e) | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when resizing. | |
-- @param e resize event | |
-------------------------------------------------------------------------------- | |
function M:resizeHandler(e) | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when the state changes. | |
-- @param e event | |
-------------------------------------------------------------------------------- | |
function M:stateChangedHandler(e) | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when the enabled state changes. | |
-- @param e event | |
-------------------------------------------------------------------------------- | |
function M:enabledChangedHandler(e) | |
end | |
return M end) | |
package.preload['hp/gui/DialogBox'] = (function (...) | |
---------------------------------------------------------------- | |
-- This is the class that displays a message in the panel. | |
---------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local NinePatch = require "hp/display/NinePatch" | |
local TextLabel = require "hp/display/TextLabel" | |
local Animation = require "hp/display/Animation" | |
local Event = require "hp/event/Event" | |
local Component = require "hp/gui/Component" | |
local Panel = require "hp/gui/Panel" | |
-- class | |
local M = class(Panel) | |
local super = Panel | |
-- Events | |
M.EVENT_MESSAGE_SHOW = "messageShow" | |
M.EVENT_MESSAGE_END = "messageEnd" | |
M.EVENT_MESSAGE_HIDE = "messageHide" | |
M.EVENT_MESSAGE_RESULT = "messageResult" | |
-- Types | |
M.TYPE_INFO = "Info" | |
M.TYPE_CONFIRM = "Confirm" | |
M.TYPE_WARNING = "Warning" | |
M.TYPE_ERROR = "Error" | |
-------------------------------------------------------------------------------- | |
-- Initializes the internal variables. | |
-------------------------------------------------------------------------------- | |
function M:initInternal() | |
super.initInternal(self) | |
self._themeName = "DialogBox" | |
self._messageHideEnabled = false | |
self._spoolingEnabled = false | |
self._existingButtons = {} | |
self._title = "Message title" | |
self._text = "Message text" | |
self._type = M.TYPE_INFO | |
self._popInAnimation = Animation():parallel( | |
Animation(self, 0.25):setScl(0.8, 0.8, 1):seekScl(1, 1, 1), | |
Animation(self, 0.25):setColor(0, 0, 0, 0):seekColor(1, 1, 1, 1) | |
) | |
self._popOutAnimation = Animation():parallel( | |
Animation(self, 0.25):seekScl(0.8, 0.8, 1), | |
Animation(self, 0.25):seekColor(0, 0, 0, 0) | |
) | |
end | |
-------------------------------------------------------------------------------- | |
-- Create a child objects. | |
-------------------------------------------------------------------------------- | |
function M:createChildren() | |
super.createChildren(self) | |
self._titleLabel = TextLabel(self._title) | |
self:addChild(self._titleLabel) | |
self._typeIcon = Sprite(self:getStyle("icon" .. self._type)) | |
self:addChild(self._typeIcon) | |
self._textLabel = TextLabel(self._text) | |
self._textLabel:setWordBreak(MOAITextBox.WORD_BREAK_CHAR) | |
self:addChild(self._textLabel) | |
self:setColor(0, 0, 0, 0) | |
end | |
-------------------------------------------------------------------------------- | |
-- Update the display. | |
-------------------------------------------------------------------------------- | |
function M:updateDisplay() | |
super.updateDisplay(self) | |
-- create requested buttons | |
for _,v in ipairs(self._existingButtons) do | |
self:removeChild(v) | |
v:dispose() | |
end | |
self._existingButtons = {} | |
if not self._buttons then | |
self._buttons = {"OK"} | |
end | |
for i,v in ipairs(self._buttons) do | |
local btn = Button { | |
parent=self, | |
text=v, | |
onClick = function() | |
self:hide() | |
local e = Event(M.EVENT_MESSAGE_RESULT) | |
e.result = v | |
e.resultIndex = i | |
self:dispatchEvent(e) | |
end, | |
} | |
table.insert(self._existingButtons, btn) | |
end | |
-- calculate buttons width | |
local bLeft, bTop, bRight, bBottom = unpack(self:getStyle("buttonsPadding")) | |
local bw = 0 | |
local bh = 0 | |
for _,v in ipairs(self._existingButtons) do | |
bw = bw + v:getWidth() + bLeft + bRight | |
bh = v:getHeight() > bh and v:getHeight() or bh | |
end | |
-- adjust button size if total exceeds size of dialog | |
local allowedButtonsWidth = self:getWidth() - bLeft - bRight | |
if bw >= allowedButtonsWidth then | |
bw = allowedButtonsWidth | |
local bwidth = (bw / #self._existingButtons) - bLeft - bRight | |
for _,v in ipairs(self._existingButtons) do | |
v:setSize(bwidth, bh) | |
end | |
end | |
local tLeft, tTop, tRight, tBottom = unpack(self:getStyle("titlePadding")) | |
self._titleLabel:fitSize() | |
self._titleLabel:setSize(self:getWidth() - tLeft - tRight, self._titleLabel:getHeight()) | |
self._titleLabel:setPos(tLeft, tTop) | |
self._titleLabel:setAlign("center", "center") | |
self._titleLabel:setColor(unpack(self:getStyle("titleColor"))) | |
self._titleLabel:setTextSize(self:getStyle("titleSize")) | |
self._titleLabel:setFont(self:getStyle("titleFont")) | |
local yoff = tTop + self._titleLabel:getHeight() + tBottom | |
local iLeft, iTop, iRight, iBottom = unpack(self:getStyle("iconPadding")) | |
self._typeIcon:setTexture(self:getStyle("icon" .. (self._type or M.ICON_INFO))) | |
local iw, ih = self._typeIcon:getSize() | |
local iconScaleFactor = self:getStyle("iconScaleFactor") or 1 | |
if iconScaleFactor ~= 1 then | |
iw = iw * iconScaleFactor | |
ih = ih * iconScaleFactor | |
self._typeIcon:setSize(iw, ih) | |
end | |
self._typeIcon:setPos(iLeft, yoff + iTop) | |
local pLeft, pTop, pRight, pBottom = unpack(self:getStyle("textPadding")) | |
local tWidth = self:getWidth() - iLeft - iw - iRight - pLeft - pRight | |
local tHeight = self:getHeight() - yoff - pTop - pBottom - bh - bTop - bBottom | |
self._textLabel:setSize(tWidth, tHeight) | |
self._textLabel:setPos(iLeft + iw + iRight + pLeft, yoff + pTop) | |
self._textLabel:setAlign("left", "top") | |
self._textLabel:setColor(unpack(self:getStyle("textColor"))) | |
self._textLabel:setTextSize(self:getStyle("textSize")) | |
self._textLabel:setFont(self:getStyle("font")) | |
yoff = yoff + pTop + tHeight + pBottom | |
local xoff = (self:getWidth() - bw) * 0.5 | |
for _,v in ipairs(self._existingButtons) do | |
v:setPos(xoff + bLeft, yoff + bTop) | |
xoff = xoff + bLeft + bRight + v:getWidth() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Turns spooling ON or OFF. | |
-- If self is currently spooling and enable is false, stop spooling and reveal | |
-- entire page. | |
-- @param enable Boolean for new state | |
-- @return none | |
------------------------------------------------------------------------------- | |
function M:spoolingEnabled(enable) | |
self._spoolingEnabled = enable and true or false | |
if self._spoolingEnabled == false and self:isBusy() then | |
self._textLabel:stop() | |
self._textLabel:revealAll() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Displays a message box in the pop-up effect. | |
-------------------------------------------------------------------------------- | |
function M:show() | |
self:setVisible(true) | |
self:setCenterPiv() | |
self:setTitle(self:getTitle()) | |
self:setText(self:getText()) | |
if self._spoolingEnabled then | |
self._textLabel:setReveal(0) | |
end | |
self._popInAnimation:play {onComplete = | |
function() | |
if self._spoolingEnabled then | |
self:spool() | |
end | |
self:dispatchEvent(M.EVENT_MESSAGE_SHOW) | |
end | |
} | |
end | |
-------------------------------------------------------------------------------- | |
-- To hide the message box in the pop-up effect. | |
-------------------------------------------------------------------------------- | |
function M:hide() | |
if self._popInAnimation:isRunning() then | |
return | |
end | |
self._popOutAnimation:play {onComplete = | |
function() | |
self:setVisible(false) | |
self:dispatchEvent(M.EVENT_MESSAGE_HIDE) | |
end | |
} | |
end | |
-------------------------------------------------------------------------------- | |
-- Spools the text. | |
-------------------------------------------------------------------------------- | |
function M:spool() | |
self:spoolingEnabled(true) | |
return self._textLabel:spool() | |
end | |
-------------------------------------------------------------------------------- | |
-- Displays the next page. | |
-------------------------------------------------------------------------------- | |
function M:nextPage() | |
return self._textLabel:nextPage() | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the next page if exists. | |
-- @return If the next page there is a true | |
-------------------------------------------------------------------------------- | |
function M:more() | |
return self._textLabel:more() | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns in the process whether messages are displayed. | |
-- @return busy | |
-------------------------------------------------------------------------------- | |
function M:isBusy() | |
return self._textLabel:isBusy() | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the type. | |
-- @param type type | |
-------------------------------------------------------------------------------- | |
function M:setType(typ) | |
self._type = typ | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the type | |
-- @return type | |
-------------------------------------------------------------------------------- | |
function M:getType() | |
return self._type | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the type. | |
-- @param type type | |
-------------------------------------------------------------------------------- | |
function M:setButtons(...) | |
self._buttons = {...} | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the type | |
-- @return type | |
-------------------------------------------------------------------------------- | |
function M:getButtons() | |
return self._buttons | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the title. | |
-- @param title title | |
-------------------------------------------------------------------------------- | |
function M:setTitle(title) | |
self._title = title | |
self._titleLabel:setText(title) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the title | |
-- @return title | |
-------------------------------------------------------------------------------- | |
function M:getTitle() | |
return self._title | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the text. | |
-- @param text text | |
-------------------------------------------------------------------------------- | |
function M:setText(text) | |
self._text = text | |
self._textLabel:setText(text) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the text. | |
-- @return text | |
-------------------------------------------------------------------------------- | |
function M:getText() | |
return self._text | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the color of the text. | |
-- @param r red | |
-- @param g green | |
-- @param b blue | |
-- @param a alpha | |
-------------------------------------------------------------------------------- | |
function M:setTextColor(r, g, b, a) | |
self:setStyle(M.STATE_NORMAL, "textColor", {r, g, b, a}) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the size of the text. | |
-- @param points points | |
-------------------------------------------------------------------------------- | |
function M:setTextSize(points) | |
self:setStyle(M.STATE_NORMAL, "textSize", points) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the event listener was called to display a message box. | |
-- @param func event listener | |
-------------------------------------------------------------------------------- | |
function M:setOnMessageShow(func) | |
self:setEventListener(M.EVENT_MESSAGE_SHOW, func) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the event listener was called to hide a message box. | |
-- @param func event listener | |
-------------------------------------------------------------------------------- | |
function M:setOnMessageHide(func) | |
self:setEventListener(M.EVENT_MESSAGE_HIDE, func) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the event listener was called to end a message box. | |
-- @param func event listener | |
-------------------------------------------------------------------------------- | |
function M:setOnMessageEnd(func) | |
self:setEventListener(M.EVENT_MESSAGE_END, func) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the event listener was called to end a message box. | |
-- @param func event listener | |
-------------------------------------------------------------------------------- | |
function M:setOnMessageResult(func) | |
self:setEventListener(M.EVENT_MESSAGE_RESULT, func) | |
end | |
---------------------------------------------------------------------------------------------------- | |
-- Event Handler | |
---------------------------------------------------------------------------------------------------- | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you touch the component. | |
-- @param e touch event | |
-------------------------------------------------------------------------------- | |
function M:touchDownHandler(e) | |
if self:isBusy() then | |
self._textLabel:stop() | |
self._textLabel:revealAll() | |
elseif self:more() then | |
self:nextPage() | |
if self._spoolingEnabled then | |
self:spool() | |
end | |
else | |
self:enterMessageEnd() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- This is called when a message has been completed. | |
-------------------------------------------------------------------------------- | |
function M:enterMessageEnd() | |
self:dispatchEvent(M.EVENT_MESSAGE_END) | |
if self._messageHideEnabled then | |
self:hide() | |
end | |
end | |
return M end) | |
package.preload['hp/gui/Joystick'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- Joystick is a virtual controller. | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local Sprite = require "hp/display/Sprite" | |
local Group = require "hp/display/Group" | |
local Event = require "hp/event/Event" | |
local Component = require "hp/gui/Component" | |
-- class define | |
local M = class(Component) | |
local super = Component | |
-- Events | |
M.EVENT_STICK_CHANGED = "stickChanged" | |
-- constraints | |
M.STICK_CENTER = "center" | |
M.STICK_LEFT = "left" | |
M.STICK_TOP = "top" | |
M.STICK_RIGHT = "right" | |
M.STICK_BOTTOM = "bottom" | |
M.MODE_ANALOG = "analog" | |
M.MODE_DIGITAL = "digital" | |
M.RANGE_OF_CENTER_RATE = 0.5 | |
-------------------------------------------------------------------------------- | |
-- Initializes the internal variables. | |
-------------------------------------------------------------------------------- | |
function M:initInternal() | |
super.initInternal(self) | |
self._touchDownFlag = false | |
self._rangeOfCenterRate = M.RANGE_OF_CENTER_RATE | |
self._stickMode = M.MODE_ANALOG | |
self._changedEvent = Event(M.EVENT_STICK_CHANGED) | |
self._themeName = "Joystick" | |
end | |
-------------------------------------------------------------------------------- | |
-- Create a child objects. | |
-------------------------------------------------------------------------------- | |
function M:createChildren() | |
local baseSkin = self:getStyle("baseSkin") | |
local knobSkin = self:getStyle("knobSkin") | |
self._baseSprite = Sprite {texture = baseSkin, left = 0, top = 0} | |
self._knobSprite = Sprite {texture = knobSkin, left = 0, top = 0} | |
self:addChild(self._baseSprite) | |
self:addChild(self._knobSprite) | |
self:setSize(self._baseSprite:getSize()) | |
self:setCenterKnob() | |
end | |
-------------------------------------------------------------------------------- | |
-- Update the display. | |
-------------------------------------------------------------------------------- | |
function M:updateDisplay() | |
self._baseSprite:setColor(unpack(self:getStyle("baseColor"))) | |
self._baseSprite:setTexture(self:getStyle("baseSkin")) | |
self._knobSprite:setColor(unpack(self:getStyle("knobColor"))) | |
self._knobSprite:setTexture(self:getStyle("knobSkin")) | |
self:setSize(self._baseSprite:getSize()) | |
end | |
-------------------------------------------------------------------------------- | |
-- To update the position of the knob. | |
-- @param x The x-position of the knob | |
-- @param y The y-position of the knob | |
-------------------------------------------------------------------------------- | |
function M:updateKnob(x, y) | |
local oldX, oldY = self._knobSprite:getLoc() | |
local newX, newY = self:getKnobNewLoc(x, y) | |
-- change loc | |
if oldX ~= newX or oldY ~= newY then | |
self._knobSprite:setLoc(newX, newY, 0) | |
local event = self._changedEvent | |
event.oldX, event.oldY = self:getKnobInputRate(oldX, oldY) | |
event.newX, event.newY = self:getKnobInputRate(newX, newY) | |
event.direction = self:getStickDirection() | |
event.down = self._touchDownFlag | |
self:dispatchEvent(event) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the position of the center of the knob. | |
-------------------------------------------------------------------------------- | |
function M:setCenterKnob() | |
local cx, cy = self:getWidth() / 2, self:getHeight() / 2 | |
self._knobSprite:setLoc(cx, cy, 0) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the position of the center of the whole. | |
-- Does not depend on the Pivot. | |
-- @return Center x-position | |
-- @return Center y-position | |
-------------------------------------------------------------------------------- | |
function M:getCenterLoc() | |
return self:getWidth() / 2, self:getHeight() / 2 | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the position that matches the mode of the stick. | |
-- @param x X-position of the model | |
-- @param y Y-position of the model | |
-- @return adjusted x-position | |
-- @return adjusted y-position | |
-------------------------------------------------------------------------------- | |
function M:getKnobNewLoc(x, y) | |
if self:getStickMode() == M.MODE_ANALOG then | |
return self:getKnobNewLocForAnalog(x, y) | |
else | |
return self:getKnobNewLocForDigital(x, y) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the position to match the analog mode. | |
-- @param x X-position of the model | |
-- @param y Y-position of the model | |
-- @return adjusted x-position | |
-- @return adjusted y-position | |
-------------------------------------------------------------------------------- | |
function M:getKnobNewLocForAnalog(x, y) | |
local cx, cy = self:getCenterLoc() | |
local rx, ry = (x - cx), (y - cy) | |
local radian = math.atan2(math.abs(ry), math.abs(rx)) | |
local maxX, maxY = math.cos(radian) * cx + cx, math.sin(radian) * cy + cy | |
local minX, minY = -math.cos(radian) * cx + cx, -math.sin(radian) * cy + cy | |
x = x < minX and minX or x | |
x = x > maxX and maxX or x | |
y = y < minY and minY or y | |
y = y > maxY and maxY or y | |
return x, y | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the position to match the digital mode. | |
-- @param x X-position of the model | |
-- @param y Y-position of the model | |
-- @return adjusted x-position | |
-- @return adjusted y-position | |
-------------------------------------------------------------------------------- | |
function M:getKnobNewLocForDigital(x, y) | |
local cx, cy = self:getCenterLoc() | |
local rx, ry = (x - cx), (y - cy) | |
local radian = math.atan2(math.abs(ry), math.abs(rx)) | |
local minX, minY = 0, 0 | |
local maxX, maxY = self:getWidth(), self:getHeight() | |
local cRate = self._rangeOfCenterRate | |
local cMinX, cMinY = cx - cx * cRate, cy - cy * cRate | |
local cMaxX, cMaxY = cx + cx * cRate, cy + cy * cRate | |
if cMinX < x and x < cMaxX and cMinY < y and y < cMaxY then | |
x = cx | |
y = cy | |
elseif math.cos(radian) > math.sin(radian) then | |
x = x < cx and minX or maxX | |
y = cy | |
else | |
x = cx | |
y = y < cy and minY or maxY | |
end | |
return x, y | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the percentage of input. | |
-- @param x X-position | |
-- @param y Y-position | |
-- @return X-ratio(-1 <= x <= 1) | |
-- @return Y-ratio(-1 <= y <= 1) | |
-------------------------------------------------------------------------------- | |
function M:getKnobInputRate(x, y) | |
local cx, cy = self:getCenterLoc() | |
local rateX, rateY = (x - cx) / cx, (y - cy) / cy | |
return rateX, rateY | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the direction of the stick. | |
-- @return direction | |
-------------------------------------------------------------------------------- | |
function M:getStickDirection() | |
local x, y = self._knobSprite:getLoc() | |
local cx, cy = self:getCenterLoc() | |
local radian = math.atan2(math.abs(x - cx), math.abs(y - cy)) | |
local dir | |
if x == cx and y == cy then | |
dir = M.STICK_CENTER | |
elseif math.cos(radian) < math.sin(radian) then | |
dir = x < cx and M.STICK_LEFT or M.STICK_RIGHT | |
else | |
dir = y < cy and M.STICK_TOP or M.STICK_BOTTOM | |
end | |
return dir | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the stick mode | |
-- @return stick mode | |
-------------------------------------------------------------------------------- | |
function M:getStickMode() | |
return self._stickMode | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the mode of the stick. | |
-- @param mode mode("analog" or "digital") | |
-------------------------------------------------------------------------------- | |
function M:setStickMode(value) | |
self._stickMode = value | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when touched. | |
-- @param e Touch Event | |
-------------------------------------------------------------------------------- | |
function M:setOnStickChanged(func) | |
self:setEventListener(M.EVENT_STICK_CHANGED, func) | |
end | |
-------------------------------------------------------------------------------- | |
-- Event Handler. | |
-------------------------------------------------------------------------------- | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when touched. | |
-- @param e Touch Event | |
-------------------------------------------------------------------------------- | |
function M:touchDownHandler(e) | |
if self._touchDownFlag then | |
return | |
end | |
local mx, my = self:worldToModel(e.x, e.y, 0) | |
self._touchDownFlag = true | |
self._touchIndex = e.idx | |
self:updateKnob(mx, my) | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when the button is released. | |
-- @param e Touch Event | |
-------------------------------------------------------------------------------- | |
function M:touchUpHandler(e) | |
if not self._touchDownFlag then | |
return | |
end | |
if e.idx ~= self._touchIndex then | |
return | |
end | |
self._touchDownFlag = false | |
local cx, cy = self:getCenterLoc() | |
self:updateKnob(cx, cy) | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you move on the button. | |
-- @param e Touch Event | |
-------------------------------------------------------------------------------- | |
function M:touchMoveHandler(e) | |
if not self._touchDownFlag then | |
return | |
end | |
if e.idx ~= self._touchIndex then | |
return | |
end | |
local wx, wy = e.x, e.y | |
local mx, my = self:worldToModel(wx, wy, 0) | |
self:updateKnob(mx, my) | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you move on the button. | |
-- @param e Touch Event | |
-------------------------------------------------------------------------------- | |
function M:touchCancelHandler(e) | |
self._touchDownFlag = false | |
self:setCenterKnob() | |
end | |
return M end) | |
package.preload['hp/gui/MessageBox'] = (function (...) | |
---------------------------------------------------------------- | |
-- This is the class that displays a message in the panel. | |
---------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local NinePatch = require "hp/display/NinePatch" | |
local TextLabel = require "hp/display/TextLabel" | |
local Animation = require "hp/display/Animation" | |
local Event = require "hp/event/Event" | |
local Component = require "hp/gui/Component" | |
local Panel = require "hp/gui/Panel" | |
-- class | |
local M = class(Panel) | |
local super = Panel | |
-- Events | |
M.EVENT_MESSAGE_SHOW = "messageShow" | |
M.EVENT_MESSAGE_END = "messageEnd" | |
M.EVENT_MESSAGE_HIDE = "messageHide" | |
-------------------------------------------------------------------------------- | |
-- Initializes the internal variables. | |
-------------------------------------------------------------------------------- | |
function M:initInternal() | |
super.initInternal(self) | |
self._themeName = "MessageBox" | |
self._messageHideEnabled = true | |
self._spoolingEnabled = true | |
self._popInAnimation = Animation():parallel( | |
Animation(self, 0.5):setScl(0.8, 0.8, 1):seekScl(1, 1, 1), | |
Animation(self, 0.5):setColor(0, 0, 0, 0):seekColor(1, 1, 1, 1) | |
) | |
self._popOutAnimation = Animation():parallel( | |
Animation(self, 0.5):seekScl(0.8, 0.8, 1), | |
Animation(self, 0.5):seekColor(0, 0, 0, 0) | |
) | |
end | |
-------------------------------------------------------------------------------- | |
-- Create a child objects. | |
-------------------------------------------------------------------------------- | |
function M:createChildren() | |
super.createChildren(self) | |
self._textLabel = TextLabel() | |
self._textLabel:setWordBreak(MOAITextBox.WORD_BREAK_CHAR) | |
self:addChild(self._textLabel) | |
self:setColor(0, 0, 0, 0) | |
end | |
-------------------------------------------------------------------------------- | |
-- Update the display. | |
-------------------------------------------------------------------------------- | |
function M:updateDisplay() | |
super.updateDisplay(self) | |
local pLeft, pTop, pRight, pBottom = unpack(self:getStyle("textPadding")) | |
local tWidth = self:getWidth() - pLeft - pRight | |
local tHeight = self:getHeight() - pTop - pBottom | |
self._textLabel:setSize(tWidth, tHeight) | |
self._textLabel:setPos(pLeft, pTop) | |
self._textLabel:setColor(unpack(self:getStyle("textColor"))) | |
self._textLabel:setTextSize(self:getStyle("textSize")) | |
self._textLabel:setFont(self:getStyle("font")) | |
end | |
-------------------------------------------------------------------------------- | |
-- Turns spooling ON or OFF. | |
-- If self is currently spooling and enable is false, stop spooling and reveal | |
-- entire page. | |
-- @param enable Boolean for new state | |
-- @return none | |
------------------------------------------------------------------------------- | |
function M:spoolingEnabled(enable) | |
self._spoolingEnabled = enable and true or false | |
if self._spoolingEnabled == false and self:isBusy() then | |
self._textLabel:stop() | |
self._textLabel:revealAll() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Displays a message box in the pop-up effect. | |
-------------------------------------------------------------------------------- | |
function M:show() | |
self:setVisible(true) | |
self:setCenterPiv() | |
self:setText(self:getText()) | |
if self._spoolingEnabled then | |
self._textLabel:setReveal(0) | |
end | |
self._popInAnimation:play {onComplete = | |
function() | |
if self._spoolingEnabled then | |
self:spool() | |
end | |
self:dispatchEvent(M.EVENT_MESSAGE_SHOW) | |
end | |
} | |
end | |
-------------------------------------------------------------------------------- | |
-- To hide the message box in the pop-up effect. | |
-------------------------------------------------------------------------------- | |
function M:hide() | |
if self._popInAnimation:isRunning() then | |
return | |
end | |
self._popOutAnimation:play {onComplete = | |
function() | |
self:setVisible(false) | |
self:dispatchEvent(M.EVENT_MESSAGE_HIDE) | |
end | |
} | |
end | |
-------------------------------------------------------------------------------- | |
-- Spools the text. | |
-------------------------------------------------------------------------------- | |
function M:spool() | |
self:spoolingEnabled(true) | |
return self._textLabel:spool() | |
end | |
-------------------------------------------------------------------------------- | |
-- Displays the next page. | |
-------------------------------------------------------------------------------- | |
function M:nextPage() | |
return self._textLabel:nextPage() | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the next page if exists. | |
-- @return If the next page there is a true | |
-------------------------------------------------------------------------------- | |
function M:more() | |
return self._textLabel:more() | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns in the process whether messages are displayed. | |
-- @return busy | |
-------------------------------------------------------------------------------- | |
function M:isBusy() | |
return self._textLabel:isBusy() | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the text. | |
-- @param text text | |
-------------------------------------------------------------------------------- | |
function M:setText(text) | |
self._text = text | |
self._textLabel:setText(text) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the text. | |
-- @return text | |
-------------------------------------------------------------------------------- | |
function M:getText() | |
return self._text | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the color of the text. | |
-- @param r red | |
-- @param g green | |
-- @param b blue | |
-- @param a alpha | |
-------------------------------------------------------------------------------- | |
function M:setTextColor(r, g, b, a) | |
self:setStyle(M.STATE_NORMAL, "textColor", {r, g, b, a}) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the size of the text. | |
-- @param points points | |
-------------------------------------------------------------------------------- | |
function M:setTextSize(points) | |
self:setStyle(M.STATE_NORMAL, "textSize", points) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the event listener was called to display a message box. | |
-- @param func event listener | |
-------------------------------------------------------------------------------- | |
function M:setOnMessageShow(func) | |
self:setEventListener(M.EVENT_MESSAGE_SHOW, func) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the event listener was called to hide a message box. | |
-- @param func event listener | |
-------------------------------------------------------------------------------- | |
function M:setOnMessageHide(func) | |
self:setEventListener(M.EVENT_MESSAGE_HIDE, func) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the event listener was called to end a message box. | |
-- @param func event listener | |
-------------------------------------------------------------------------------- | |
function M:setOnMessageEnd(func) | |
self:setEventListener(M.EVENT_MESSAGE_END, func) | |
end | |
---------------------------------------------------------------------------------------------------- | |
-- Event Handler | |
---------------------------------------------------------------------------------------------------- | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you touch the component. | |
-- @param e touch event | |
-------------------------------------------------------------------------------- | |
function M:touchDownHandler(e) | |
if self:isBusy() then | |
self._textLabel:stop() | |
self._textLabel:revealAll() | |
elseif self:more() then | |
self:nextPage() | |
if self._spoolingEnabled then | |
self:spool() | |
end | |
else | |
self:enterMessageEnd() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- This is called when a message has been completed. | |
-------------------------------------------------------------------------------- | |
function M:enterMessageEnd() | |
self:dispatchEvent(M.EVENT_MESSAGE_END) | |
if self._messageHideEnabled then | |
self:hide() | |
end | |
end | |
return M end) | |
package.preload['hp/gui/Panel'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This is a simple panel. | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local NinePatch = require "hp/display/NinePatch" | |
local TextLabel = require "hp/display/TextLabel" | |
local Event = require "hp/event/Event" | |
local Component = require "hp/gui/Component" | |
-- class define | |
local M = class(Component) | |
local super = Component | |
-------------------------------------------------------------------------------- | |
-- Initializes the internal variables. | |
-------------------------------------------------------------------------------- | |
function M:initInternal() | |
super.initInternal(self) | |
self._themeName = "Panel" | |
end | |
-------------------------------------------------------------------------------- | |
-- Create a child objects. | |
-------------------------------------------------------------------------------- | |
function M:createChildren() | |
local backgroundSkinClass = self:getStyle("backgroundSkinClass") | |
self._background = backgroundSkinClass() | |
self._background:setTexture(self:getStyle("backgroundSkin")) | |
self:addChild(self._background) | |
end | |
-------------------------------------------------------------------------------- | |
-- Update the display. | |
-------------------------------------------------------------------------------- | |
function M:updateDisplay() | |
local background = self._background | |
background:setColor(unpack(self:getStyle("backgroundColor"))) | |
background:setTexture(self:getStyle("backgroundSkin")) | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when resizing. | |
-- @param e resize event | |
-------------------------------------------------------------------------------- | |
function M:resizeHandler(e) | |
self._background:setSize(e.newWidth, e.newHeight) | |
end | |
return M end) | |
package.preload['hp/gui/Scroller'] = (function (...) | |
---------------------------------------------------------------- | |
-- This class will scroll according to the size of the parent. | |
-- By a parent View, and typically in the range can scroll the screen. | |
-- TODO:I moved just by touch. It is necessary to have a little margin. | |
---------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local Layer = require "hp/display/Layer" | |
local Event = require "hp/event/Event" | |
local Component = require "hp/gui/Component" | |
local Executors = require "hp/util/Executors" | |
local math = require "hp/lang/math" | |
-- class | |
local super = Component | |
local M = class(Component) | |
-- Computes attenuation as a function of distance. | |
-- @param distance Distance | |
-- @return distance^(-2/3) | |
local function attenuation(distance) | |
distance = distance == 0 and 1 or math.pow(distance, 0.667) | |
return 1 / distance | |
end | |
-------------------------------------------------------------------------------- | |
-- Initializes the internal variables. | |
-------------------------------------------------------------------------------- | |
function M:initInternal(params) | |
super.initInternal(self, params) | |
self._autoResizing = true | |
self._friction = 0.1 | |
self._hScrollEnabled = true | |
self._vScrollEnabled = true | |
self._scrollingForceX = 0 | |
self._scrollingForceY = 0 | |
self._maxScrollingForceX = 100 | |
self._maxScrollingForceY = 100 | |
self._minScrollingForceX = 0.1 | |
self._minScrollingForceY = 0.1 | |
self._touchDownFlag = false | |
self._touchDownIndex = nil | |
self._touchMoved = false | |
self._themeName = "Scroller" | |
self._disposed = false | |
self._scrollToAnimation = nil | |
self._hBounceEnabled = true | |
self._vBounceEnabled = true | |
Executors.callLoop(self.enterFrame, self) | |
end | |
-------------------------------------------------------------------------------- | |
-- Update frame. | |
-------------------------------------------------------------------------------- | |
function M:enterFrame() | |
if self._disposed then | |
return true | |
end | |
self:updateScroll() | |
end | |
-------------------------------------------------------------------------------- | |
-- Update of the scroll processing. | |
-------------------------------------------------------------------------------- | |
function M:updateScroll() | |
self._touchMoved = false | |
if self:isTouching() then | |
return | |
end | |
if not self:isScrolling() then | |
-- If we're not scrolling, not animating and are O.B., initiate scrollTo() | |
if not self:isAnimating() then | |
local left, top = self:getPos() | |
if self:isPositionOutOfBounds(left, top) then | |
local clippedLeft, clippedTop = self:clipScrollPosition(left, top) | |
self:scrollTo(clippedLeft, clippedTop, 0.5, MOAIEaseType.SOFT_EASE_IN) | |
end | |
end | |
return | |
end | |
local scrollX, scrollY = self:getScrollingForce() | |
local rate = (1 - self:getFriction()) | |
-- Increase the attenuation when we're out of bounds | |
local left, top = self:getPos() | |
if self:isPositionOutOfBounds(left, top) then | |
rate = 0.35 * rate | |
end | |
self:addLoc(scrollX, scrollY, 0) | |
self:setScrollingForce(scrollX * rate, scrollY * rate) | |
self:ajustScrollPosition() | |
end | |
-------------------------------------------------------------------------------- | |
-- Also changes the size of the scroll container when layout update. | |
-------------------------------------------------------------------------------- | |
function M:updateLayout() | |
super.updateLayout(self) | |
self:ajustScrollSize() | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets whether to automatically update the scroll range. | |
-- @param value auto resizing | |
-------------------------------------------------------------------------------- | |
function M:setAutoResizing(value) | |
self._autoResizing = value | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns whether to automatically update the scroll range. | |
-- @return auto resizing | |
-------------------------------------------------------------------------------- | |
function M:isAutoResizing() | |
return self._autoResizing | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets whether the horizontal scroll is enabled. | |
-- @param value horizontal scroll enabled | |
-------------------------------------------------------------------------------- | |
function M:setHScrollEnabled(value) | |
self._hScrollEnabled = value | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns whether the horizontal scroll is enabled. | |
-- @return horizontal scroll enabled | |
-------------------------------------------------------------------------------- | |
function M:isHScrollEnabled() | |
return self._hScrollEnabled | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets whether the vertical scroll is enabled. | |
-- @param value vertical scroll enabled | |
-------------------------------------------------------------------------------- | |
function M:setVScrollEnabled(value) | |
self._vScrollEnabled = value | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns whether the vertical scroll is enabled. | |
-- @return vertical scroll enabled | |
-------------------------------------------------------------------------------- | |
function M:isVScrollEnabled() | |
return self._vScrollEnabled | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the ability to bounce horizontally. | |
-- @param value horizontal bouncing enabled | |
-------------------------------------------------------------------------------- | |
function M:setHBounceEnabled(value) | |
self._hBounceEnabled = value | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns whether horizontal bouncing is enabled. | |
-- @return horizontal bouncing enabled | |
-------------------------------------------------------------------------------- | |
function M:isHBouncelEnabled() | |
return self._hBounceEnabled | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the ability to bounce vertically. | |
-- @param value vertical bouncing enabled | |
-------------------------------------------------------------------------------- | |
function M:setVBounceEnabled(value) | |
self._vBounceEnabled = value | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns whether vertical bouncing is enabled. | |
-- @return vertical bouncing enabled | |
-------------------------------------------------------------------------------- | |
function M:isVBounceEnabled() | |
return self._vBounceEnabled | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the coefficient of friction at the time of scrolling. | |
-- @param value friction | |
-------------------------------------------------------------------------------- | |
function M:setFriction(value) | |
self._friction = value | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the coefficient of friction at the time of scrolling. | |
-- @return friction | |
-------------------------------------------------------------------------------- | |
function M:getFriction() | |
return self._friction | |
end | |
-------------------------------------------------------------------------------- | |
-- If this component is scrolling returns true. | |
-- @return scrolling | |
-------------------------------------------------------------------------------- | |
function M:isScrolling() | |
return self._scrollingForceX ~= 0 or self._scrollingForceY ~= 0 | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the force to scroll in one frame. | |
-- It does not make sense if you're touch. | |
-- @param x x force | |
-- @param y y force | |
-------------------------------------------------------------------------------- | |
function M:setScrollingForce(x, y) | |
self._scrollingForceX = self:isHScrollEnabled() and x or 0 | |
self._scrollingForceY = self:isVScrollEnabled() and y or 0 | |
local maxScrollX, maxScrollY = self:getMaxScrollingForce() | |
local minScrollX, minScrollY = self:getMinScrollingForce() | |
local scrollX, scrollY = self._scrollingForceX, self._scrollingForceY | |
scrollX = (-minScrollX < scrollX and scrollX < minScrollX) and 0 or scrollX | |
scrollY = (-minScrollY < scrollY and scrollY < minScrollY) and 0 or scrollY | |
scrollX = scrollX < -maxScrollX and -maxScrollX or scrollX | |
scrollX = maxScrollX < scrollX and maxScrollX or scrollX | |
scrollY = scrollY < -maxScrollY and -maxScrollY or scrollY | |
scrollY = maxScrollY < scrollY and maxScrollY or scrollY | |
self._scrollingForceX = scrollX | |
self._scrollingForceY = scrollY | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the force to scroll in one frame. | |
-- @return x force | |
-- @return y force | |
-------------------------------------------------------------------------------- | |
function M:getScrollingForce() | |
return self._scrollingForceX, self._scrollingForceY | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the maximum force in one frame. | |
-- @param x x force | |
-- @param y y force | |
-------------------------------------------------------------------------------- | |
function M:setMaxScrollingForce(x, y) | |
self._maxScrollingForceX = x | |
self._maxScrollingForceY = y | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the maximum force in one frame. | |
-- @param x force | |
-- @param y force | |
-------------------------------------------------------------------------------- | |
function M:getMaxScrollingForce() | |
return self._maxScrollingForceX, self._maxScrollingForceY | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the minimum force in one frame. | |
-- @param x x force | |
-- @param y y force | |
-------------------------------------------------------------------------------- | |
function M:setMinScrollingForce(x, y) | |
self._minScrollingForceX = x | |
self._minScrollingForceY = y | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the minimum force in one frame. | |
-- @param x force | |
-- @param y force | |
-------------------------------------------------------------------------------- | |
function M:getMinScrollingForce() | |
return self._minScrollingForceX, self._minScrollingForceY | |
end | |
-------------------------------------------------------------------------------- | |
-- If the user has touched returns true. | |
-- @return If the user has touched returns true. | |
-------------------------------------------------------------------------------- | |
function M:isTouching() | |
return self._touchDownFlag | |
end | |
-------------------------------------------------------------------------------- | |
-- Scroll to the specified location. | |
-- @param x position of the x | |
-- @param y position of the x | |
-- @param sec second | |
-- @param mode EaseType | |
-- @param callback (optional) allows callback notification when animation completes. | |
-------------------------------------------------------------------------------- | |
function M:scrollTo(x, y, sec, mode, callback) | |
mode = mode or MOAIEaseType.SHARP_EASE_IN | |
local x, y = self:clipScrollPosition(x, y) | |
self:stopAnimation() | |
self._scrollToAnimation = Animation(self, sec, mode):seekLoc(x, y, 0) | |
self._scrollToAnimation:play({onComplete = callback}) | |
end | |
-------------------------------------------------------------------------------- | |
-- Adjusted so as to fall within the scope of the scroll. | |
-------------------------------------------------------------------------------- | |
function M:ajustScrollPosition() | |
local left, top = self:getPos() | |
-- Clips the new position when bouncing is disabled | |
if not self:isHBouncelEnabled() then | |
local _ | |
left, _ = self:clipScrollPosition(left, top) | |
end | |
if not self:isVBounceEnabled() then | |
local _ | |
_, top = self:clipScrollPosition(left, top) | |
end | |
self:setPos(left, top) | |
end | |
-------------------------------------------------------------------------------- | |
-- Adjust the scroll size. | |
-------------------------------------------------------------------------------- | |
function M:ajustScrollSize() | |
if not self._autoResizing then | |
return | |
end | |
local width, height = 0, 0 | |
local parent = self:getParent() | |
local minWidth = parent and parent:getWidth() or 0 | |
local minHeight = parent and parent:getHeight() or 0 | |
for i, child in ipairs(self:getChildren()) do | |
width = math.max(width, child:getRight()) | |
height = math.max(height, child:getBottom()) | |
end | |
width = width >= minWidth and width or minWidth | |
height = height >= minHeight and height or minHeight | |
self:setSize(width, height) | |
end | |
-------------------------------------------------------------------------------- | |
-- Computes the boundaries of the scroll area. | |
-- @return the min and max values of the scroll area | |
-------------------------------------------------------------------------------- | |
function M:scrollBoundaries() | |
local width, height = self:getSize() | |
local parentWidth, parentHeight = self:getParent():getSize() | |
local minX, minY = parentWidth - width, parentHeight - height | |
local maxX, maxY = 0, 0 | |
return minX, minY, maxX, maxY | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns whether the input position is out of bounds. | |
-- @param left The x position | |
-- @param top The y position | |
-- @return boolean | |
-------------------------------------------------------------------------------- | |
function M:isPositionOutOfBounds(left, top) | |
local minX, minY, maxX, maxY = self:scrollBoundaries() | |
return left < minX or left > maxX or top < minY or top > maxY | |
end | |
-------------------------------------------------------------------------------- | |
-- Clips the input position to the size of the container | |
-- @param left The x position | |
-- @param top The y position | |
-- @return clipped left and top | |
-------------------------------------------------------------------------------- | |
function M:clipScrollPosition(left, top) | |
local minX, minY, maxX, maxY = self:scrollBoundaries() | |
left = left < minX and minX or left | |
left = left > maxX and maxX or left | |
top = top < minY and minY or top | |
top = top > maxY and maxY or top | |
return left, top | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns whether the scrollTo animation is running. | |
-- @return boolean | |
-------------------------------------------------------------------------------- | |
function M:isAnimating() | |
return self._scrollToAnimation and self._scrollToAnimation:isRunning() | |
end | |
-------------------------------------------------------------------------------- | |
-- Stops the scrollTo animation if it's running | |
-- @return none | |
-------------------------------------------------------------------------------- | |
function M:stopAnimation() | |
if self._scrollToAnimation then | |
self._scrollToAnimation:stop() | |
self._scrollToAnimation = nil | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- If you set a parent, you also change the scroll size. | |
-- @param value parent | |
-------------------------------------------------------------------------------- | |
function M:setParent(value) | |
super.setParent(self, value) | |
self:ajustScrollSize() | |
end | |
-------------------------------------------------------------------------------- | |
-- Dispose resourece. | |
-------------------------------------------------------------------------------- | |
function M:dispose() | |
super.dispose(self) | |
self._disposed = true | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you touch the component. | |
-- @param e touch event | |
-------------------------------------------------------------------------------- | |
function M:touchDownHandler(e) | |
if self._touchDownFlag then | |
return | |
end | |
self._scrollingForceX = 0 | |
self._scrollingForceY = 0 | |
self._touchDownFlag = true | |
self._touchDownIndex = e.idx | |
-- User's input takes precedence over animation | |
self:stopAnimation() | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you touch the component. | |
-- @param e touch event | |
-------------------------------------------------------------------------------- | |
function M:touchUpHandler(e) | |
if self._touchDownIndex ~= e.idx then | |
return | |
end | |
self._touchDownFlag = false | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you touch the component. | |
-- @param e touch event | |
-------------------------------------------------------------------------------- | |
function M:touchMoveHandler(e) | |
if self._touchDownIndex ~= e.idx then | |
return | |
end | |
if self._touchMoved then | |
return | |
end | |
local scale = self:getLayer():getViewScale() | |
local moveX, moveY = e.moveX, e.moveY | |
self:setScrollingForce(moveX, moveY) | |
moveX, moveY = self:getScrollingForce() | |
-- Implements an elastic effect when we're dragging O.B. | |
local minX, minY, maxX, maxY = self:scrollBoundaries() | |
local left, top = self:getPos() | |
local newLeft = left + moveX | |
local newTop = top + moveY | |
if newLeft < minX or newLeft > maxX then | |
if not self:isHBouncelEnabled() then | |
moveX = 0 | |
else | |
local clippedLeft, clippedTop = self:clipScrollPosition(newLeft, newTop) | |
local diff = math.distance(clippedLeft, clippedTop, newLeft, newTop) | |
moveX = attenuation(diff) * moveX | |
end | |
end | |
if newTop < minY or newTop > maxY then | |
if not self:isVBounceEnabled() then | |
moveY = 0 | |
else | |
local clippedLeft, clippedTop = self:clipScrollPosition(newLeft, newTop) | |
local diff = math.distance(clippedLeft, clippedTop, newLeft, newTop) | |
moveY = attenuation(diff) * moveY | |
end | |
end | |
self:addLoc(moveX, moveY, 0) | |
self._touchMoved = true | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you touch the component. | |
-- @param e touch event | |
-------------------------------------------------------------------------------- | |
function M:touchCancelHandler(e) | |
if self._touchDownIndex ~= e.idx then | |
return | |
end | |
self._touchDownFlag = false | |
self._touchDownIndex = nil | |
end | |
return M end) | |
package.preload['hp/gui/Slider'] = (function (...) | |
---------------------------------------------------------------- | |
-- This class is a general horizontal slider. | |
---------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local Event = require "hp/event/Event" | |
local Sprite = require "hp/display/Sprite" | |
local Component = require "hp/gui/Component" | |
-- class define | |
local M = class(Component) | |
local super = Component | |
-- States | |
M.STATE_NORMAL = "normal" | |
M.STATE_DISABLED = "disabled" | |
-- Events | |
M.EVENT_SLIDER_BEGIN = "sliderBeginChange" | |
M.EVENT_SLIDER_CHANGED = "sliderChanged" | |
M.EVENT_SLIDER_END = "sliderEndChange" | |
-------------------------------------------------------------------------------- | |
-- Initializes the internal variables. | |
-------------------------------------------------------------------------------- | |
function M:initInternal() | |
super.initInternal(self) | |
self._selected = false | |
self._touching = false | |
self._touchIndex = nil | |
self._themeName = "Slider" | |
self._beginChangeEvent = Event(M.EVENT_SLIDER_BEGIN) | |
self._changedEvent = Event(M.EVENT_SLIDER_CHANGED) | |
self._endChangeEvent = Event(M.EVENT_SLIDER_END) | |
self._value = 0 | |
self._bounds = {min=0, max=1, span=1} | |
self._accuracy = 0.1 | |
end | |
-------------------------------------------------------------------------------- | |
-- Create a child objects. | |
-------------------------------------------------------------------------------- | |
function M:createChildren() | |
self._background = NinePatch(self:getStyle("bg")) | |
self._progress = NinePatch(self:getStyle("progress")) | |
self._thumb = Sprite { texture = self:getStyle("thumb"), left = 0, top = 0 } | |
self:addChild(self._background) | |
self:addChild(self._progress) | |
self:addChild(self._thumb) | |
local _,bh = self._background:getSize() | |
self:setSize(200, bh) | |
self._thumb_width = self._thumb:getWidth() | |
end | |
-------------------------------------------------------------------------------- | |
-- Update the display. | |
-------------------------------------------------------------------------------- | |
function M:updateDisplay() | |
local background = self._background | |
background:setColor(unpack(self:getStyle("color"))) | |
background:setTexture(self:getStyle("bg")) | |
local progress = self._progress | |
progress:setColor(unpack(self:getStyle("color"))) | |
progress:setTexture(self:getStyle("progress")) | |
local thumb = self._thumb | |
thumb:setColor(unpack(self:getStyle("color"))) | |
thumb:setTexture(self:getStyle("thumb")) | |
local thumbLoc = self:_valueToLoc(self._value) | |
thumb:setLoc(thumbLoc, self:getHeight() * 0.5) | |
progress:setSize(thumbLoc + self._thumb_width * 0.5, self:getHeight()) | |
end | |
function M:_valueToLoc(value) | |
-- normalize value | |
local v = (value - self._bounds.min) / self._bounds.span | |
return self._thumb_width * 0.5 + (self:getWidth() - self._thumb_width) * v | |
end | |
function M:_locToValue(x) | |
-- normalized | |
local v = (x - self._thumb_width * 0.5) / (self:getWidth() - self._thumb_width) | |
return self._bounds.min + v * self._bounds.span | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the value (must be between 0 and 1). | |
-- @param value value | |
-------------------------------------------------------------------------------- | |
function M:setValue(value) | |
if value < self._bounds.min then | |
value = self._bounds.min | |
end | |
if value > self._bounds.max then | |
value = self._bounds.max | |
end | |
-- round to 4 decimal places = value | |
value = math.floor(value * 10000) / 10000 | |
-- snap to accuracy | |
local invsnap = 1 / self._accuracy | |
value = math.floor(value * invsnap) / invsnap | |
-- if value has not changed, abort | |
if value == self._value then | |
return | |
end | |
local old_value = self._value | |
self._value = value | |
self:_updateDrawables() | |
local event = self._changedEvent | |
event.oldValue = old_value | |
event.value = self._value | |
self:dispatchEvent(event) | |
end | |
function M:_updateDrawables() | |
-- and indication we 're still initializing (called by resizeHandler)... | |
if self._thumb_width == nil then | |
return | |
end | |
local thumbLoc = self:_valueToLoc(self._value) | |
self._thumb:setLoc(thumbLoc, self._background:getHeight() * 0.5) | |
self._progress:setSize(thumbLoc + self._thumb_width * 0.5, self:getHeight()) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the value. | |
-- @return value | |
-------------------------------------------------------------------------------- | |
function M:getValue() | |
return self._value | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the accuracy. | |
-- @return accuracy | |
-------------------------------------------------------------------------------- | |
function M:getAccuracy() | |
return self._accuracy | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the accuracy. | |
-- @param accuracy accuracy | |
-------------------------------------------------------------------------------- | |
function M:setAccuracy(accuracy) | |
self._accuracy = accuracy | |
self:setValue(self._value) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the minimum and maximum values this slider can hold. | |
-- @return minimum and maximum values | |
-------------------------------------------------------------------------------- | |
function M:getValueBounds() | |
return self._bounds.min, self._bounds.max | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the minimum and maximum values this slider can hold. | |
-- @param minMax table holding {min, max} values | |
-------------------------------------------------------------------------------- | |
function M:setValueBounds(...) | |
local minMax = {...} | |
assert(#minMax >= 2) | |
self._bounds.min = minMax[1] | |
self._bounds.max = minMax[2] | |
self._bounds.span = self._bounds.max - self._bounds.min | |
self:setValue(self._value) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the event listener that is called when the user pushes the thumb. | |
-- @param func push event handler | |
-------------------------------------------------------------------------------- | |
function M:setOnSliderBeginChange(func) | |
self:setEventListener(M.EVENT_SLIDER_BEGIN, func) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the event listener that is called when the user moves the thumb. | |
-- @param func move event handler | |
-------------------------------------------------------------------------------- | |
function M:setOnSliderChanged(func) | |
self:setEventListener(M.EVENT_SLIDER_CHANGED, func) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the event listener that is called when the user releases the thumb. | |
-- @param func release event handler | |
-------------------------------------------------------------------------------- | |
function M:setOnSliderEndChange(func) | |
self:setEventListener(M.EVENT_SLIDER_END, func) | |
end | |
-------------------------------------------------------------------------------- | |
-- Event Handler | |
-------------------------------------------------------------------------------- | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when touched. | |
-- @param e Touch Event | |
-------------------------------------------------------------------------------- | |
function M:touchDownHandler(e) | |
if self._touching then | |
return | |
end | |
e:stop() | |
if self._thumb:hitTestWorld(e.x, e.y) then | |
self._touchIndex = e.idx | |
self._touching = true | |
local event = self._beginChangeEvent | |
event.value = self._value | |
self:dispatchEvent(event) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when the button is released. | |
-- @param e Touch Event | |
-------------------------------------------------------------------------------- | |
function M:touchUpHandler(e) | |
if e.idx ~= self._touchIndex then | |
return | |
end | |
e:stop() | |
self._touching = false | |
self._touchIndex = nil | |
local event = self._endChangeEvent | |
event.value = self._value | |
self:dispatchEvent(event) | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you move on the button. | |
-- @param e Touch Event | |
-------------------------------------------------------------------------------- | |
function M:touchMoveHandler(e) | |
if e.idx ~= self._touchIndex then | |
return | |
end | |
e:stop() | |
if self._touching then | |
local mx, my = self:worldToModel(e.x, e.y, 0) | |
local v = self:_locToValue(mx) | |
self:setValue(v) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when you move on the button. | |
-- @param e Touch Event | |
-------------------------------------------------------------------------------- | |
function M:touchCancelHandler(e) | |
if not self:isToggle() then | |
self._touching = false | |
self._touchIndex = nil | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when resizing. | |
-- @param e resize event | |
-------------------------------------------------------------------------------- | |
function M:resizeHandler(e) | |
self._background:setSize(self:getWidth(), self:getHeight()) | |
self:_updateDrawables() | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when the enabled state changes. | |
-- @param e event | |
-------------------------------------------------------------------------------- | |
function M:enabledChangedHandler(e) | |
if not self:isEnabled() then | |
self._touching = false | |
self._touchIndex = 0 | |
end | |
end | |
return M end) | |
package.preload['hp/gui/Theme'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This is a standard GUI theme. | |
-- Can not dynamically change the theme. | |
-------------------------------------------------------------------------------- | |
-- import | |
local Sprite = require "hp/display/Sprite" | |
local NinePatch = require "hp/display/NinePatch" | |
-- module define | |
local M = {} | |
M.Button = { | |
normal = { | |
skin = "skins/button-normal.png", | |
skinClass = NinePatch, | |
skinColor = {1, 1, 1, 1}, | |
font = "VL-PGothic", | |
textSize = 24, | |
textColor = {0.0, 0.0, 0.0, 1}, | |
textPadding = {10, 5, 10, 8}, | |
}, | |
selected = { | |
skin = "skins/button-selected.png", | |
}, | |
over = { | |
skin = "skins/button-over.png", | |
}, | |
disabled = { | |
skin = "skins/button-disabled.png", | |
textColor = {0.5, 0.5, 0.5, 1}, | |
}, | |
} | |
M.Joystick = { | |
normal = { | |
baseSkin = "skins/joystick_base.png", | |
knobSkin = "skins/joystick_knob.png", | |
baseColor = {1, 1, 1, 1}, | |
knobColor = {1, 1, 1, 1}, | |
}, | |
disabled = { | |
baseColor = {0.5, 0.5, 0.5, 1}, | |
knobColor = {0.5, 0.5, 0.5, 1}, | |
}, | |
} | |
M.Panel = { | |
normal = { | |
backgroundSkin = "skins/panel.png", | |
backgroundSkinClass = NinePatch, | |
backgroundColor = {1, 1, 1, 1}, | |
}, | |
disabled = { | |
backgroundColor = {0.5, 0.5, 0.5, 1}, | |
}, | |
} | |
M.MessageBox = { | |
normal = { | |
backgroundSkin = "skins/panel.png", | |
backgroundSkinClass = NinePatch, | |
backgroundColor = {1, 1, 1, 1}, | |
font = "VL-PGothic", | |
textPadding = {20, 20, 15, 15}, | |
textSize = 20, | |
textColor = {0, 0, 0, 1}, | |
}, | |
disabled = { | |
backgroundColor = {0.5, 0.5, 0.5, 1}, | |
textColor = {0.2, 0.2, 0.2, 1}, | |
}, | |
} | |
M.Slider = { | |
normal = { | |
bg = "skins/slider_background.png", | |
thumb = "skins/slider_thumb.png", | |
progress = "skins/slider_progress.png", | |
color = {1, 1, 1, 1}, | |
}, | |
disabled = { | |
color = {0.5, 0.5, 0.5, 1}, | |
}, | |
} | |
M.DialogBox = { | |
normal = { | |
backgroundSkin = "skins/dialog.png", | |
backgroundSkinClass = NinePatch, | |
backgroundColor = {1, 1, 1, 1}, | |
font = "VL-PGothic", | |
textPadding = {5, 5, 5, 5}, | |
textSize = 14, | |
textColor = {1, 1, 1, 1}, | |
titleFont = "VL-PGothic", | |
titlePadding = {0, 0, 0, 0}, | |
titleSize = 20, | |
titleColor = {1, 1, 0, 1}, | |
iconPadding = {5, 5, 0, 5}, | |
iconScaleFactor = 0.5, | |
iconInfo = "skins/info.png", | |
iconConfirm = "skins/okay.png", | |
iconWarning = "skins/warning.png", | |
iconError = "skins/error.png", | |
buttonsPadding = {5, 0, 5, 5}, | |
}, | |
disabled = { | |
backgroundColor = {0.5, 0.5, 0.5, 1}, | |
textColor = {0.2, 0.2, 0.2, 1}, | |
titleColor = {0.2, 0.2, 0, 1}, | |
}, | |
} | |
return M end) | |
package.preload['hp/gui/View'] = (function (...) | |
---------------------------------------------------------------- | |
-- This is the root class for adding components. | |
-- View parent can not be set. | |
---------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local array = require "hp/lang/array" | |
local class = require "hp/lang/class" | |
local Layer = require "hp/display/Layer" | |
local Event = require "hp/event/Event" | |
local Component = require "hp/gui/Component" | |
local Executors = require "hp/util/Executors" | |
-- class define | |
local super = Component | |
local M = class(super) | |
local function internalUpdateRenderPriority(obj, priority) | |
obj:setPriority(priority) | |
priority = priority + 1 | |
if obj.isGroup then | |
local children = obj:getChildren() | |
for i, child in ipairs(children) do | |
priority = internalUpdateRenderPriority(child, priority) | |
end | |
end | |
return priority | |
end | |
-------------------------------------------------------------------------------- | |
-- Initializes the internal variables. | |
-------------------------------------------------------------------------------- | |
function M:initInternal() | |
super.initInternal(self) | |
self._priorityUpdateEnabled = true | |
end | |
-------------------------------------------------------------------------------- | |
-- Performing the initialization processing of the component. | |
-- @param params Parameter table | |
-------------------------------------------------------------------------------- | |
function M:initComponent(params) | |
self:initLayer() | |
super.initComponent(self, params) | |
end | |
-------------------------------------------------------------------------------- | |
-- Initialize the layer of View. | |
-------------------------------------------------------------------------------- | |
function M:initLayer() | |
local layer = Layer() | |
layer:setSortMode(MOAILayer.SORT_PRIORITY_ASCENDING) | |
layer:setTouchEnabled(true) | |
self:setLayer(layer) | |
self:setSize(layer:getViewSize()) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the scene. | |
-- @param scene scene | |
-------------------------------------------------------------------------------- | |
function M:setScene(scene) | |
local currentScene = self:getScene() | |
if currentScene == scene then | |
return | |
end | |
if currentScene then | |
currentScene:removeEventListener("destroy", self.sceneDestroyHandler, self) | |
end | |
self:getLayer():setScene(scene) | |
if scene then | |
scene:addEventListener("destroy", self.sceneDestroyHandler, self) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the scene. | |
-- @return scene | |
-------------------------------------------------------------------------------- | |
function M:getScene() | |
local layer = self:getLayer() | |
if layer then | |
return layer:getScene() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Automatically updates the drawing order. | |
-------------------------------------------------------------------------------- | |
function M:updateLayout() | |
super.updateLayout(self) | |
if self._priorityUpdateEnabled then | |
internalUpdateRenderPriority(self, 1) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Set whether to automatically update the drawing order of priority. | |
-------------------------------------------------------------------------------- | |
function M:setPriorityUpdateEnabled(value) | |
self._priorityUpdateEnabled = value | |
end | |
-------------------------------------------------------------------------------- | |
-- This event handler is called when scene destroyed. | |
-- @param e Touch Event | |
-------------------------------------------------------------------------------- | |
function M:sceneDestroyHandler(e) | |
self:dispose() | |
end | |
return M end) | |
package.preload['hp/lang/array'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- modules that extend functionality of the table. | |
-------------------------------------------------------------------------------- | |
local M = {} | |
-------------------------------------------------------------------------------- | |
-- Returns the position found by searching for a matching value from the array. | |
-- @param array table array | |
-- @param value Search value | |
-- @return If one is found the index. 0 if not found. | |
-------------------------------------------------------------------------------- | |
function M.indexOf(array, value) | |
for i, v in ipairs(array) do | |
if v == value then | |
return i | |
end | |
end | |
return 0 | |
end | |
function M.concat(...) | |
local dest = {} | |
local args = {...} | |
for i, t in ipairs(args) do | |
for j, v in ipairs(src) do | |
dest[#dest + 1] = v | |
end | |
end | |
return dest | |
end | |
function M.reverse(t) | |
local dest = {} | |
local size = #t | |
for i = 1, size do | |
dest[i] = t[size - i + 1] | |
end | |
return dest | |
end | |
-------------------------------------------------------------------------------- | |
-- Adds an element to the table. | |
-- If the element was present, the element will return false without the need for additional. | |
-- If the element does not exist, and returns true add an element. | |
-- @param t table | |
-- @param o element | |
-- @return If it already exists, false. If you add is true. | |
-------------------------------------------------------------------------------- | |
function M.insertElement(t, o) | |
if M.indexOf(t, o) > 0 then | |
return false | |
end | |
M.insert(t, o) | |
return true | |
end | |
-------------------------------------------------------------------------------- | |
-- This removes the element from the table. | |
-- If you have successfully removed, it returns the index of the yuan. | |
-- If there is no element, it returns 0. | |
-- @param t table | |
-- @param o element | |
-- @return index | |
-------------------------------------------------------------------------------- | |
function M.removeElement(t, o) | |
local i = M.indexOf(t, o) | |
if i == 0 then | |
return 0 | |
end | |
M.remove(t, i) | |
return i | |
end | |
return M | |
end) | |
package.preload['hp/lang/class'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- Class that enable you to easily object-oriented. <br> | |
-- Provide the basic functionality of the class. <br> | |
-- <br> | |
-- class does not perform inheritance setmetatable. <br> | |
-- The inheritance by copying it to the table. <br> | |
-- Will consume a little more memory, | |
-- the performance does not deteriorate if the inheritance is deep. <br> | |
-------------------------------------------------------------------------------- | |
local table = require("hp/lang/table") | |
local M = {} | |
setmetatable(M, M) | |
local function call(self, ...) | |
return self:new(...) | |
end | |
-------------------------------------------------------------------------------- | |
-- Class definition is a function. | |
-- @param ... Base class list. | |
-- @return class | |
-------------------------------------------------------------------------------- | |
function M:__call(...) | |
local class = table.copy(self) | |
local bases = {...} | |
for i = #bases, 1, -1 do | |
table.copy(bases[i], class) | |
end | |
class.__call = call | |
return setmetatable(class, class) | |
end | |
-------------------------------------------------------------------------------- | |
-- Instance generating functions.<br> | |
-- The user can use this function.<br> | |
-- Calling this function, init function will be called internally.<br> | |
-- @return Instance | |
-------------------------------------------------------------------------------- | |
function M:new(...) | |
local obj = {__index = self} | |
setmetatable(obj, obj) | |
if obj.init then | |
obj:init(...) | |
end | |
obj.new = nil | |
obj.init = nil | |
return obj | |
end | |
return M | |
end) | |
package.preload['hp/lang/delegate'] = (function (...) | |
---------------------------------------------------------------- | |
-- Modules to perform additional functions by delegation. <br> | |
---------------------------------------------------------------- | |
local M = {} | |
local function call(self, dest, src, funcName) | |
if funcName then | |
dest[funcName] = function(self, ...) | |
return src[funcName](src, ...) | |
end | |
return | |
end | |
for k, v in pairs(src) do | |
if type(v) == "function" then | |
dest[k] = function(self, ...) | |
return src[k](src, ...) | |
end | |
end | |
end | |
end | |
setmetatable(M, {__call = call}) | |
return M end) | |
package.preload['hp/lang/math'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- modules that extend functionality of the math. | |
-------------------------------------------------------------------------------- | |
local gmath = math | |
local math = {} | |
setmetatable(math, {__index = gmath}) | |
--------------------------------------- | |
-- Calculate the average of the values of the argument. | |
-- @param ... The number of variable-length argument | |
-- @return average | |
--------------------------------------- | |
function math.average(...) | |
local total = 0 | |
local array = {...} | |
for i, v in ipairs(array) do | |
total = total + v | |
end | |
return total / #array | |
end | |
--------------------------------------- | |
-- Calculate the total values of the argument | |
-- @param ... The number of variable-length argument | |
-- @return total | |
--------------------------------------- | |
function math.sum(...) | |
local total = 0 | |
local array = {...} | |
for i, v in ipairs(array) do | |
total = total + v | |
end | |
return total | |
end | |
function math.distance( x0, y0, x1, y1 ) | |
if not x1 then x1 = 0 end | |
if not y1 then y1 = 0 end | |
local dX = x1 - x0 | |
local dY = y1 - y0 | |
local dist = math.sqrt((dX * dX) + (dY * dY)) | |
return dist | |
end | |
function math.normalize( x, y ) | |
local d = math.distance( x, y ) | |
return x/d, y/d | |
end | |
function math.getAngle( a, b, c ) | |
local result | |
if c then | |
local ab, bc = { }, { } | |
ab.x = b.x - a.x; | |
ab.y = b.y - a.y; | |
bc.x = b.x - c.x; | |
bc.y = b.y - c.y; | |
local angleAB = math.atan2( ab.y, ab.x ) | |
local angleBC = math.atan2( bc.y, bc.x ) | |
result = angleAB - angleBC | |
else | |
local ab = { } | |
ab.x = b.x - a.x; | |
ab.y = b.y - a.y; | |
result = math.deg( math.atan2( ab.y, ab.x ) ) | |
end | |
return result | |
end | |
function math.clamp( v, min, max ) | |
if v < min then | |
v = min | |
elseif v > max then | |
v = max | |
end | |
return v | |
end | |
return math | |
end) | |
package.preload['hp/lang/string'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- modules that extend functionality of the string. | |
-------------------------------------------------------------------------------- | |
local M = {} | |
setmetatable(M, {__index = string}) | |
local string = M | |
-------------------------------------------------------------------------------- | |
-- Converts the string to number, or returns string if fail. | |
-------------------------------------------------------------------------------- | |
function string.toNumber( self ) | |
if type( tonumber( self ) ) =="number" then | |
return tonumber( self ) | |
else | |
return self | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Converts number to string, filling in zeros at beginning. | |
-- Technically, this shouldn't really extend string class | |
-- because it doesn't operate on string (doesn't have a "self" ) | |
-- Usage: print( string.fromNumbersWithZeros( 421, 6 ) ) | |
-- 000421 | |
-------------------------------------------------------------------------------- | |
function string.fromNumberWithZeros( n, l ) | |
local s = tostring ( n ) | |
local sl = string.len ( s ) | |
if sl < l then | |
-- add zeros before | |
for i=1, l - sl do | |
s = "0"..s | |
end | |
end | |
return s | |
end | |
-------------------------------------------------------------------------------- | |
-- Converts hex number to rgb (format: #FF00FF) | |
-------------------------------------------------------------------------------- | |
function string.hexToRGB( s, returnAsTable ) | |
if returnAsTable then | |
return { tonumber ( string.sub( s, 2, 3 ),16 )/255.0, | |
tonumber ( string.sub( s, 4, 5 ),16 )/255.0, | |
tonumber ( string.sub( s, 6, 7 ),16 )/255.0 } | |
else | |
return tonumber ( string.sub( s, 2, 3 ),16 )/255.0, | |
tonumber ( string.sub( s, 4, 5 ),16 )/255.0, | |
tonumber ( string.sub( s, 6, 7 ),16 )/255.0 | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Splits string into N lines, using default ("#") or custom delimiter | |
-- Routine separate words by spaces so make sure you have them. | |
-- USAGE: For a string "width:150 height:150", or "width:150_height:150" | |
-- returns a table { width=150, height=150 } | |
-------------------------------------------------------------------------------- | |
function string.toTable( self, delimiter ) | |
local t = {} | |
if not delimiter then delimiter = " " end | |
local kvPairs = self:split( delimiter ) | |
local k, v, kvPair | |
for i=1, #kvPairs do | |
kvPair = kvPairs[i]:split( ":" ) | |
if #kvPair == 2 then | |
t[ kvPair[1] ] = string.toNumber( kvPair[2] ) | |
end | |
end | |
return t | |
end | |
-------------------------------------------------------------------------------- | |
-- Splits string into a table of strings using delimiter.<br> | |
-- Usage: local table = a:split( ",", false )<br> | |
-- TODO: Does not correspond to multi-byte.<br> | |
-- @param self string. | |
-- @param delim Delimiter. | |
-- @param toNumber If set to true or to be converted to a numeric value. | |
-- @return Split the resulting table | |
-------------------------------------------------------------------------------- | |
function string.split( self, delim, toNumber ) | |
local start = 1 | |
local t = {} -- results table | |
local newElement | |
-- find each instance of a string followed by the delimiter | |
while true do | |
local pos = string.find (self, delim, start, true) -- plain find | |
if not pos then | |
break | |
end | |
-- force to number | |
newElement = string.sub (self, start, pos - 1) | |
if toNumber then | |
newElement = newElement:toNumber() | |
end | |
table.insert (t, newElement) | |
start = pos + string.len (delim) | |
end -- while | |
-- insert final one (after last delimiter) | |
local value = string.sub (self, start) | |
if toNumber then | |
value = value:toNumber() | |
end | |
table.insert (t,value ) | |
return t | |
end | |
-------------------------------------------------------------------------------- | |
-- Splits string into N lines, using default ("#") or custom delimiter | |
-- Routine separate words by spaces so make sure you have them. | |
-- Usage: local string = s:splitIntoLines( 3, "\n" ) | |
-------------------------------------------------------------------------------- | |
function string.splitToLines( self, numLines, delim ) | |
local result = "" | |
delim = delim or "#" -- Default delimiter used for display.newText | |
numLines = numLines or 2 | |
-- break into all words. | |
local allWords = self:split( " " ) | |
if #allWords < numLines then | |
numLines = #allWords | |
end | |
-- Words per line | |
local wordsPerLine = math.ceil( #allWords/numLines ) | |
local counter = wordsPerLine | |
for i=1, #allWords do | |
result = result..allWords[i] | |
counter = counter - 1 | |
if counter == 0 and i<#allWords then | |
counter = wordsPerLine | |
result = result..delim | |
else | |
result = result.." " | |
end | |
end | |
return result | |
end | |
------------------------------------------------------------------------------ | |
-- String encryption | |
-------------------------------------------------------------------------------- | |
function string.encrypt( str, code ) | |
code = code or math.random(3,8) | |
local newString = string.char( 65 + code ) | |
local newChar | |
for i=1, str:len() do | |
newChar = str:byte(i) + code | |
newString = newString..string.char(newChar) | |
end | |
return newString | |
end | |
------------------------------------------------------------------------------ | |
-- String encryption | |
-------------------------------------------------------------------------------- | |
function string.decrypt( str ) | |
local newString = "" | |
local code = str:byte(1) - 65 | |
for i = 2, str:len() do | |
newChar = str:byte(i) - code | |
newString = newString..string.char(newChar) | |
end | |
return newString | |
end | |
return M | |
end) | |
package.preload['hp/lang/table'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- | |
-- modules that extend functionality of the table. | |
-- | |
-------------------------------------------------------------------------------- | |
local M = {} | |
setmetatable(M, {__index = table}) | |
-- Compatibility and implementation of Lua5.2 Lua5.1 | |
if unpack then | |
M.unpack = unpack | |
end | |
-------------------------------------------------------------------------------- | |
-- Table decorate is useful for decorating objects | |
-- when using tables as classes. | |
-- @param src | |
-- @param arg1 - string=new key when string, needs arg2 | |
-- @param arg2 - table=will extend all key/values | |
-------------------------------------------------------------------------------- | |
function M.decorate( src, arg1, arg2 ) | |
if not arg2 then | |
if type(arg1)=="table" then | |
for k,v in pairs( arg1 ) do | |
if not src[k] then | |
src[k] = v | |
elseif src[ k ] ~= v then | |
print( "ERROR (table.decorate): Extension failed because key "..k.." exists.") | |
end | |
end | |
end | |
elseif type(arg1)=="string" and type(arg2)=="function" then | |
if not src[arg1] then | |
src[arg1] = arg2 | |
elseif src[ arg1 ] ~= arg2 then | |
print( "ERROR (table.decorate): Extension failed because key "..arg1.." exists.") | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- table.override and table.extend are very similar, but are made different | |
-- routines so that they wouldn't be confused | |
-- Author:Nenad Katic<br> | |
-------------------------------------------------------------------------------- | |
function M.extend( src, dest ) | |
for k,v in pairs( src) do | |
if not dest[k] then | |
dest[k] = v | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Copies and overrides properties from src to dest.<br> | |
-- If onlyExistingKeys is true, it *only* overrides the properties.<br> | |
-- Author:Nenad Katic<br> | |
-------------------------------------------------------------------------------- | |
function M.override( src, dest, onlyExistingKeys ) | |
for k,v in pairs( src ) do | |
if not onlyExistingKeys then | |
dest[k] = v | |
elseif dest[k] then | |
-- override only existing keys if asked for | |
dest[k] = v | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the position found by searching for a matching value from the array. | |
-- @param array table array | |
-- @param value Search value | |
-- @return If one is found the index. 0 if not found. | |
-------------------------------------------------------------------------------- | |
function M.indexOf(array, value) | |
for i, v in ipairs(array) do | |
if v == value then | |
return i | |
end | |
end | |
return 0 | |
end | |
-------------------------------------------------------------------------------- | |
-- Same as indexOf, only for key values (slower) | |
-- Author:Nenad Katic<br> | |
-------------------------------------------------------------------------------- | |
function M.keyOf( src, val ) | |
for k, v in pairs( src ) do | |
if v == val then | |
return k | |
end | |
end | |
return nil | |
end | |
-------------------------------------------------------------------------------- | |
-- The shallow copy of the table. | |
-- @param src copy | |
-- @param dest (option)Destination | |
-- @return dest | |
-------------------------------------------------------------------------------- | |
function M.copy(src, dest) | |
dest = dest or {} | |
for i, v in pairs(src) do | |
dest[i] = v | |
end | |
return dest | |
end | |
-------------------------------------------------------------------------------- | |
-- The deep copy of the table. | |
-- @param src copy | |
-- @param dest (option)Destination | |
-- @return dest | |
-------------------------------------------------------------------------------- | |
function M.deepCopy(src, dest) | |
dest = dest or {} | |
for k, v in pairs(src) do | |
if type(v) == "table" then | |
dest[k] = M.deepCopy(v) | |
else | |
dest[k] = v | |
end | |
end | |
return dest | |
end | |
-------------------------------------------------------------------------------- | |
-- Adds an element to the table. | |
-- If the element was present, the element will return false without the need for additional. | |
-- If the element does not exist, and returns true add an element. | |
-- @param t table | |
-- @param o element | |
-- @return If it already exists, false. If you add is true. | |
-------------------------------------------------------------------------------- | |
function M.insertElement(t, o) | |
if M.indexOf(t, o) > 0 then | |
return false | |
end | |
M.insert(t, o) | |
return true | |
end | |
-------------------------------------------------------------------------------- | |
-- This removes the element from the table. | |
-- If you have successfully removed, it returns the index of the yuan. | |
-- If there is no element, it returns 0. | |
-- @param t table | |
-- @param o element | |
-- @return index | |
-------------------------------------------------------------------------------- | |
function M.removeElement(t, o) | |
local i = M.indexOf(t, o) | |
if i == 0 then | |
return 0 | |
end | |
M.remove(t, i) | |
return i | |
end | |
return M | |
end) | |
package.preload['hp/layout/BaseLayout'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- GUIコンポーネントのレイアウトを更新するためのクラスです. | |
-- レイアウトクラスは、コンポーネントに対する参照を持ちません. | |
-- また、コンポーネント間で共有してもいいように実装しなければなりません. | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local PropertyUtil = require "hp/util/PropertyUtil" | |
-- class | |
local M = class() | |
-------------------------------------------------------------------------------- | |
-- コンストラクタです | |
-------------------------------------------------------------------------------- | |
function M:init(params) | |
self:initInternal(params) | |
self:copyParams(params) | |
end | |
-------------------------------------------------------------------------------- | |
-- 内部変数の初期化処理です. | |
-------------------------------------------------------------------------------- | |
function M:initInternal(params) | |
end | |
-------------------------------------------------------------------------------- | |
-- レイアウトの更新処理を行います. | |
-- デフォルトでは何もしません. | |
-- 継承するクラスで実装してください. | |
-------------------------------------------------------------------------------- | |
function M:update(parent) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the parameter setter function. | |
-- @param params Parameter is set to Object.<br> | |
-------------------------------------------------------------------------------- | |
function M:copyParams(params) | |
if params then | |
PropertyUtil.setProperties(self, params, true) | |
end | |
end | |
return M end) | |
package.preload['hp/layout/BoxLayout'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- 表示オブジェクトの位置やサイズのレイアウトを更新する為のクラスです. | |
-- このクラスでは、Box形式のオブジェクトを水平、垂直方向に配置する事が可能です. | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local BaseLayout = require "hp/layout/BaseLayout" | |
-- class | |
local super = BaseLayout | |
local M = class(super) | |
-- constraints | |
-- Horizotal Align | |
M.HORIZOTAL_LEFT = "left" | |
M.HORIZOTAL_CENTER = "center" | |
M.HORIZOTAL_RIGHT = "right" | |
-- Vertical Align | |
M.VERTICAL_TOP = "top" | |
M.VERTICAL_CENTER = "center" | |
M.VERTICAL_BOTTOM = "bottom" | |
-- Direction | |
M.DIRECTION_VERTICAL = "vertical" | |
M.DIRECTION_HORIZOTAL = "horizotal" | |
-------------------------------------------------------------------------------- | |
-- 内部変数の初期化処理です. | |
-------------------------------------------------------------------------------- | |
function M:initInternal(params) | |
self._horizotalAlign = M.HORIZOTAL_LEFT | |
self._horizotalGap = 5 | |
self._verticalAlign = M.VERTICAL_TOP | |
self._verticalGap = 5 | |
self._paddingTop = 0 | |
self._paddingBottom = 0 | |
self._paddingLeft = 0 | |
self._paddingRight = 0 | |
self._direction = M.DIRECTION_VERTICAL | |
self._parentResizable = true | |
end | |
-------------------------------------------------------------------------------- | |
-- 指定した親コンポーネントのレイアウトを更新します. | |
-------------------------------------------------------------------------------- | |
function M:update(parent) | |
if self._direction == M.DIRECTION_VERTICAL then | |
self:updateVertical(parent) | |
elseif self._direction == M.DIRECTION_HORIZOTAL then | |
self:updateHorizotal(parent) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- 垂直方向に子オブジェクトを配置します. | |
-------------------------------------------------------------------------------- | |
function M:updateVertical(parent) | |
local children = parent:getChildren() | |
local childrenWidth, childrenHeight = self:getVerticalLayoutSize(children) | |
local parentWidth, parentHeight = parent:getSize() | |
local parentWidth = parentWidth > childrenWidth and parentWidth or childrenWidth | |
local parentHeight = parentHeight > childrenHeight and parentHeight or childrenHeight | |
if self._parentResizable then | |
parent:setSize(parentWidth, parentHeight) | |
end | |
local childY = self:getChildY(parentHeight, childrenHeight) | |
for i, child in ipairs(children) do | |
if child.isIncludeLayout == nil or child:isIncludeLayout() then | |
local childWidth, childHeight = child:getSize() | |
local childX = self:getChildX(parentWidth, childWidth) | |
child:setPos(childX, childY) | |
childY = childY + childHeight + self._verticalGap | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- 水平方向に子オブジェクトを配置します. | |
-------------------------------------------------------------------------------- | |
function M:updateHorizotal(parent) | |
local children = parent:getChildren() | |
local childrenWidth, childrenHeight = self:getHorizotalLayoutSize(children) | |
local parentWidth, parentHeight = parent:getSize() | |
local parentWidth = parentWidth > childrenWidth and parentWidth or childrenWidth | |
local parentHeight = parentHeight > childrenHeight and parentHeight or childrenHeight | |
if self._parentResizable then | |
parent:setSize(parentWidth, parentHeight) | |
end | |
local childX = self:getChildX(parentWidth, childrenWidth) | |
for i, child in ipairs(children) do | |
if child.isIncludeLayout == nil or child:isIncludeLayout() then | |
local childWidth, childHeight = child:getSize() | |
local childY = self:getChildY(parentHeight, childHeight) | |
child:setPos(childX, childY) | |
childX = childX + childWidth + self._horizotalGap | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- 上下左右の余白を設定します. | |
-------------------------------------------------------------------------------- | |
function M:setPadding(left, top, right, bottom) | |
self._paddingLeft = left or self._paddingTop | |
self._paddingTop = top or self._paddingTop | |
self._paddingRight = right or self._paddingRight | |
self._paddingBottom = bottom or self._paddingBottom | |
end | |
-------------------------------------------------------------------------------- | |
-- 上下左右の余白を設定します. | |
-------------------------------------------------------------------------------- | |
function M:getPadding() | |
return self._paddingLeft, self._paddingTop, self._paddingRight, self._paddingBottom | |
end | |
-------------------------------------------------------------------------------- | |
-- アラインを設定します. | |
-------------------------------------------------------------------------------- | |
function M:setAlign(horizotalAlign, verticalAlign) | |
self._horizotalAlign = horizotalAlign | |
self._verticalAlign = verticalAlign | |
end | |
-------------------------------------------------------------------------------- | |
-- アラインを返します. | |
-------------------------------------------------------------------------------- | |
function M:getAlign() | |
return self._horizotalAlign, self._verticalAlign | |
end | |
-------------------------------------------------------------------------------- | |
-- コンポーネントを配置する方向を設定します. | |
-------------------------------------------------------------------------------- | |
function M:setDirection(direction) | |
self._direction = direction | |
end | |
-------------------------------------------------------------------------------- | |
-- コンポーネントを配置する方向を返します. | |
-------------------------------------------------------------------------------- | |
function M:getDirection() | |
return self._direction | |
end | |
-------------------------------------------------------------------------------- | |
-- コンポーネントの間隔を設定します. | |
-------------------------------------------------------------------------------- | |
function M:setGap(horizotalGap, verticalGap) | |
self._horizotalGap = horizotalGap | |
self._verticalGap = verticalGap | |
end | |
-------------------------------------------------------------------------------- | |
-- コンポーネントの間隔を返します.. | |
-------------------------------------------------------------------------------- | |
function M:getGap() | |
return self._horizotalGap, self._verticalGap | |
end | |
-------------------------------------------------------------------------------- | |
-- 子オブジェクトのX座標を返します. | |
-------------------------------------------------------------------------------- | |
function M:getChildX(parentWidth, childWidth) | |
local diffWidth = parentWidth - childWidth | |
local x = 0 | |
if self._horizotalAlign == M.HORIZOTAL_LEFT then | |
x = self._paddingLeft | |
elseif self._horizotalAlign == M.HORIZOTAL_CENTER then | |
x = math.floor((diffWidth + self._paddingLeft - self._paddingRight) / 2) | |
elseif self._horizotalAlign == M.HORIZOTAL_RIGHT then | |
x = diffWidth - self._paddingRight | |
else | |
error("Not found direction!") | |
end | |
return x | |
end | |
-------------------------------------------------------------------------------- | |
-- 子オブジェクトのY座標を返します. | |
-------------------------------------------------------------------------------- | |
function M:getChildY(parentHeight, childHeight) | |
local diffHeight = parentHeight - childHeight | |
local y = 0 | |
if self._verticalAlign == M.VERTICAL_TOP then | |
y = self._paddingTop | |
elseif self._verticalAlign == M.VERTICAL_CENTER then | |
y = math.floor((diffHeight + self._paddingTop - self._paddingBottom) / 2) | |
elseif self._verticalAlign == M.VERTICAL_BOTTOM then | |
y = diffHeight - self._paddingBottom | |
else | |
error("Not found direction!") | |
end | |
return y | |
end | |
-------------------------------------------------------------------------------- | |
-- 垂直方向に子オブジェクトを配置した時の | |
-- 全体のレイアウトサイズを返します. | |
-------------------------------------------------------------------------------- | |
function M:getVerticalLayoutSize(children) | |
local width = self._paddingLeft + self._paddingRight | |
local height = self._paddingTop + self._paddingBottom | |
local count = 0 | |
for i, child in ipairs(children) do | |
if child.isIncludeLayout == nil or child:isIncludeLayout() then | |
local cWidth, cHeight = child:getSize() | |
height = height + cHeight + self._verticalGap | |
width = math.max(width, cWidth) | |
count = count + 1 | |
end | |
end | |
if count > 1 then | |
height = height - self._verticalGap | |
end | |
return width, height | |
end | |
-------------------------------------------------------------------------------- | |
-- 水平方向に子オブジェクトを配置した時の | |
-- 全体のレイアウトサイズを返します. | |
-------------------------------------------------------------------------------- | |
function M:getHorizotalLayoutSize(children) | |
local width = self._paddingLeft + self._paddingRight | |
local height = self._paddingTop + self._paddingBottom | |
local count = 0 | |
for i, child in ipairs(children) do | |
if child.isIncludeLayout == nil or child:isIncludeLayout() then | |
local cWidth, cHeight = child:getSize() | |
width = width + cWidth + self._horizotalGap | |
height = math.max(height, cHeight) | |
count = count + 1 | |
end | |
end | |
if count > 1 then | |
width = width - self._horizotalGap | |
end | |
return width, height | |
end | |
return M end) | |
package.preload['hp/layout/HBoxLayout'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- デフォルトで水平方向にオブジェクトを配置するBoxLayoutです | |
-------------------------------------------------------------------------------- | |
-- import | |
local class = require "hp/lang/class" | |
local BoxLayout = require "hp/layout/BoxLayout" | |
-- class define | |
local super = BoxLayout | |
local M = class(super) | |
-------------------------------------------------------------------------------- | |
-- 内部変数の初期化処理を行います. | |
-------------------------------------------------------------------------------- | |
function M:initInternal(params) | |
super.initInternal(self, params) | |
self._direction = BoxLayout.DIRECTION_HORIZOTAL | |
end | |
return M end) | |
package.preload['hp/layout/VBoxLayout'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- デフォルトで垂直方向にオブジェクトを配置するBoxLayoutです | |
-------------------------------------------------------------------------------- | |
-- import | |
local class = require "hp/lang/class" | |
local BoxLayout = require "hp/layout/BoxLayout" | |
-- class define | |
local super = BoxLayout | |
local M = class(super) | |
-------------------------------------------------------------------------------- | |
-- 内部変数の初期化処理を行います. | |
-------------------------------------------------------------------------------- | |
function M:initInternal(params) | |
super.initInternal(self, params) | |
self._direction = BoxLayout.DIRECTION_VERTICAL | |
end | |
return M end) | |
package.preload['hp/manager/FocusManager'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This is a class to manage the Component. | |
-- TODO: Not used? | |
-------------------------------------------------------------------------------- | |
local class = require "hp/lang/class" | |
local Event = require "hp/event/Event" | |
local EventDispatcher = require "hp/event/EventDispatcher" | |
local M = EventDispatcher() | |
-------------------------------------------------------------------------------- | |
-- コンポーネントにフォーカスをセットします. | |
-------------------------------------------------------------------------------- | |
function M:setFocus(component) | |
if component == self.focusedComponent then | |
return | |
end | |
if not component:isFocusEnabled() then | |
return | |
end | |
if self.focusedComponent then | |
self.focusedComponent:dispatchEvent(Event.FOCUS_OUT) | |
end | |
self.focusedComponent = component | |
if self.focusedComponent then | |
self.focusedComponent:dispatchEvent(Event.FOCUS_IN) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- フォーカスがセットされているコンポーネントを返します. | |
-------------------------------------------------------------------------------- | |
function M:getFocus() | |
return self.focusedComponent | |
end | |
return M | |
end) | |
package.preload['hp/manager/FontManager'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This is a class to manage the Font. | |
-------------------------------------------------------------------------------- | |
-- import | |
local ResourceManager = require "hp/manager/ResourceManager" | |
-- class | |
local M = {} | |
-- variables | |
M.cache = {} | |
M.fontPaths = { | |
["VL-PGothic"] = "fonts/VL-PGothic.ttf", | |
["arial-rounded"] = "fonts/arial-rounded.ttf", | |
} | |
local function generateUid(fontPath, points, charcodes, dpi) | |
return (fontPath or "") .. "$" .. (points or "") .. "$" .. (charcodes or "") .. "$" .. (dpi or "") | |
end | |
-------------------------------------------------------------------------------- | |
-- Requests the texture. | |
-- The textures are cached internally. | |
-- @param fontName fontName or fontPath. | |
-- @param points Points of the Font. | |
-- @param charcodes Charcodes of the Font. | |
-- @param dpi dpi of the Font. | |
-- @return MOAIFont instance. | |
-------------------------------------------------------------------------------- | |
function M:request(fontName, points, charcodes, dpi) | |
local path = ResourceManager:getFilePath(M.fontPaths[fontName] or fontName) | |
local uid = generateUid(path, points, charcodes, dpi) | |
if self.cache[uid] then | |
return M.cache[uid] | |
end | |
local font = self:newFont(path, points, charcodes, dpi) | |
self.cache[font.uid] = font | |
return font | |
end | |
-------------------------------------------------------------------------------- | |
-- Return you have generated the font. | |
-- @param fontName fontName or fontPath. | |
-- @param points Points of the Font. | |
-- @param charcodes Charcodes of the Font. | |
-- @param dpi dpi of the Font. | |
-- @return MOAIFont instance. | |
-------------------------------------------------------------------------------- | |
function M:newFont(fontName, points, charcodes, dpi) | |
local path = ResourceManager:getFilePath(M.fontPaths[fontName] or fontName) | |
local font = MOAIFont.new() | |
font:load(path) | |
font.path = path | |
font.points = points | |
font.charcodes = charcodes | |
font.dpi = dpi | |
font.uid = generateUid(path, points, charcodes, dpi) | |
if points and charcodes then | |
font:preloadGlyphs(charcodes, points, dpi) | |
end | |
return font | |
end | |
return M | |
end) | |
package.preload['hp/manager/InputManager'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- To catch the operation of the screen, and sends the event. <br> | |
-------------------------------------------------------------------------------- | |
local table = require("hp/lang/table") | |
local Event = require("hp/event/Event") | |
local EventDispatcher = require("hp/event/EventDispatcher") | |
local M = EventDispatcher() | |
local pointer = {x = 0, y = 0, down = false} | |
local keyboard = {key = 0, down = false} | |
local touchEventStack = {} | |
local TOUCH_EVENTS = {} | |
TOUCH_EVENTS[MOAITouchSensor.TOUCH_DOWN] = Event.TOUCH_DOWN | |
TOUCH_EVENTS[MOAITouchSensor.TOUCH_UP] = Event.TOUCH_UP | |
TOUCH_EVENTS[MOAITouchSensor.TOUCH_MOVE] = Event.TOUCH_MOVE | |
TOUCH_EVENTS[MOAITouchSensor.TOUCH_CANCEL] = Event.TOUCH_CANCEL | |
local function onTouch(eventType, idx, x, y, tapCount) | |
-- event | |
local event = touchEventStack[idx] or Event(TOUCH_EVENTS[eventType], M) | |
local oldX, oldY = event.x, event.y | |
event.type = TOUCH_EVENTS[eventType] | |
event.idx = idx | |
event.x = x | |
event.y = y | |
event.tapCount = tapCount | |
if eventType == MOAITouchSensor.TOUCH_DOWN then | |
touchEventStack[idx] = event | |
elseif eventType == MOAITouchSensor.TOUCH_UP then | |
touchEventStack[idx] = nil | |
elseif eventType == MOAITouchSensor.TOUCH_MOVE then | |
if oldX == nil or oldY == nil then | |
return | |
end | |
event.moveX = event.x - oldX | |
event.moveY = event.y - oldY | |
touchEventStack[idx] = event | |
elseif eventType == MOAITouchSensor.TOUCH_CANCEL then | |
touchEventStack[idx] = nil | |
end | |
M:dispatchEvent(event) | |
end | |
local function onPointer(x, y) | |
pointer.x = x | |
pointer.y = y | |
if pointer.down then | |
onTouch(MOAITouchSensor.TOUCH_MOVE, 1, x, y, 1) | |
end | |
end | |
local function onClick(down) | |
pointer.down = down | |
local eventType = nil | |
if down then | |
eventType = MOAITouchSensor.TOUCH_DOWN | |
else | |
eventType = MOAITouchSensor.TOUCH_UP | |
end | |
onTouch(eventType, 1, pointer.x, pointer.y, 1) | |
end | |
local function onKeyboard(key, down) | |
keyboard.key = key | |
keyboard.down = down | |
local etype = down and Event.KEY_DOWN or Event.KEY_UP | |
local event = Event:new(etype, M) | |
event.key = key | |
M:dispatchEvent(event) | |
end | |
-------------------------------------------------------------------------------- | |
-- Initialize InputManager. <br> | |
-- Register a callback function for input operations. | |
-------------------------------------------------------------------------------- | |
function M:initialize() | |
-- コールバック関数の登録 | |
if MOAIInputMgr.device.pointer then | |
-- mouse input | |
MOAIInputMgr.device.pointer:setCallback(onPointer) | |
MOAIInputMgr.device.mouseLeft:setCallback(onClick) | |
else | |
-- touch input | |
MOAIInputMgr.device.touch:setCallback(onTouch) | |
end | |
-- keyboard input | |
if MOAIInputMgr.device.keyboard then | |
MOAIInputMgr.device.keyboard:setCallback(onKeyboard) | |
end | |
end | |
function M:isKeyDown(key) | |
if MOAIInputMgr.device.keyboard then | |
return MOAIInputMgr.device.keyboard:keyIsDown(key) | |
end | |
end | |
return M | |
end) | |
package.preload['hp/manager/LayoutManager'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- UIComponentのレイアウトを管理するマネージャです. | |
-------------------------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local PriorityQueue = require "hp/util/PriorityQueue" | |
local Executors = require "hp/util/Executors" | |
-- module | |
local M = {} | |
-------------------------------------------------------------------------------- | |
-- private | |
-------------------------------------------------------------------------------- | |
-- 比較関数 | |
local ascComparetor = function(a, b) | |
local alevel = a:getNestLevel() | |
local blevel = b:getNestLevel() | |
if alevel < blevel then | |
return -1 | |
elseif alevel == blevel then | |
return 0 | |
else | |
return 1 | |
end | |
end | |
-- 比較関数 | |
local descComparetor = function(a, b) | |
return ascComparetor(a, b) * -1 | |
end | |
-- queue | |
local invalidateDisplayQueue = PriorityQueue(descComparetor) | |
local invalidateLayoutQueue = PriorityQueue(descComparetor) | |
-- flag | |
local invalidateDisplayFlag = false | |
local invalidateLayoutFlag = false | |
-- 表示の更新 | |
local function validateDisplay() | |
local object = invalidateDisplayQueue:poll() | |
while object do | |
object:validateDisplay() | |
object = invalidateDisplayQueue:poll() | |
end | |
end | |
-- レイアウトの検証実施 | |
local function validateLayout() | |
local object = invalidateLayoutQueue:poll() | |
while object do | |
object:validateLayout() | |
object = invalidateLayoutQueue:poll() | |
end | |
end | |
-- フレーム処理 | |
local function enterFrame() | |
if invalidateDisplayFlag then | |
validateDisplay() | |
invalidateDisplayFlag = false | |
end | |
if invalidateLayoutFlag then | |
validateLayout() | |
invalidateLayoutFlag = false | |
end | |
end | |
-- event handler | |
Executors.callLoop(enterFrame) | |
-------------------------------------------------------------------------------- | |
-- public functions | |
-------------------------------------------------------------------------------- | |
--------------------------------------- | |
-- invalidateDisplayをスケジューリングします. | |
--------------------------------------- | |
function M:invalidateDisplay(object) | |
invalidateDisplayFlag = true | |
invalidateDisplayQueue:push(object) | |
end | |
--------------------------------------- | |
-- invalidateLayoutをスケジューリングします. | |
--------------------------------------- | |
function M:invalidateLayout(object) | |
invalidateLayoutFlag = true | |
invalidateLayoutQueue:push(object) | |
end | |
return M | |
end) | |
package.preload['hp/manager/ResourceManager'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This is a class to manage the resources.<br> | |
-------------------------------------------------------------------------------- | |
local table = require("hp/lang/table") | |
local M = {} | |
local paths = {} | |
local SEPARETOR = "/" | |
-------------------------------------------------------------------------------- | |
-- Add the resource directory path. | |
-------------------------------------------------------------------------------- | |
function M:addPath(path) | |
table.insertElement(paths, path) | |
end | |
-------------------------------------------------------------------------------- | |
-- Remove the resource directory path. | |
-------------------------------------------------------------------------------- | |
function M:removePath(path) | |
return table.removeElement(paths, path) | |
end | |
-------------------------------------------------------------------------------- | |
-- Clear the resource directory paths. | |
-------------------------------------------------------------------------------- | |
function M:clearPaths() | |
paths = {} | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the filePath from fileName. | |
-------------------------------------------------------------------------------- | |
function M:getFilePath(fileName, defaultPath) | |
if MOAIFileSystem.checkFileExists(fileName) then | |
return fileName | |
end | |
for i, path in ipairs(paths) do | |
local filePath = path .. SEPARETOR .. fileName | |
if MOAIFileSystem.checkFileExists(filePath) then | |
return filePath | |
end | |
end | |
if not defaultPath then | |
error("File not found error!") | |
end | |
return defaultPath | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the file data. | |
-------------------------------------------------------------------------------- | |
function M:readFile(fileName) | |
local path = self:getFilePath(fileName) | |
local input = assert(io.input(path)) | |
local data = input:read("*a") | |
input:close() | |
return data | |
end | |
return M end) | |
package.preload['hp/manager/SceneManager'] = (function (...) | |
---------------------------------------------------------------- | |
-- This is a class to manage the Scene. <br> | |
-- Order to manage the rendering of the scene and event notification. <br> | |
---------------------------------------------------------------- | |
-- import | |
local table = require "hp/lang/table" | |
local SceneAnimation = require "hp/display/SceneAnimation" | |
local SceneFactory = require "hp/factory/SceneFactory" | |
local InputManager = require "hp/manager/InputManager" | |
local Event = require "hp/event/Event" | |
local EventDispatcher = require "hp/event/EventDispatcher" | |
local Logger = require "hp/util/Logger" | |
local Executors = require "hp/util/Executors" | |
-- singleton class | |
local M = EventDispatcher() | |
-- constranits | |
local LOG_TAG = "SceneManager" | |
-- private var | |
local scenes = {} | |
local sceneFactory = SceneFactory | |
local currentScene = nil | |
local currentClosing = false | |
local nextScene = nil | |
local closingScene = nil | |
local transitioning = false | |
local sceneAnimation = nil | |
local renderTable = {} | |
local updateRenderFlag = false | |
local backgroundLayers = {} | |
local frontLayers = {} | |
local function updateRender() | |
renderTable = {} | |
-- background | |
for i, layer in ipairs(backgroundLayers) do | |
table.insert(renderTable, layer) | |
end | |
-- scene | |
for i, scene in ipairs(scenes) do | |
if scene.visible then | |
table.insert(renderTable, scene:getRenderTable()) | |
end | |
end | |
-- front | |
for i, layer in ipairs(frontLayers) do | |
table.insert(renderTable, layer) | |
end | |
MOAIRenderMgr.setRenderTable(renderTable) | |
end | |
local function onTouchDown(e) | |
if currentScene and not transitioning then | |
currentScene:onTouchDown(e) | |
end | |
end | |
local function onTouchUp(e) | |
if currentScene and not transitioning then | |
currentScene:onTouchUp(e) | |
end | |
end | |
local function onTouchMove(e) | |
if currentScene and not transitioning then | |
currentScene:onTouchMove(e) | |
end | |
end | |
local function onTouchCancel(e) | |
if currentScene and not transitioning then | |
currentScene:onTouchCancel(e) | |
end | |
end | |
local function onKeyDown(e) | |
if currentScene and not transitioning then | |
currentScene:onKeyDown(e) | |
end | |
end | |
local function onKeyUp(e) | |
if currentScene and not transitioning then | |
currentScene:onKeyUp(e) | |
end | |
end | |
local function onEnterFrame() | |
if updateRenderFlag then | |
updateRenderFlag = false | |
updateRender() | |
end | |
local currentScene = currentScene | |
if currentScene and not transitioning then | |
currentScene:onEnterFrame() | |
end | |
end | |
local function addScene(scene) | |
if table.indexOf(scenes, scene) == 0 then | |
table.insert(scenes, scene) | |
end | |
end | |
local function removeScene(scene) | |
local i = table.indexOf(scenes, scene) | |
if i > 0 then | |
table.remove(scenes, i) | |
end | |
end | |
local function hideScene(scene) | |
if scene then | |
scene:setVisible(false) | |
end | |
end | |
local function showScene(scene) | |
if scene then | |
scene:setVisible(true) | |
scene:setLeft(0) | |
scene:setTop(0) | |
scene:setColor(1, 1, 1, 1) | |
scene:setScl(1, 1, 1) | |
scene:setRot(0, 0, 0) | |
end | |
end | |
local function animateScene(params, completeFunc) | |
updateRenderFlag = true | |
local animation = params.animation | |
if animation then | |
if type(animation) == "string" then | |
animation = SceneAnimation[animation] | |
end | |
transitioning = true | |
animation(currentScene, nextScene, params):play({onComplete = completeFunc}) | |
else | |
hideScene(currentScene) | |
showScene(nextScene) | |
completeFunc() | |
end | |
end | |
local function openComplete() | |
if currentScene and currentClosing then | |
removeScene(currentScene) | |
currentScene:onDestroy() | |
end | |
currentScene = nextScene | |
currentScene:onStart() | |
currentScene:onResume() | |
M:updateRender() | |
transitioning = false | |
end | |
local function closeComplete() | |
removeScene(closingScene) | |
closingScene:onDestroy() | |
closingScene = nil | |
currentScene = nextScene or currentScene | |
currentScene = #scenes > 0 and currentScene or nil | |
if currentScene then | |
currentScene:onResume() | |
end | |
M:updateRender() | |
transitioning = false | |
end | |
local function initialize() | |
InputManager:addEventListener(Event.TOUCH_DOWN, onTouchDown) | |
InputManager:addEventListener(Event.TOUCH_UP, onTouchUp) | |
InputManager:addEventListener(Event.TOUCH_MOVE, onTouchMove) | |
InputManager:addEventListener(Event.TOUCH_CANCEL, onTouchCancel) | |
InputManager:addEventListener(Event.KEY_DOWN, onKeyDown) | |
InputManager:addEventListener(Event.KEY_UP, onKeyUp) | |
Executors.callLoop(onEnterFrame) | |
end | |
initialize() | |
-------------------------------------------------------------------------------- | |
-- Open a new scene. <br> | |
-- The current scene is the stack intact. <br> | |
-- But if set to true currentClosing, close the current scene. <br> | |
-- <br> | |
-- You can specify the behavior in the argument params. <br> | |
-- 1. params.sceneClass <br> | |
-- Specifies the class of scenes to be generated. <br> | |
-- 2. params.animation <br> | |
-- Specifies the animation of the scene transitions. <br> | |
-- 3. params.sec <br> | |
-- Specifies the time of the animation.<br> | |
-- 4. params.currentClosing <br> | |
-- Specify whether to close the current scene. <br> | |
-- | |
-- @param sceneName The unique name of the scene. Scene module path. | |
-- @param params (option)Parameters that define the behavior. | |
-- @return If you generate a return to the scene. | |
-------------------------------------------------------------------------------- | |
function M:openScene(sceneName, params) | |
if transitioning then | |
Logger.warn(LOG_TAG, "openScene()", "Scene transitioning!") | |
return | |
end | |
params = params or {} | |
currentClosing = params.currentClosing or false | |
-- get next scene | |
nextScene = self:findSceneByName(sceneName) | |
if nextScene then | |
nextScene = nil | |
return | |
end | |
-- stop current scene | |
if currentScene then | |
currentScene:onPause() | |
if currentClosing then | |
currentScene:onStop() | |
end | |
end | |
-- create scene | |
local scene = sceneFactory.createScene(sceneName, params) | |
scene:onCreate(params) | |
scene:setVisible(false) | |
addScene(scene) | |
nextScene = scene | |
animateScene(params, openComplete) | |
return nextScene | |
end | |
-------------------------------------------------------------------------------- | |
-- Open to the next scene. | |
-- The current scene will be closed. | |
-- See M:openScene(). | |
-- @param sceneName The unique name of the scene. Scene module path. | |
-- @param params (option)Parameters that define the behavior. | |
-- @return If you generate a return to the scene. | |
-------------------------------------------------------------------------------- | |
function M:openNextScene(sceneName, params) | |
params = params and params or {} | |
params.currentClosing = true | |
return self:openScene(sceneName, params) | |
end | |
-------------------------------------------------------------------------------- | |
-- Close the current scene. <br> | |
-- To resume the previous scene. | |
-- @param params (option)Parameters that define the behavior. | |
-------------------------------------------------------------------------------- | |
function M:closeScene(params) | |
if transitioning then | |
Logger.warn(LOG_TAG, "closeScene()", "Scene transitioning!") | |
return | |
end | |
if #scenes == 0 then | |
return | |
end | |
params = params and params or {} | |
closingScene = params.closingScene or currentScene | |
closingScene = type(closingScene) == "string" and self:findSceneByName(closingScene) or closingScene | |
if not closingScene then | |
return | |
end | |
nextScene = closingScene == currentScene and scenes[#scenes - 1] or nil | |
closingScene:onStop() | |
animateScene(params, closeComplete) | |
return nextScene | |
end | |
-------------------------------------------------------------------------------- | |
-- Update the drawing order of layers. <br> | |
-- Normally, you need to manipulate this function is not available. <br> | |
-- Timing to be updated, in fact, is done in EnterFrame. | |
-------------------------------------------------------------------------------- | |
function M:updateRender() | |
updateRenderFlag = true | |
end | |
-------------------------------------------------------------------------------- | |
-- Update the drawing order of layers. <br> | |
-- Normally, you need to manipulate this function is not available. | |
-------------------------------------------------------------------------------- | |
function M:forceUpdateRender() | |
updateRender() | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the scene to find the scene name. | |
-- @param sceneName Name of the target scene. | |
-- @return If a match is found the scene. | |
-------------------------------------------------------------------------------- | |
function M:findSceneByName(sceneName) | |
for i, scene in ipairs(scenes) do | |
if scene.name == sceneName then | |
return scene | |
end | |
end | |
return nil | |
end | |
-------------------------------------------------------------------------------- | |
-- Move to the front scene. <br> | |
-- @param scene Scene or scene name. | |
-------------------------------------------------------------------------------- | |
function M:orderToFront(scene) | |
if #scenes <= 1 or transitioning then | |
return | |
end | |
scene = type(scene) == "string" and self:findSceneByName(scene) or scene | |
local i = table.indexOf(scenes, scene) | |
if i > 0 then | |
table.remove(scenes, i) | |
table.insert(scenes, scene) | |
currentScene = scene | |
self:updateRender() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Move to the back scene. <br> | |
-- @param scene Scene or scene name. | |
-------------------------------------------------------------------------------- | |
function M:orderToBack(scene) | |
if #scenes <= 1 or transitioning then | |
return | |
end | |
scene = type(scene) == "string" and self:findSceneByName(scene) or scene | |
local i = table.indexOf(scenes, scene) | |
if i > 0 then | |
table.remove(scenes, i) | |
table.insert(scenes, 1, scene) | |
currentScene = scenes[#scenes] | |
self:updateRender() | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the SceneFactory. <br> | |
-- If you need to use your own factory. <br> | |
-- @param factory Scene factory module. | |
-------------------------------------------------------------------------------- | |
function M:setSceneFactory(factory) | |
sceneFactory = assert(factory, "sceneFactory is nil!") | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the current scene. <br> | |
-- @return currentScene. | |
-------------------------------------------------------------------------------- | |
function M:getCurrentScene() | |
return currentScene | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the transitioning. <br> | |
-- @return transitioning. | |
-------------------------------------------------------------------------------- | |
function M:isTransitioning() | |
return transitioning | |
end | |
-------------------------------------------------------------------------------- | |
-- Add the background Layer. <br> | |
-- @param layer layer | |
-------------------------------------------------------------------------------- | |
function M:addBackgroundLayer(layer) | |
M:updateRender() | |
return table.insertElement(backgroundLayers, layer) | |
end | |
-------------------------------------------------------------------------------- | |
-- remove the background Layer. <br> | |
-- @param layer layer | |
-------------------------------------------------------------------------------- | |
function M:removeBackgroundLayer(layer) | |
M:updateRender() | |
return table.removeElement(backgroundLayers, layer) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the background Layer. <br> | |
-- @param i Index. | |
-- @return layer. | |
-------------------------------------------------------------------------------- | |
function M:getBackgroundLayerAt(i) | |
return backgroundLayers[i] | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the background Layers. <br> | |
-- @return layers. | |
-------------------------------------------------------------------------------- | |
function M:getBackgroundLayers() | |
return backgroundLayers | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the size for background Layers. <br> | |
-- @return layer size | |
-------------------------------------------------------------------------------- | |
function M:getBackgroundLayerSize() | |
return #backgroundLayers | |
end | |
-------------------------------------------------------------------------------- | |
-- Add the front Layer. <br> | |
-- @param layer layer | |
-------------------------------------------------------------------------------- | |
function M:addFrontLayer(layer) | |
M:updateRender() | |
return table.insertElement(frontLayers, layer) | |
end | |
-------------------------------------------------------------------------------- | |
-- remove the front Layer. <br> | |
-- @param layer layer | |
-------------------------------------------------------------------------------- | |
function M:removeFrontLayer(layer) | |
M:updateRender() | |
return table.removeElement(frontLayers, layer) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the front Layer. <br> | |
-- @param i Index. | |
-- @return layer. | |
-------------------------------------------------------------------------------- | |
function M:getFrontLayerAt(i) | |
return frontLayers[i] | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the front Layers. <br> | |
-- @return layers. | |
-------------------------------------------------------------------------------- | |
function M:getFrontLayers() | |
return frontLayers | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the size for front Layers. <br> | |
-- @return layer size | |
-------------------------------------------------------------------------------- | |
function M:getFrontLayerSize() | |
return #frontLayers | |
end | |
return M end) | |
package.preload['hp/manager/ShaderManager'] = (function (...) | |
---------------------------------------------------------------- | |
-- This is a class to manage the Shader. <br> | |
-- This source has been implemented by Nenad Katic. <br> | |
-- Has been partially modified. <br> | |
---------------------------------------------------------------- | |
local ResourceManager = require("hp/manager/ResourceManager") | |
local M = {} | |
M.shaders = {} | |
M.BASIC_COLOR_SHADER = "simpleColor" | |
local function getFileData(filename) | |
return ResourceManager:readFile(filename) | |
end | |
function M:simpleColor() | |
if not MOAIGfxDevice.isProgrammable () then | |
return | |
end | |
local shader = MOAIShader.new () | |
local vsh = getFileData("hp/shader/shader_simple.vsh") | |
local fsh = getFileData("hp/shader/shader_simple.fsh") | |
shader:reserveUniforms(2) | |
shader:declareUniform(1, 'transform', MOAIShader.UNIFORM_WORLD_VIEW_PROJ ) | |
shader:declareUniform(2, 'ucolor', MOAIShader.UNIFORM_PEN_COLOR ) | |
shader:setVertexAttribute ( 1, 'position' ) | |
shader:setVertexAttribute ( 2, 'color' ) | |
shader:load ( vsh, fsh ) | |
return shader | |
end | |
function M:getShader(shaderName) | |
if self.shaders[shaderName] then | |
return self.shaders[shaderName] | |
end | |
local shader = self[shaderName](self) | |
self.shaders[shaderName] = shader | |
return shader | |
end | |
return M end) | |
package.preload['hp/manager/SoundManager'] = (function (...) | |
---------------------------------------------------------------- | |
-- This is a class to manage the MOAIUntzSound. | |
---------------------------------------------------------------- | |
local ResourceManager = require("hp/manager/ResourceManager") | |
local M = {} | |
local cache = {} | |
M.initialized = false | |
function M:initialize() | |
if not self.initialized then | |
MOAIUntzSystem.initialize() | |
self.initialized = true | |
end | |
end | |
---------------------------------------------------------------- | |
-- Returns the untz sound. <br> | |
-- @param path path | |
-- @param volume volume | |
-- @param looping looping | |
-- @return MOAIUntzSound instance. | |
---------------------------------------------------------------- | |
function M:getSound(path, volume, looping) | |
if not self.initialized then | |
self:initialize() | |
end | |
path = ResourceManager:getFilePath(path) | |
if cache[path] == nil then | |
local sound = MOAIUntzSound.new() | |
sound:load(path) | |
sound:setVolume(1) | |
sound:setLooping(false) | |
cache[path] = sound | |
end | |
local sound = cache[path] | |
if volume then | |
sound:setVolume(volume) | |
end | |
if looping then | |
sound:setLooping(looping) | |
end | |
return sound | |
end | |
return M end) | |
package.preload['hp/manager/TextureManager'] = (function (...) | |
--------------------------------------------------------------------------------------------------- | |
-- This is a class to manage the Texture. | |
--------------------------------------------------------------------------------------------------- | |
local ResourceManager = require("hp/manager/ResourceManager") | |
local Logger = require("hp/util/Logger") | |
local M = {} | |
local cache = {} | |
setmetatable(cache, {__mode = "v"}) | |
M.DEFAULT_FILTER = MOAITexture.GL_LINEAR | |
---------------------------------------------------------------- | |
-- Requests the texture. <br> | |
-- The textures are cached internally. | |
-- @param path path | |
-- @return MOAITexture instance. | |
---------------------------------------------------------------- | |
function M:request(path) | |
path = ResourceManager:getFilePath(path) | |
if cache[path] == nil then | |
local texture = MOAITexture.new() | |
texture:load(path) | |
texture.path = path | |
cache[path] = texture | |
if M.DEFAULT_FILTER then | |
texture:setFilter(M.DEFAULT_FILTER) | |
end | |
end | |
local texture = cache[path] | |
return cache[path] | |
end | |
return M | |
end) | |
package.preload['hp/manager/ThemeManager'] = (function (...) | |
---------------------------------------------------------------------------------------------------- | |
-- This is a class to manage Theme. | |
---------------------------------------------------------------------------------------------------- | |
-- import | |
local Event = require "hp/event/Event" | |
local EventDispatcher = require "hp/event/EventDispatcher" | |
local Theme = require "hp/gui/Theme" | |
-- class define | |
local M = EventDispatcher() | |
local theme = Theme | |
---------------------------------------------------------------- | |
-- Sets the default widget theme to use. | |
-- @param value Widget theme. | |
---------------------------------------------------------------- | |
function M:setTheme(value) | |
value = type(value) == "string" and dofile(value) or value | |
if theme ~= value then | |
theme = value | |
self:dispatchEvent("themeChanged") | |
end | |
end | |
---------------------------------------------------------------- | |
-- Returns the current default theme. | |
-- @return GuiTheme. | |
---------------------------------------------------------------- | |
function M:getTheme() | |
return theme | |
end | |
---------------------------------------------------------------- | |
-- Returns the current default theme. | |
-- @return component theme. | |
---------------------------------------------------------------- | |
function M:getComponentTheme(name) | |
return theme[name] | |
end | |
return M end) | |
package.preload['hp/physics/PhysicsBody'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- Class that inherits from MOAIBox2DBody.<br> | |
-------------------------------------------------------------------------------- | |
local table = require("hp/lang/table") | |
local class = require("hp/lang/class") | |
local Event = require("hp/event/Event") | |
local EventDispatcher = require("hp/event/EventDispatcher") | |
local PhysicsFixture = require("hp/physics/PhysicsFixture") | |
local M = class(EventDispatcher) | |
local Interface = MOAIBox2DBody.getInterfaceTable() | |
M.DEFAULT_FIXTURE_PARAMS = { | |
density = 1, | |
friction = 0.3, | |
restitution = 0, | |
filter = {categoryBits = 1, maskBits = nil, groupIndex = nil}, | |
sensor = false, | |
center = {x = 0, y = 0} | |
} | |
M.PHASE = {} | |
M.PHASE[MOAIBox2DArbiter.BEGIN] = "begin" | |
M.PHASE[MOAIBox2DArbiter.END] = "end" | |
M.PHASE[MOAIBox2DArbiter.POST_SOLVE] = "postSolve" | |
M.PHASE[MOAIBox2DArbiter.PRE_SOLVE] = "preSolve" | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-- @param body MOAIBox2DBody instance. | |
-------------------------------------------------------------------------------- | |
function M:new(body) | |
table.copy(self, assert(body)) | |
if body.init then | |
body:init() | |
end | |
body.new = nil | |
body.init = nil | |
return body | |
end | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-------------------------------------------------------------------------------- | |
function M:init() | |
EventDispatcher.init(self) | |
self._fixtures = {} | |
end | |
-------------------------------------------------------------------------------- | |
-- Add the PhysicsData was created in PhysicsEditor. <br> | |
-- Partially, it is proprietary. | |
-- @param ... fixture datas | |
-------------------------------------------------------------------------------- | |
function M:addPhysicsData(...) | |
for i, data in ipairs({...}) do | |
if data.radius then | |
local fixture = self:addCircle(data.center.x, data.center.y, data.radius) | |
fixture:copyParams(data) | |
elseif data.shape == "rectangle" then | |
local fixture = self:addRect(data.xMin, data.yMin, data.xMax, data.yMax) | |
fixture:copyParams(data) | |
elseif type(data.shape) == "table" then | |
local fixture = self:addPolygon(data.shape) | |
fixture:copyParams(data) | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Add a circle. | |
-------------------------------------------------------------------------------- | |
function M:addCircle(x, y, radius) | |
local fixture = Interface.addCircle(self, x, y, radius) | |
fixture = PhysicsFixture(fixture) | |
fixture:copyParams(M.DEFAULT_FIXTURE_PARAMS) | |
table.insert(self:getFixtures(), fixture) | |
return fixture | |
end | |
-------------------------------------------------------------------------------- | |
-- Add the edge. | |
-------------------------------------------------------------------------------- | |
function M:addEdges(verts) | |
local fixture = Interface.addEdges(self, verts) | |
fixture = PhysicsFixture(fixture) | |
fixture:copyParams(M.DEFAULT_FIXTURE_PARAMS) | |
table.insert(self:getFixtures(), fixture) | |
return fixture | |
end | |
-------------------------------------------------------------------------------- | |
-- Adds a polygon. | |
-------------------------------------------------------------------------------- | |
function M:addPolygon(verts) | |
local fixture = Interface.addPolygon(self, verts) | |
fixture = PhysicsFixture(fixture) | |
fixture:copyParams(M.DEFAULT_FIXTURE_PARAMS) | |
table.insert(self:getFixtures(), fixture) | |
return fixture | |
end | |
-------------------------------------------------------------------------------- | |
-- Add a rectangle. | |
-------------------------------------------------------------------------------- | |
function M:addRect(xMin, yMin, xMax, yMax) | |
local fixture = Interface.addRect(self, xMin, yMin, xMax, yMax) | |
fixture = PhysicsFixture(fixture) | |
fixture:copyParams(M.DEFAULT_FIXTURE_PARAMS) | |
table.insert(self:getFixtures(), fixture) | |
return fixture | |
end | |
-------------------------------------------------------------------------------- | |
-- Search from the name, and returns the Fixture was the first match. | |
-- @param name Fixture name. | |
-- @return Fixture instance. | |
-------------------------------------------------------------------------------- | |
function M:findFixtureByName(name) | |
for i, v in self:getFixtures() do | |
if v:getName() == name then | |
return v | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Search from the name, it returns a list of Fixture match. | |
-- @param name Fixture name. | |
-- @return Fixture instance list. | |
-------------------------------------------------------------------------------- | |
function M:findFixturesByName(name) | |
local list = {} | |
for i, v in self:getFixtures() do | |
if v:getName() == name then | |
table.insert(list, v) | |
end | |
end | |
return list | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the Fixture for all. | |
-- @return Fixtures | |
-------------------------------------------------------------------------------- | |
function M:getFixtures() | |
return self._fixtures | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns a Fixture at the specified index. | |
-- @param i index | |
-- @return Fixture instance. | |
-------------------------------------------------------------------------------- | |
function M:getFixtureAt(i) | |
return self:getFixtures()[i] | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets angle. | |
-- @param angle angle | |
-------------------------------------------------------------------------------- | |
function M:setAngle(angle) | |
local x, y = self:getPosition() | |
self:setTransform(x, y, angle) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the position x. | |
-- @return x | |
-------------------------------------------------------------------------------- | |
function M:getX() | |
local x, y = self:getPosition() | |
return x | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the position x. | |
-- @param x position x. | |
-------------------------------------------------------------------------------- | |
function M:setX(x) | |
self:setTransform(x, self:getY(), self:getAngle()) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the position y. | |
-- @return y | |
-------------------------------------------------------------------------------- | |
function M:getY() | |
local x, y = self:getPosition() | |
return y | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the position y. | |
-- @param y position y. | |
-------------------------------------------------------------------------------- | |
function M:setY(y) | |
self:setTransform(self:getX(), y, self:getAngle()) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the position. | |
-- @param x position x. | |
-- @param y position y. | |
-------------------------------------------------------------------------------- | |
function M:setPos(x, y) | |
self:setTransform(x, y, self:getAngle()) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the position. | |
-- @return x, y. | |
-------------------------------------------------------------------------------- | |
function M:getPos() | |
return self:getPosition() | |
end | |
-------------------------------------------------------------------------------- | |
-- Adds the position. | |
-- @param x x position | |
-- @param x y position | |
-------------------------------------------------------------------------------- | |
function M:addPos(x, y) | |
self:setPos(x + self:getX(), y + self:getY()) | |
end | |
-------------------------------------------------------------------------------- | |
-- Adds an event listener. | |
-- Also responsible for handling of Fixture. | |
-------------------------------------------------------------------------------- | |
function M:addEventListener(eventType, callback, source, priority) | |
EventDispatcher.addEventListener(self, eventType, callback, source, priority) | |
if eventType == Event.COLLISION then | |
for i, fixture in ipairs(self:getFixtures()) do | |
fixture:setCollisionHandler(M.fixtureCollisionHandler, MOAIBox2DArbiter.ALL) | |
end | |
end | |
end | |
function M.fixtureCollisionHandler(phase, fixtureA, fixtureB, arbiter) | |
local bodyA = fixtureA:getBody() | |
local bodyB = fixtureB:getBody() | |
local bodyAListened = bodyA:hasEventListener(Event.COLLISION) | |
local bodyBListened = bodyB:hasEventListener(Event.COLLISION) | |
if bodyAListened or bodyBListened then | |
local e = Event(Event.COLLISION) | |
e.phase = M.PHASE[phase] | |
e.fixtureA = fixtureA | |
e.fixtureB = fixtureB | |
e.arbiter = arbiter | |
if bodyAListened then | |
bodyA:dispatchEvent(e) | |
end | |
if bodyBListened then | |
bodyB:dispatchEvent(e) | |
end | |
end | |
end | |
return M end) | |
package.preload['hp/physics/PhysicsFixture'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- Class that inherits from MOAIBox2DFixture.<br> | |
-------------------------------------------------------------------------------- | |
local table = require("hp/lang/table") | |
local class = require("hp/lang/class") | |
local M = class() | |
local Interface = MOAIBox2DFixture.getInterfaceTable() | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-- @param obj MOAIBox2DFixture instance. | |
-------------------------------------------------------------------------------- | |
function M:new(obj, ...) | |
table.copy(self, assert(obj)) | |
if obj.init then | |
obj:init(...) | |
end | |
obj.new = nil | |
obj.init = nil | |
return obj | |
end | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-------------------------------------------------------------------------------- | |
function M:init(params) | |
if params then | |
self:copyParams(params) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the parameter setter function. | |
-- @param params Parameter is set to Object.<br> | |
-- (params:pe_fixture_id, name, density, friction, restitution, filter) | |
-------------------------------------------------------------------------------- | |
function M:copyParams(params) | |
if params.pe_fixture_id then | |
self:setName(params.pe_fixture_id) | |
end | |
if params.name then | |
self:setName(params.name) | |
end | |
if params.density then | |
self:setDensity(params.density) | |
end | |
if params.friction then | |
self:setFriction(params.friction) | |
end | |
if params.restitution then | |
self:setRestitution(params.restitution) | |
end | |
if params.filter then | |
local filter = params.filter | |
self:setFilter(filter.categoryBits, filter.maskBits, filter.groupIndex) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Destroys the Fixture. | |
-------------------------------------------------------------------------------- | |
function M:destroy() | |
local body = self:getBody() | |
Interface.destroy(self) | |
local fixtures = body:getFixtures() | |
table.removeElement(fixtures, self) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the name. | |
-- @param name | |
-------------------------------------------------------------------------------- | |
function M:setName(name) | |
self._name = name | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the name. | |
-- @return name | |
-------------------------------------------------------------------------------- | |
function M:getName() | |
return self._name | |
end | |
return M end) | |
package.preload['hp/physics/PhysicsWorld'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- Class that inherits from MOAIBox2DWorld. <br> | |
-- Has been prepared to create an object, a useful function. | |
-------------------------------------------------------------------------------- | |
local table = require("hp/lang/table") | |
local class = require("hp/lang/class") | |
local EventDispatcher = require("hp/event/EventDispatcher") | |
local PhysicsBody = require("hp/physics/PhysicsBody") | |
local MOAIPropUtil = require("hp/util/MOAIPropUtil") | |
local M = class(EventDispatcher) | |
local Interface = MOAIBox2DWorld.getInterfaceTable() | |
-------------------------------------------------------------------------------- | |
-- This is the default parameter set to MOAIBox2DWorld. | |
-------------------------------------------------------------------------------- | |
M.DEFUALT_PARAMS = { | |
gravity = {0, 10}, | |
unitsToMeters = 0.06, | |
} | |
-------------------------------------------------------------------------------- | |
-- Constants representing the type of the Body. | |
-------------------------------------------------------------------------------- | |
M.BODY_TYPES = { | |
dynamic = MOAIBox2DBody.DYNAMIC, | |
static = MOAIBox2DBody.STATIC, | |
kinematic = MOAIBox2DBody.KINEMATIC | |
} | |
---------------------------------------------------------------- | |
-- Instance generating functions.<br> | |
-- Unlike an ordinary class, and based on the MOAI_CLASS.<br> | |
-- To inherit this function is not recommended.<br> | |
-- @param ... params. | |
-- @return instance. | |
---------------------------------------------------------------- | |
function M:new(...) | |
local obj = MOAIBox2DWorld.new() | |
table.copy(self, obj) | |
if obj.init then | |
obj:init(...) | |
end | |
obj.init = nil | |
obj.new = nil | |
return obj | |
end | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-- @param params | |
-------------------------------------------------------------------------------- | |
function M:init(params) | |
params = params or M.DEFUALT_PARAMS | |
self:copyParams(params) | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the parameter setter function. | |
-- @param params Parameter is set to Object.<br> | |
-- (params:gravity, unitsToMeters) | |
-------------------------------------------------------------------------------- | |
function M:copyParams(params) | |
if params.gravity then | |
self:setGravity(unpack(params.gravity)) | |
end | |
if params.unitsToMeters then | |
self:setUnitsToMeters(params.unitsToMeters) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Create a Body based on MOAIProp. | |
-- @param prop MOAIProp instance. | |
-- @param bodyType The type of the Body. | |
-- @param ... physicsDatas. Data that was created in PhysicsEditor can be used. | |
-- @return PhysicsBody instance. | |
-------------------------------------------------------------------------------- | |
function M:createBodyFromProp(prop, bodyType, ...) | |
local params = {...} | |
if #params == 0 then | |
table.insert(params, {shape == "rectangle"}) | |
end | |
local body = self:addBody(bodyType) | |
local width, height = MOAIPropUtil.getSize(prop) | |
local xMin, yMin, xMax, yMax = -width / 2, -height / 2, width / 2, height / 2 | |
for i, data in ipairs(params) do | |
data = table.copy(data) | |
data.shape = data.shape or "rectangle" | |
if data.shape == "rectangle" then | |
data.xMin = data.xMin or xMin | |
data.yMin = data.yMin or yMin | |
data.xMax = data.xMax or xMax | |
data.yMax = data.yMax or yMax | |
elseif data.shape == "circle" then | |
data.radius = data.radius or width / 2 | |
data.center = data.center or {x = 0, y = 0} | |
end | |
body:addPhysicsData(data) | |
end | |
MOAIPropUtil.setPos(prop, xMin, yMin) | |
prop:setParent(body) | |
prop.body = body | |
body.prop = prop | |
body:resetMassData() | |
return body | |
end | |
-------------------------------------------------------------------------------- | |
-- To create a rectangle. | |
-- @return PhysicsBody instance. | |
-------------------------------------------------------------------------------- | |
function M:createRect(left, top, width, height, params) | |
params = params or {} | |
local body = self:addBody(params.type) | |
local fixture = body:addRect(0, 0, width, height) | |
fixture:copyParams(params) | |
body:setPos(left, top) | |
body:resetMassData() | |
return body | |
end | |
-------------------------------------------------------------------------------- | |
-- Add the PhysicsBody object. | |
-- @param bodyType Can also be specified in the extended string. | |
-- @return PhysicsBody instance. | |
-------------------------------------------------------------------------------- | |
function M:addBody(bodyType) | |
bodyType = bodyType or "dynamic" | |
bodyType = type(bodyType) == "string" and M.BODY_TYPES[bodyType] or bodyType | |
return PhysicsBody(Interface.addBody(self, bodyType)) | |
end | |
return M end) | |
package.preload['hp/rpg/RPGMapView'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- RPG用のMapViewクラスです.<br> | |
-- マップで表示するオブジェクトがRPGSpriteになります. | |
-- @class table | |
-- @name RPGMapView | |
-------------------------------------------------------------------------------- | |
local table = require("hp/lang/table") | |
local class = require("hp/lang/class") | |
local TMXMapView = require("hp/tmx/TMXMapView") | |
local RPGSprite = require("hp/rpg/RPGSprite") | |
local M = class(TMXMapView) | |
-------------------------------------------------------------------------------- | |
-- コンストラクタです. | |
-- この段階では表示オブジェクトは生成しません. | |
-- loadMap関数を使用する事で、表示オブジェクトを生成します. | |
-------------------------------------------------------------------------------- | |
function M:init(resourceDirectory) | |
TMXMapView.init(self, resourceDirectory) | |
self.cameraToFocusObjectEnabled = true | |
end | |
-------------------------------------------------------------------------------- | |
-- 表示オブジェクトを作成します. | |
-------------------------------------------------------------------------------- | |
function M:createDisplayObject(object) | |
local tmxMap = self.tmxMap | |
local gid = object.gid | |
local tileset = tmxMap:findTilesetByGid(gid) | |
self:loadTexture(tileset) | |
local texture = tileset.texture | |
local tw, th = texture:getSize() | |
local spacing, margin = tileset.spacing, tileset.margin | |
local tilewidth, tileheight = tileset.tilewidth, tileset.tileheight | |
local tileCol = math.floor((tw + spacing) / tilewidth) | |
local tileRow = math.floor((th + spacing) / tileheight) | |
local sprite = RPGSprite:new({texture = texture, mapView = self}) | |
sprite.mapObject = object | |
sprite.mapType = object.type | |
sprite:setTiledSheets(tilewidth, tileheight, tileCol, tileRow) | |
sprite:setLeft(object.x) | |
sprite:setTop(object.y - sprite:getHeight()) | |
sprite:setIndex(object.gid - tileset.firstgid + 1) | |
if object.properties.playAnim then | |
sprite:playAnim(object.properties.playAnim) | |
end | |
if object.properties.moveType then | |
sprite:setMoveType(object.properties.moveType) | |
end | |
if object.properties.visible then | |
sprite:setVisible(toboolean(object.properties.visible)) | |
end | |
return sprite | |
end | |
-------------------------------------------------------------------------------- | |
-- マップ読み込み後、カメラの位置をプレイヤーの座標に設定します. | |
-------------------------------------------------------------------------------- | |
function M:loadMap(tmxMap) | |
TMXMapView.loadMap(self, tmxMap) | |
self.focusObject = self:findPlayerObject() | |
self.collisionLayer = self:findCollisionLayer() | |
self.eventLayer = self:findEventLayer() | |
self:scrollCameraToFocusObject() | |
end | |
-------------------------------------------------------------------------------- | |
-- フレーム毎の処理を行います. | |
-------------------------------------------------------------------------------- | |
function M:onEnterFrame() | |
-- object move | |
for i, layer in ipairs(self.objectLayers) do | |
for i, object in ipairs(layer.objects) do | |
if object.onEnterFrame then | |
object:onEnterFrame() | |
end | |
end | |
end | |
-- camera move | |
self:scrollCameraToFocusObject() | |
end | |
-------------------------------------------------------------------------------- | |
-- 指定した位置の衝突判定を行います. | |
-------------------------------------------------------------------------------- | |
function M:collisionWith(object, x, y, w, h) | |
if self:collisionWithMap(x, y, w, h) then | |
return true | |
end | |
if self:collisionWithObjects(object, x, y, w, h) then | |
return true | |
end | |
return false | |
end | |
-------------------------------------------------------------------------------- | |
-- 指定した位置と衝突判定レイヤーが衝突するか判定します. | |
-------------------------------------------------------------------------------- | |
function M:collisionWithMap(x, y, w, h) | |
if not self.collisionLayer then | |
return false | |
end | |
w = w or 1 | |
h = h or 1 | |
for ty = 1, h do | |
for tx = 1, w do | |
local gid = self.collisionLayer:getGid(x, y) | |
if gid and gid > 0 then | |
return true | |
end | |
end | |
end | |
return false | |
end | |
-------------------------------------------------------------------------------- | |
-- 指定した位置とオブジェクトが衝突するか判定します. | |
-------------------------------------------------------------------------------- | |
function M:collisionWithObjects(target, x, y, w, h) | |
w = w or 1 | |
h = h or 1 | |
for i, objectLayer in ipairs(self.objectLayers) do | |
for j, object in ipairs(objectLayer.objects) do | |
if target ~= object and object:isCollisionByMapPosition(x, y, w, h) then | |
return true | |
end | |
end | |
end | |
return false | |
end | |
-------------------------------------------------------------------------------- | |
-- Playerというnameのオブジェクトを検索して返します. | |
-------------------------------------------------------------------------------- | |
function M:findPlayerObject() | |
return self:findObjectByName("Player") | |
end | |
-------------------------------------------------------------------------------- | |
-- Collisionというnameのレイヤーを検索して返します. | |
-------------------------------------------------------------------------------- | |
function M:findCollisionLayer() | |
return self.tmxMap:findLayerByName("Collision") | |
end | |
-------------------------------------------------------------------------------- | |
-- Eventというnameのレイヤーを検索して返します. | |
-------------------------------------------------------------------------------- | |
function M:findEventLayer() | |
return self.tmxMap:findLayerByName("Event") | |
end | |
-------------------------------------------------------------------------------- | |
-- 指定した座標のオブジェクトを検索して、最初に見つかったオブジェクトを返します. | |
-------------------------------------------------------------------------------- | |
function M:findObjectByMapPosition(x, y, w, h) | |
for i, objectLayer in ipairs(self.objectLayers) do | |
for j, object in ipairs(objectLayer.objects) do | |
if object:isCollisionByMapPosition(x, y) then | |
return object | |
end | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- 指定した座標のオブジェクトを検索して返します. | |
-------------------------------------------------------------------------------- | |
function M:findObjectsByMapPosition(x, y) | |
local objects = {} | |
for i, objectLayer in ipairs(self.objectLayers) do | |
for j, object in ipairs(objectLayer.objects) do | |
if object:isCollisionByMapPosition(x, y) then | |
table.insert(objects, object) | |
end | |
end | |
end | |
return objects | |
end | |
-------------------------------------------------------------------------------- | |
-- カメラの位置をプレイヤーの座標まで移動します. | |
-------------------------------------------------------------------------------- | |
function M:scrollCameraToFocusObject() | |
if not self.cameraToFocusObjectEnabled then | |
return | |
end | |
if not self.focusObject then | |
return | |
end | |
local x, y = self.focusObject:getLoc() | |
self:scrollCameraToCenter(x, y) | |
end | |
return M end) | |
package.preload['hp/rpg/RPGSprite'] = (function (...) | |
---------------------------------------------------------------- | |
-- RPGMapView用のスプライトクラスです.<br> | |
-- @class table | |
-- @name RPGSprite | |
---------------------------------------------------------------- | |
local table = require("hp/lang/table") | |
local class = require("hp/lang/class") | |
local SpriteSheet = require("hp/display/SpriteSheet") | |
local Event = require("hp/event/Event") | |
local EventDispatcher = require("hp/event/EventDispatcher") | |
local RPGMoveFactory = require("hp/rpg/move/RPGMoveFactory") | |
local M = class(SpriteSheet) | |
-- constraints | |
-- Sheet animations | |
M.SHEET_ANIMS = { | |
{name = "walkDown", indexes = {2, 1, 2, 3, 2}, sec = 0.25}, | |
{name = "walkLeft", indexes = {5, 4, 5, 6, 5}, sec = 0.25}, | |
{name = "walkRight", indexes = {8, 7, 8, 9, 8}, sec = 0.25}, | |
{name = "walkUp", indexes = {11, 10, 11, 12, 11}, sec = 0.25}, | |
} | |
-- 移動方向 | |
M.DIR_NONE = "none" | |
M.DIR_LEFT = "left" | |
M.DIR_UP = "up" | |
M.DIR_RIGHT = "right" | |
M.DIR_DOWN = "down" | |
-- 移動方向と移動先座標のオフセット値 | |
M.DIR_NEXT = { | |
[M.DIR_NONE] = {0, 0}, | |
[M.DIR_LEFT] = {-1, 0}, | |
[M.DIR_UP] = {0, -1}, | |
[M.DIR_RIGHT] = {1, 0}, | |
[M.DIR_DOWN] = {0, 1}, | |
} | |
-- 移動方向とアニメーションの表 | |
M.DIR_ANIMS = { | |
[M.DIR_LEFT] = "walkLeft", | |
[M.DIR_UP] = "walkUp", | |
[M.DIR_RIGHT] = "walkRight", | |
[M.DIR_DOWN] = "walkDown", | |
} | |
-- 移動速度 | |
M.MOVE_SPEED = 2 | |
-- 移動タイプ | |
M.MOVE_NONE = "noneMove" | |
M.MOVE_RANDOM = "randomMove" | |
---------------------------------------------------------------- | |
-- インスタンスを生成して返します.<br> | |
-- @return インスタンス | |
---------------------------------------------------------------- | |
function M:init(params) | |
SpriteSheet.init(self, params) | |
self:setSheetAnims(self.SHEET_ANIMS) | |
self.mapView = assert(params.mapView) | |
self.mapTileWidth = self.mapView.tmxMap.tilewidth | |
self.mapTileHeight = self.mapView.tmxMap.tileheight | |
self.moveLogicFactory = RPGMoveFactory | |
self.moveSpeed = self.MOVE_SPEED | |
self.currentDirection = M.DIR_NONE | |
self.currentMoveX = 0 | |
self.currentMoveY = 0 | |
self.currentMoveCount = 0 | |
end | |
---------------------------------------------------------------- | |
-- フレーム更新処理を行います. | |
---------------------------------------------------------------- | |
function M:onEnterFrame() | |
-- 移動ロジックの処理 | |
local moveTypeFunc = self[self.moveType] | |
if moveTypeFunc then | |
moveTypeFunc(self) | |
end | |
-- 移動処理 | |
self:moveStep() | |
end | |
---------------------------------------------------------------- | |
-- マップ座標で衝突するか判定します. | |
---------------------------------------------------------------- | |
function M:isCollisionByMapPosition(targetX, targetY, targetW, targetH) | |
targetW = targetW or 1 | |
targetH = targetH or 1 | |
local mapX, mapY = self:getMapLoc() | |
local mapW, mapH = self:getMapSize() | |
for y = targetY, targetY + targetH - 1 do | |
for x = targetX, targetX + targetW - 1 do | |
if mapX <= x and x < mapX + mapW and mapY <= y and y < mapY + mapH then | |
return true | |
end | |
end | |
end | |
return false | |
end | |
---------------------------------------------------------------- | |
-- マップ座標で衝突するか判定します. | |
---------------------------------------------------------------- | |
function M:isCollisionByMapObject(obj) | |
local mapX, mapY = obj:getMapLoc() | |
local mapW, mapH = obj:getMapSize() | |
return self:isCollisionByMapPosition(mapX, mapY, mapW, mapH) | |
end | |
---------------------------------------------------------------- | |
-- 次に移動する予定のマップ上の座標を返します. | |
---------------------------------------------------------------- | |
function M:getNextMapLoc() | |
local mapX, mapY = self:getMapLoc() | |
local offsetMap = M.DIR_NEXT[self.currentDirection] or M.DIR_NEXT[M.DIR_NONE] | |
local offsetX, offsetY = offsetMap[1], offsetMap[2] | |
return mapX + offsetX, mapY + offsetY | |
end | |
---------------------------------------------------------------- | |
-- マップ上の座標を返します. | |
---------------------------------------------------------------- | |
function M:getMapLoc() | |
return self:getMapX(), self:getMapY() | |
end | |
---------------------------------------------------------------- | |
-- マップ上の座標を設定します. | |
---------------------------------------------------------------- | |
function M:setMapLoc(x, y) | |
self:setMapX(x) | |
self:setMapY(y) | |
end | |
---------------------------------------------------------------- | |
-- マップ上の座標を返します. | |
---------------------------------------------------------------- | |
function M:getMapX() | |
return math.floor(self:getLeft() / self.mapTileWidth) + 1 | |
end | |
---------------------------------------------------------------- | |
-- マップ上の座標を設定します. | |
---------------------------------------------------------------- | |
function M:setMapX(mapX) | |
local x = (mapX - 1) * self.mapTileWidth | |
self:setLeft(x) | |
end | |
---------------------------------------------------------------- | |
-- マップ上の座標を返します. | |
---------------------------------------------------------------- | |
function M:getMapY() | |
return math.floor(self:getTop() / self.mapTileHeight) + 1 | |
end | |
---------------------------------------------------------------- | |
-- マップ上の座標を設定します. | |
---------------------------------------------------------------- | |
function M:setMapY(mapY) | |
local y = (mapY - 1) * self.mapTileHeight | |
self:setTop(y) | |
end | |
---------------------------------------------------------------- | |
-- マップ上の幅を返します. | |
---------------------------------------------------------------- | |
function M:getMapSize() | |
return self:getMapWidth(), self:getMapHeight() | |
end | |
---------------------------------------------------------------- | |
-- マップ上の幅を返します. | |
---------------------------------------------------------------- | |
function M:getMapWidth() | |
return math.ceil(self:getWidth() / self.mapTileWidth) | |
end | |
---------------------------------------------------------------- | |
-- マップ上の高さを返します. | |
---------------------------------------------------------------- | |
function M:getMapHeight() | |
return math.ceil(self:getHeight() / self.mapTileHeight) | |
end | |
---------------------------------------------------------------- | |
-- 移動区分を設定します. | |
---------------------------------------------------------------- | |
function M:setMoveType(moveType) | |
self.moveType = moveType | |
self.moveLogic = self.moveLogicFactory:createMove(self.moveType, {target = self}) | |
end | |
---------------------------------------------------------------- | |
-- 現在の向きを設定します. | |
-- ただし、移動中の場合は無視されます. | |
---------------------------------------------------------------- | |
function M:setDirection(direction) | |
if self:isMoving() then | |
return | |
end | |
if self.currentDirection == direction then | |
return | |
end | |
self.currentDirection = direction | |
local animName = M.DIR_ANIMS[direction] | |
if animName then | |
self:playAnim(animName) | |
end | |
end | |
---------------------------------------------------------------- | |
-- ステップ毎の移動処理を行います. | |
-- moveLocではいまいちなので、自前で移動する. | |
---------------------------------------------------------------- | |
function M:moveStep() | |
if self.moveLogic then | |
self.moveLogic:onStep() | |
end | |
if self:isMoving() then | |
self:addLoc(self.currentMoveX, self.currentMoveY, 0) | |
self.currentMoveCount = self.currentMoveCount - 1 | |
if self.currentMoveCount == 0 then | |
if self:hasEventListener(Event.MOVE_FINISHED) then | |
self:dispatchEvent(Event.MOVE_FINISHED) | |
end | |
self:onMoveFinished() | |
end | |
end | |
end | |
---------------------------------------------------------------- | |
-- マップ上の座標を移動する共通処理です. | |
-- TODO:リファクタリング | |
---------------------------------------------------------------- | |
function M:moveMapLoc(direction) | |
if self:isMoving() then | |
return false | |
end | |
if not M.DIR_NEXT[direction] then | |
return false | |
end | |
-- 移動方向を設定 | |
self:setDirection(direction) | |
-- 衝突判定 | |
local mapX, mapY = self:getMapLoc() | |
local mapW, mapH = self:getMapSize() | |
local nextMapX, nextMapY = self:getNextMapLoc() | |
local moveX, moveY = nextMapX - mapX, nextMapY - mapY | |
-- 移動しない場合 | |
if moveX == 0 and moveY == 0 then | |
return | |
end | |
-- 移動先が衝突する場合 | |
if self.mapView:collisionWith(self, nextMapX, nextMapY, mapW, mapH) then | |
local e = Event(Event.MOVE_COLLISION) | |
e.collisionMapX = nextMapX | |
e.collisionMapY = nextMapY | |
self:dispatchEvent(e) | |
self:onMoveCollision() | |
return false | |
end | |
-- 移動処理 | |
self.currentMoveX = moveX * self.moveSpeed | |
self.currentMoveY = moveY * self.moveSpeed | |
self.currentMoveCount = self.mapTileWidth / self.moveSpeed | |
if self:hasEventListener(Event.MOVE_STARTED) then | |
self:dispatchEvent(Event.MOVE_STARTED) | |
end | |
self:onMoveStarted() | |
return true | |
end | |
---------------------------------------------------------------- | |
-- マップ上の座標を移動します. | |
-- TODO:互換性の為に残しています.いずれ削除すべきです. | |
---------------------------------------------------------------- | |
function M:moveMap(dir) | |
return self:moveMapLoc(dir) | |
end | |
---------------------------------------------------------------- | |
-- マップ上の座標を移動します. | |
---------------------------------------------------------------- | |
function M:moveMapLeft() | |
return self:moveMapLoc(M.DIR_LEFT) | |
end | |
---------------------------------------------------------------- | |
-- マップ上の座標を移動します. | |
---------------------------------------------------------------- | |
function M:moveMapUp() | |
return self:moveMapLoc(M.DIR_UP) | |
end | |
---------------------------------------------------------------- | |
-- マップ上の座標を移動します. | |
---------------------------------------------------------------- | |
function M:moveMapRight() | |
return self:moveMapLoc(M.DIR_RIGHT) | |
end | |
---------------------------------------------------------------- | |
-- マップ上の座標を移動します. | |
---------------------------------------------------------------- | |
function M:moveMapDown() | |
return self:moveMapLoc(M.DIR_DOWN) | |
end | |
---------------------------------------------------------------- | |
-- マップ上の座標を移動しているか返します. | |
---------------------------------------------------------------- | |
function M:isMoving() | |
return self.currentMoveCount > 0 | |
end | |
---------------------------------------------------------------- | |
-- 移動開始時に呼ばれます. | |
---------------------------------------------------------------- | |
function M:onMoveStarted() | |
end | |
---------------------------------------------------------------- | |
-- 移動完了時に呼ばれます. | |
---------------------------------------------------------------- | |
function M:onMoveFinished() | |
local eventLayer = self.mapView:findEventLayer() | |
if not eventLayer then | |
return | |
end | |
local gid = eventLayer:getGid(self:getMapX(), self:getMapY()) | |
if gid and gid > 0 and self:hasEventListener("moveOnTile") then | |
local tileset = self.mapView.tmxMap:findTilesetByGid(gid) | |
local e = Event("moveOnTile") | |
e.gid = gid | |
e.tileNo = tileset:getTileIndexByGid(gid) | |
self:dispatchEvent(e) | |
end | |
end | |
---------------------------------------------------------------- | |
-- 移動で衝突した時に呼ばれます. | |
---------------------------------------------------------------- | |
function M:onMoveCollision() | |
end | |
return M end) | |
package.preload['hp/rpg/move/RPGMove'] = (function (...) | |
---------------------------------------------------------------- | |
-- RPGSpriteの移動を行う処理の共通クラスです.<br> | |
-- このクラス自身は何もしません. | |
-- @class table | |
-- @name RPGMove | |
---------------------------------------------------------------- | |
local table = require("hp/lang/table") | |
local class = require("hp/lang/class") | |
local M = class() | |
---------------------------------------------------------------- | |
-- コンストラクタです.<br> | |
---------------------------------------------------------------- | |
function M:init(params) | |
assert(params.target) | |
self._target = params.target | |
end | |
---------------------------------------------------------------- | |
-- ステップ毎に呼ばれる処理です.<br> | |
---------------------------------------------------------------- | |
function M:onStep() | |
end | |
---------------------------------------------------------------- | |
-- 移動可能なオブジェクトを返します.<br> | |
---------------------------------------------------------------- | |
function M:getTarget() | |
return self._target | |
end | |
return M end) | |
package.preload['hp/rpg/move/RPGMoveFactory'] = (function (...) | |
---------------------------------------------------------------- | |
-- RPGMoveを作成するファクトリークラスです.<br> | |
-- @class table | |
-- @name RPGMoveFactory | |
---------------------------------------------------------------- | |
local table = require("hp/lang/table") | |
local class = require("hp/lang/class") | |
local RPGRandomMove = require("hp/rpg/move/RPGRandomMove") | |
local M = class() | |
M.MOVE_CLASSES = { | |
randomMove = RPGRandomMove, | |
} | |
---------------------------------------------------------------- | |
-- 移動を行うクラスのインスタンスを生成します.<br> | |
---------------------------------------------------------------- | |
function M:createMove(name, params) | |
if not name then | |
return | |
end | |
local moveClass = self.MOVE_CLASSES[name] | |
if moveClass then | |
return moveClass:new(params) | |
end | |
end | |
return M end) | |
package.preload['hp/rpg/move/RPGRandomMove'] = (function (...) | |
---------------------------------------------------------------- | |
-- RPGSpriteの移動を行うクラスです.<br> | |
-- ランダム移動を行います.<br> | |
-- @class table | |
-- @name RPGRandomMove | |
---------------------------------------------------------------- | |
local table = require("hp/lang/table") | |
local class = require("hp/lang/class") | |
local RPGMove = require("hp/rpg/move/RPGMove") | |
local M = class(RPGMove) | |
local super = RPGMove | |
math.randomseed(os.time()) | |
---------------------------------------------------------------- | |
-- コンストラクタです.<br> | |
---------------------------------------------------------------- | |
function M:init(params) | |
super.init(self, params) | |
end | |
---------------------------------------------------------------- | |
-- ランダム移動処理を行います. | |
---------------------------------------------------------------- | |
function M:onStep() | |
local target = self:getTarget() | |
local r = math.random(200) | |
target:moveMap(r) | |
end | |
return M end) | |
package.preload['hp/tmx/TMXLayer'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- Class is a layer of TMXMap. | |
-------------------------------------------------------------------------------- | |
local class = require("hp/lang/class") | |
local M = class() | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-------------------------------------------------------------------------------- | |
function M:init(tmxMap) | |
self.tmxMap = tmxMap | |
self.type = "tilelayer" | |
self.name = "" | |
self.x = 0 | |
self.y = 0 | |
self.width = 0 | |
self.height = 0 | |
self.opacity = 0 | |
self.visible = 1 | |
self.properties = {} | |
self.tiles = {} | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the property. | |
-- @param key key. | |
-- @return value. | |
-------------------------------------------------------------------------------- | |
function M:getProperty(key) | |
return self.properties[key] | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the property of the tile that is at the specified point. | |
-- @param x position of x | |
-- @param y position of y | |
-- @param key property key | |
-- @return property value | |
-------------------------------------------------------------------------------- | |
function M:getTileProperty(x, y, key) | |
local gid = self:getGid(x, y) | |
return self.tmxMap:getTileProperty(gid, key) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the properties of the tile that is at the specified point. | |
-- @param x position of x | |
-- @param y position of y | |
-- @return Properties | |
-------------------------------------------------------------------------------- | |
function M:getTileProperties(x, y) | |
local gid = self:getGid(x, y) | |
return self.tmxMap:getTileProperties(gid) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the gid of the specified position. <br> | |
-- If is out of range, return nil. | |
-- @param x potision of x. | |
-- @param y potision of y. | |
-- @return gid. | |
-------------------------------------------------------------------------------- | |
function M:getGid(x, y) | |
if not self:checkBounds(x, y) then | |
return nil | |
end | |
return self.tiles[(y - 1) * self.width + x] | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets gid of the specified position. <br> | |
-- If you set the position is out of range to error. | |
-- @param x potision of x. | |
-- @param y potision of y. | |
-- @param gid global id. | |
-------------------------------------------------------------------------------- | |
function M:setGid(x, y, gid) | |
if not self:checkBounds(x, y) then | |
error("index out of bounds!") | |
end | |
self.tiles[(y - 1) * self.width + x] = gid | |
end | |
-------------------------------------------------------------------------------- | |
-- Tests whether the position is within the range specified. | |
-- @param x potision of x. | |
-- @param y potision of y. | |
-- @return True if in the range. | |
-------------------------------------------------------------------------------- | |
function M:checkBounds(x, y) | |
if x < 1 or self.width < x then | |
return false | |
end | |
if y < 1 or self.height < y then | |
return false | |
end | |
return true | |
end | |
return M end) | |
package.preload['hp/tmx/TMXMap'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This class stores data in the form of map tiles. | |
-- Applies to the Model class. | |
-- | |
-- Display function is not held. | |
-- Use the TMXMapView. | |
-- | |
-- For tile map editor, please see below. | |
-- http://www.mapeditor.org/ | |
-- | |
-------------------------------------------------------------------------------- | |
local class = require("hp/lang/class") | |
local table = require("hp/lang/table") | |
local M = class() | |
-- constraints | |
M.ATTRIBUTE_NAMES = { | |
"version", "orientation", "width", "height", "tilewidth", "tileheight" | |
} | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-------------------------------------------------------------------------------- | |
function M:init() | |
self.version = 0 | |
self.orientation = "" | |
self.width = 0 | |
self.height = 0 | |
self.tilewidth = 0 | |
self.tileheight = 0 | |
self.allLayers = {} | |
self.layers = {} | |
self.tilesets = {} | |
self.objectGroups = {} | |
self.properties = {} | |
end | |
-------------------------------------------------------------------------------- | |
-- The information on the standard output TMXMap. | |
-------------------------------------------------------------------------------- | |
function M:printDebug() | |
-- header | |
print("<TMXMap>") | |
-- attributes | |
for i, attr in ipairs(self.ATTRIBUTE_NAMES) do | |
local value = self[attr] | |
value = value and value or "" | |
print(attr .. " = " .. value) | |
end | |
print("</TMXMap>") | |
end | |
-------------------------------------------------------------------------------- | |
-- Add a layer. | |
-- @param layer layer. | |
-------------------------------------------------------------------------------- | |
function M:addLayer(layer) | |
table.insert(self.allLayers, layer) | |
table.insert(self.layers, layer) | |
end | |
-------------------------------------------------------------------------------- | |
-- Remove a layer. | |
-- @param layer layer. | |
-------------------------------------------------------------------------------- | |
function M:removeLayer(layer) | |
table.removeElement(self.allLayers, layer) | |
return table.removeElement(self.layers, layer) | |
end | |
-------------------------------------------------------------------------------- | |
-- Remove a layer. | |
-- @param index index. | |
-------------------------------------------------------------------------------- | |
function M:removeLayerAt(index) | |
table.removeElement(self.allLayers, self.layers[index]) | |
return table.remove(self.layers, index) | |
end | |
-------------------------------------------------------------------------------- | |
-- Finds and returns the layer. | |
-- @param name Find name. | |
-------------------------------------------------------------------------------- | |
function M:findLayerByName(name) | |
for i, v in ipairs(self.layers) do | |
if v.name == name then | |
return v | |
end | |
end | |
return nil | |
end | |
-------------------------------------------------------------------------------- | |
-- Add the tile set. | |
-- @param tileset tileset. | |
-------------------------------------------------------------------------------- | |
function M:addTileset(tileset) | |
table.insert(self.tilesets, tileset) | |
end | |
-------------------------------------------------------------------------------- | |
-- Remove the tile set. | |
-- @param tileset tileset. | |
-------------------------------------------------------------------------------- | |
function M:removeTileset(tileset) | |
return table.removeElement(self.tilesets, tileset) | |
end | |
-------------------------------------------------------------------------------- | |
-- Remove the tile set. | |
-- @param index index | |
-------------------------------------------------------------------------------- | |
function M:removeTilesetAt(index) | |
return table.remove(self.tilesets, index) | |
end | |
-------------------------------------------------------------------------------- | |
-- Finds and returns the tileset from the specified gid. | |
-- @param gid gid | |
-- @return TMXTileset | |
-------------------------------------------------------------------------------- | |
function M:findTilesetByGid(gid) | |
local matchTileset = nil | |
for i, tileset in ipairs(self.tilesets) do | |
if gid >= tileset.firstgid then | |
matchTileset = tileset | |
end | |
end | |
return matchTileset | |
end | |
-------------------------------------------------------------------------------- | |
-- Add the ObjectGroup. | |
-- @param objectGroup objectGroup | |
-------------------------------------------------------------------------------- | |
function M:addObjectGroup(objectGroup) | |
table.insert(self.allLayers, objectGroup) | |
table.insert(self.objectGroups, objectGroup) | |
end | |
-------------------------------------------------------------------------------- | |
-- Remove the ObjectGroup. | |
-- @param objectGroup objectGroup | |
-------------------------------------------------------------------------------- | |
function M:removeObjectGroup(objectGroup) | |
table.removeElement(self.allLayers, objectGroup) | |
return table.removeElement(self.objectGroups, objectGroup) | |
end | |
-------------------------------------------------------------------------------- | |
-- Remove the ObjectGroup. | |
-- @param index index | |
-------------------------------------------------------------------------------- | |
function M:removeObjectGroupAt(index) | |
table.removeElement(self.allLayers, self.objectGroups[index]) | |
return table.remove(self.objectGroups, index) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the property with the specified key. | |
-- @param key property key | |
-------------------------------------------------------------------------------- | |
function M:getProperty(key) | |
return self.properties[key] | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the property of the tile that corresponds to the specified gid. | |
-- @param gid gid | |
-- @param key property key | |
-- @return tile property | |
-------------------------------------------------------------------------------- | |
function M:getTileProperty(gid, key) | |
local properties = self:getTileProperties(gid) | |
if properties then | |
return properties[key] | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the properties of the tile that corresponds to the specified gid. | |
-- @param gid gid | |
-- @return tile properties | |
-------------------------------------------------------------------------------- | |
function M:getTileProperties(gid) | |
for i, tileset in ipairs(self.tilesets) do | |
local tileId = tileset:getTileIndexByGid(gid) | |
if tileset.tiles[tileId] then | |
return tileset.tiles[tileId].properties | |
end | |
end | |
end | |
return M end) | |
package.preload['hp/tmx/TMXMapLoader'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- TMXMapLoader is a class that reads the file format tmx, to create a TMXMap. | |
-- Some functions, please do not see from the outside. | |
-- Dare, leaving for the inheritance. | |
-------------------------------------------------------------------------------- | |
local table = require("hp/lang/table") | |
local class = require("hp/lang/class") | |
local TMXMap = require("hp/tmx/TMXMap") | |
local TMXTileset = require("hp/tmx/TMXTileset") | |
local TMXLayer = require("hp/tmx/TMXLayer") | |
local TMXObject = require("hp/tmx/TMXObject") | |
local TMXObjectGroup = require("hp/tmx/TMXObjectGroup") | |
local ResourceManager = require("hp/manager/ResourceManager") | |
local M = class() | |
M.ENCODING_CSV = "csv" | |
M.ENCODING_BASE64 = "base64" | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-------------------------------------------------------------------------------- | |
function M:init() | |
self.nodeParserNames = { | |
map = "parseNodeMap", | |
tileset = "parseNodeTileset", | |
layer = "parseNodeLayer", | |
objectgroup = "parseNodeObjectGroup" | |
} | |
end | |
-------------------------------------------------------------------------------- | |
-- Read the file format of TMX. <br> | |
-- Returns TMXMap a result of reading. | |
-- @param filename | |
-- @return TMXMap instance. | |
-------------------------------------------------------------------------------- | |
function M:loadFile(filename) | |
local data = ResourceManager:readFile(filename) | |
return self:loadString(data) | |
-- TODO:Windowsだとpackage.pathを使用した場合に動作しない | |
-- MEMO:Moai1.3 Build160以降で修正されたかもしれない | |
--[[ | |
local xml = MOAIXmlParser.parseFile(filename) | |
self:parseNode(xml) | |
return assert(self.map) | |
--]] | |
end | |
-------------------------------------------------------------------------------- | |
-- Read the string format of TMX. <br> | |
-- Returns TMXMap a result of reading. | |
-- @param data string data | |
-- @return TMXMap instance. | |
-------------------------------------------------------------------------------- | |
function M:loadString(data) | |
local xml = MOAIXmlParser.parseString(data) | |
self:parseNode(xml) | |
return assert(self.map) | |
end | |
-------------------------------------------------------------------------------- | |
-- Reads the node. <br> | |
-- Has been left for inheritance. <br> | |
-- Please do not accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:parseNode(node) | |
local parser = self.nodeParserNames[node.type] | |
if parser then | |
self[parser](self, node) | |
else | |
return | |
end | |
if not node.children then | |
return | |
end | |
for key, value in pairs(node.children) do | |
for key, value in ipairs(value) do | |
if type(value) == "table" then | |
self:parseNode(value) | |
end | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Please do not accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:parseNodeMap(node) | |
local map = TMXMap:new() | |
self.map = map | |
self:parseNodeAttributes(node, map) | |
self:parseNodeProperties(node, map.properties) | |
end | |
-------------------------------------------------------------------------------- | |
-- Please do not accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:parseNodeAttributes(node, dest) | |
for key, value in pairs(node.attributes) do | |
if tonumber(value) ~= nil then | |
dest[key] = tonumber(value) | |
else | |
dest[key] = value | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Please do not accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:parseNodeTileset(node) | |
local tileset = TMXTileset:new(self.map) | |
self.map:addTileset(tileset) | |
self:parseNodeAttributes(node, tileset) | |
self:parseNodeImage(node, tileset) | |
self:parseNodeTile(node, tileset) | |
self:parseNodeProperties(node, tileset.properties) | |
end | |
-------------------------------------------------------------------------------- | |
-- Please do not accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:parseNodeImage(node, tileset) | |
if not node.children.image then | |
return | |
end | |
for key, value in pairs(node.children.image) do | |
for key, value in pairs(value.attributes) do | |
tileset.image[key] = value | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Please do not accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:parseNodeTile(node, tileset) | |
if not node.children.tile then | |
return | |
end | |
for key, value in pairs(node.children.tile) do | |
local id = tonumber(value.attributes.id) + 1 | |
if tileset.tiles[id] == nil then | |
tileset.tiles[id] = {properties = {}} | |
end | |
self:parseNodeProperties(value, tileset.tiles[id].properties) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Please do not accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:parseNodeLayer(node) | |
local layer = TMXLayer:new(self.map) | |
self.map:addLayer(layer) | |
self:parseNodeAttributes(node, layer) | |
self:parseNodeData(node, layer) | |
self:parseNodeProperties(node, layer.properties) | |
end | |
-------------------------------------------------------------------------------- | |
-- Please do not accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:parseNodeData(node, layer) | |
if node.children.data == nil or #node.children.data < 1 then | |
return | |
end | |
local data = node.children.data[1] | |
if not data.attributes or not data.attributes.encoding then | |
self:parseNodeDataForPlane(node, layer, data) | |
elseif data.attributes.encoding == M.ENCODING_BASE64 then | |
self:parseNodeDataForBase64(node, layer, data) | |
elseif data.attributes.encoding == M.ENCODING_CSV then | |
self:parseNodeDataForCsv(node, layer, data) | |
else | |
error("Not supported encoding!") | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Please do not accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:parseNodeDataForPlane(node, layer, data) | |
for j, tile in ipairs(data.children.tile) do | |
layer.tiles[j] = tonumber(tile.attributes.gid) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Please do not accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:parseNodeDataForCsv(node, layer, data) | |
layer.tiles = assert(loadstring("return {" .. data.value .. "}"))() | |
end | |
-------------------------------------------------------------------------------- | |
-- Please do not accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:parseNodeDataForBase64(node, layer, data) | |
local decodedData = MOAIDataBuffer.base64Decode(data.value) | |
if data.attributes.compression then | |
decodedData = MOAIDataBuffer.inflate(decodedData, 47) | |
end | |
local tileSize = #decodedData / 4 | |
for i = 1, tileSize do | |
local start = (i - 1) * 4 + 1 | |
local a0, a1, a2, a3 = string.byte(decodedData, start, start + 3) | |
local gid = a3 * 256 * 3 + a2 * 256 * 2 + a1 * 256 + a0 | |
layer.tiles[i] = gid | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Please do not accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:parseNodeObjectGroup(node) | |
local group = TMXObjectGroup:new(self.map) | |
self.map:addObjectGroup(group) | |
self:parseNodeAttributes(node, group) | |
self:parseNodeObject(node, group) | |
self:parseNodeProperties(node, group.properties) | |
end | |
-------------------------------------------------------------------------------- | |
-- Please do not accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:parseNodeObject(node, group) | |
if node.children.object == nil then | |
return | |
end | |
for i, value in ipairs(node.children.object) do | |
local object = TMXObject:new(group) | |
self:parseNodeAttributes(value, object) | |
self:parseNodeProperties(value, object.properties) | |
group:addObject(object) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Please do not accessible from the outside. | |
-------------------------------------------------------------------------------- | |
function M:parseNodeProperties(node, dest) | |
if not node.children then | |
return | |
end | |
if not node.children.properties then | |
return | |
end | |
for key, value in ipairs(node.children.properties) do | |
for key, value in ipairs(value.children.property) do | |
dest[value.attributes.name] = value.attributes.value | |
end | |
end | |
end | |
return M | |
end) | |
package.preload['hp/tmx/TMXMapView'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- View the class is to draw the TMXMap. <br> | |
-- You can render TMXMap by the use of this class. <br> | |
-- You can add your own processing can be inherited. <br> | |
-------------------------------------------------------------------------------- | |
local table = require("hp/lang/table") | |
local class = require("hp/lang/class") | |
local Layer = require("hp/display/Layer") | |
local MapSprite = require("hp/display/MapSprite") | |
local SpriteSheet = require("hp/display/SpriteSheet") | |
local Event = require("hp/event/Event") | |
local EventDispatcher = require("hp/event/EventDispatcher") | |
local TextureManager = require("hp/manager/TextureManager") | |
local M = class(EventDispatcher) | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-------------------------------------------------------------------------------- | |
function M:init(resourceDirectory) | |
EventDispatcher.init(self) | |
self.resourceDirectory = resourceDirectory or "" | |
end | |
-------------------------------------------------------------------------------- | |
-- Reads the map data, to generate a display object. | |
-------------------------------------------------------------------------------- | |
function M:loadMap(tmxMap) | |
self.tmxMap = tmxMap | |
self.camera = self:createCamera() | |
self:createDisplayMapLayers() | |
for i, layer in ipairs(self.mapLayers) do | |
layer:setCamera(self.camera) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Load the texture of the tile set that is specified. | |
-- Because of inheritance has been left for, please do not call from the outside. | |
-------------------------------------------------------------------------------- | |
function M:loadTexture(tileset) | |
local tmxMap = self.tmxMap | |
if tileset then | |
if not tileset.texture then | |
local path = self.resourceDirectory .. tileset.image.source | |
tileset.texture = TextureManager:request(path) | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Display to generate a map layers. | |
-- Because of inheritance has been left for, please do not call from the outside. | |
-------------------------------------------------------------------------------- | |
function M:createDisplayMapLayers() | |
local tmxMap = self.tmxMap | |
self.mapLayers = {} | |
self.layers = {} | |
self.objectLayers = {} | |
for i, layerData in ipairs(tmxMap.allLayers) do | |
if layerData.type == "tilelayer" then | |
if layerData.visible ~= 0 and layerData.properties.visible ~= "false" then | |
local tileLayer = self:createDisplayLayer(layerData) | |
table.insert(self.mapLayers, tileLayer) | |
table.insert(self.layers, tileLayer) | |
end | |
else | |
local objectLayer = self:createDisplayObjectLayer(layerData) | |
table.insert(self.mapLayers, objectLayer) | |
table.insert(self.objectLayers, objectLayer) | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- To generate a 2D camera. | |
-- Because of inheritance has been left for, please do not call from the outside. | |
-------------------------------------------------------------------------------- | |
function M:createCamera() | |
local camera = MOAICamera.new() | |
camera:setOrtho(true) | |
camera:setNearPlane(1) | |
camera:setFarPlane(-1) | |
return camera | |
end | |
-------------------------------------------------------------------------------- | |
-- Display to generate a tile layer. | |
-- Because of inheritance has been left for, please do not call from the outside. | |
-------------------------------------------------------------------------------- | |
function M:createDisplayLayer(layer) | |
local tmxMap = self.tmxMap | |
local displayTilesets = self:createDisplayTilesets(layer) | |
local displayLayer = Layer() | |
displayLayer.mapLayer = layer | |
displayLayer.tilesetRenderers = {} | |
for key, tileset in pairs(displayTilesets) do | |
if tileset.texture then | |
local mapSprite = self:createDisplayLayerRenderer(displayLayer, tileset) | |
table.insert(displayLayer.tilesetRenderers, mapSprite) | |
end | |
end | |
return displayLayer | |
end | |
-------------------------------------------------------------------------------- | |
-- To generate the object on which to draw the layer. | |
-- Because of inheritance has been left for, please do not call from the outside. | |
-------------------------------------------------------------------------------- | |
function M:createDisplayLayerRenderer(displayLayer, tileset) | |
local tmxMap = self.tmxMap | |
local mapWidth, mapHeight = tmxMap.width, tmxMap.height | |
local mapLayer = displayLayer.mapLayer | |
local texture = tileset.texture | |
-- tile data | |
local tw, th = texture:getSize() | |
local spacing, margin = tileset.spacing, tileset.margin | |
local tilewidth, tileheight = tileset.tilewidth, tileset.tileheight | |
local tileCol = math.floor((tw + spacing) / tilewidth) | |
local tileRow = math.floor((th + spacing) / tileheight) | |
local tileSize = tileCol * tileRow | |
-- make sprite | |
local mapSprite = MapSprite({texture = texture, layer = displayLayer}) | |
mapSprite:setMapSize(mapWidth, mapHeight, tilewidth, tileheight) | |
mapSprite:setMapSheets(tilewidth, tileheight, tileCol, tileRow, spacing, margin) | |
mapSprite.tileset = tileset | |
for y = 1, mapLayer.height do | |
local rowData = {} | |
for x = 1, mapLayer.width do | |
local gid = mapLayer.tiles[(y - 1) * mapLayer.width + x] | |
local tileNo = gid == 0 and gid or gid - tileset.firstgid + 1 | |
tileNo = tileNo > tileSize and 0 or tileNo | |
table.insert(rowData, tileNo) | |
end | |
mapSprite:setRow(y, unpack(rowData)) | |
end | |
return mapSprite | |
end | |
-------------------------------------------------------------------------------- | |
-- To generate a list of tile set that is used by a given layer. | |
-- Because of inheritance has been left for, please do not call from the outside. | |
-------------------------------------------------------------------------------- | |
function M:createDisplayTilesets(layer) | |
local tmxMap = self.tmxMap | |
local tilesets = {} | |
for i, gid in ipairs(layer.tiles) do | |
local tileset = tmxMap:findTilesetByGid(gid) | |
if tileset then | |
self:loadTexture(tileset) | |
tilesets[tileset.name] = tileset | |
end | |
end | |
return tilesets | |
end | |
-------------------------------------------------------------------------------- | |
-- Layer to generate a display object from the object group. | |
-- Because of inheritance has been left for, please do not call from the outside. | |
-------------------------------------------------------------------------------- | |
function M:createDisplayObjectLayer(objectGroup) | |
local objectLayer = Layer:new() | |
objectLayer.objects = {} | |
objectLayer.objectGroup = objectGroup | |
for j, object in ipairs(objectGroup.objects) do | |
if object.gid and object.gid > 0 then | |
local displayObject = self:createDisplayObject(object) | |
self:addDisplayObject(objectLayer, displayObject) | |
end | |
end | |
return objectLayer | |
end | |
-------------------------------------------------------------------------------- | |
-- To generate a display object from the object data. | |
-------------------------------------------------------------------------------- | |
function M:createDisplayObject(object) | |
local tmxMap = self.tmxMap | |
local gid = object.gid | |
local tileset = tmxMap:findTilesetByGid(gid) | |
self:loadTexture(tileset) | |
local texture = tileset.texture | |
local tw, th = texture:getSize() | |
local spacing, margin = tileset.spacing, tileset.margin | |
local tilewidth, tileheight = tileset.tilewidth, tileset.tileheight | |
local tileCol = math.floor((tw + spacing) / tilewidth) | |
local tileRow = math.floor((th + spacing) / tileheight) | |
local sprite = SpriteSheet {texture = texture} | |
sprite:setTiledSheets(tilewidth, tileheight, tileCol, tileRow) | |
sprite.mapObject = object | |
sprite:setLeft(object.x) | |
sprite:setTop(object.y - sprite:getHeight()) | |
sprite:setIndex(object.gid - tileset.firstgid + 1) | |
if object.properties.sheetAnims then | |
local sheetAnims = assert(loadstring("return {" .. object.properties.sheetAnims .. "}"))() | |
sprite:setSheetAnims(sheetAnims) | |
end | |
if object.properties.playAnim then | |
sprite:playAnim(object.properties.playAnim) | |
end | |
if object.properties.visible then | |
sprite:setVisible(toboolean(object.properties.visible)) | |
end | |
return sprite | |
end | |
-------------------------------------------------------------------------------- | |
-- Set the Scene. | |
-- Add a layer for each Scene. | |
-------------------------------------------------------------------------------- | |
function M:setScene(scene) | |
self.scene = scene | |
for i, layer in ipairs(self.mapLayers) do | |
scene:addChild(layer) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- To scroll through the camera. | |
-- Adjust the position so that it does not appear out-of-range region is specified. | |
-------------------------------------------------------------------------------- | |
function M:scrollCamera(x, y) | |
local viewWidth, viewHeight = self:getViewSize() | |
local firstLayer = self.layers[1] | |
local maxX, maxY = viewWidth - firstLayer:getViewWidth(), viewWidth - firstLayer:getViewHeight() | |
x = x < 0 and 0 or x | |
x = x > maxX and maxX or x | |
y = y < 0 and 0 or y | |
y = y > maxY and maxY or y | |
self.camera:setLoc(x, y, 0) | |
end | |
-------------------------------------------------------------------------------- | |
-- Scroll to the specified position in the center of the camera. | |
-- Adjust the position so that it does not appear out-of-range region is specified. | |
-------------------------------------------------------------------------------- | |
function M:scrollCameraToCenter(x, y) | |
local firstLayer = self.layers[1] | |
local cx, cy = firstLayer:getViewWidth() / 2, firstLayer:getViewHeight() / 2 | |
self:scrollCamera(x - cx, y - cy) | |
end | |
-------------------------------------------------------------------------------- | |
-- To return the object to find the object from the name, the first one it finds. | |
-- If not found, returns nil. | |
-------------------------------------------------------------------------------- | |
function M:findObjectByName(name) | |
for i, objectLayer in ipairs(self.objectLayers) do | |
for j, object in ipairs(objectLayer.objects) do | |
if object.mapObject.name == name then | |
return object | |
end | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns all of the objects to find the object from the name, was found. | |
-------------------------------------------------------------------------------- | |
function M:findObjectsByName(name) | |
local objects = {} | |
for i, objectLayer in ipairs(self.objectLayers) do | |
for j, object in ipairs(objectLayer.objects) do | |
if object.mapObject.name == name then | |
table.insert(objects, object) | |
end | |
end | |
end | |
return objects | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the layer by layer from the name search, was found. | |
-------------------------------------------------------------------------------- | |
function M:findLayerByName(name) | |
for i, layer in ipairs(self.layers) do | |
if layer.mapLayer.name == name then | |
return layer | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Search for renderer for the Tileset and Layer. | |
-- @param layer Display layer | |
-- @param tileset TMXTileset | |
-------------------------------------------------------------------------------- | |
function M:findLayerRendererByTileset(layer, tileset) | |
for i, renderer in ipairs(layer.tilesetRenderers) do | |
if renderer.tileset == tileset then | |
return renderer | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Update the GID of the specified layer. | |
-- @param layer The name of the layer or object | |
-- @param x position of x. | |
-- @param y position of y. | |
-- @param gid Global tile ID | |
-------------------------------------------------------------------------------- | |
function M:updateGid(layer, x, y, gid) | |
layer = type(layer) == "string" and self:findLayerByName(layer) or layer | |
layer.mapLayer:setGid(x, y, gid) | |
local tileset = self.tmxMap:findTilesetByGid(gid) | |
for i, renderer in ipairs(layer.tilesetRenderers) do | |
if renderer.tileset == tileset then | |
local tileNo = gid == 0 and gid or gid - tileset.firstgid + 1 | |
renderer:setTile(x, y, tileNo) | |
else | |
renderer:setTile(x, y, 0) | |
end | |
end | |
local renderer = self:findLayerRendererByTileset(layer, tileset) | |
if not renderer then | |
self:loadTexture(tileset) | |
if tileset.texture then | |
renderer = self:createDisplayLayerRenderer(layer, tileset) | |
table.insert(layer.tilesetRenderers, renderer) | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- Add the object. | |
-- @param objectLayer object layer | |
-- @param object target object | |
-------------------------------------------------------------------------------- | |
function M:addDisplayObject(objectLayer, object) | |
table.insertElement(objectLayer.objects, object) | |
object:setLayer(objectLayer) | |
end | |
-------------------------------------------------------------------------------- | |
-- Remove the object. | |
-- @param objectLayer object layer | |
-- @param object target object | |
-------------------------------------------------------------------------------- | |
function M:removeDisplayObject(objectLayer, object) | |
table.removeElement(objectLayer.objects, object) | |
object:setLayer(nil) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the size of the MapView. | |
-------------------------------------------------------------------------------- | |
function M:getViewSize() | |
if not self.tmxMap then | |
return 0, 0 | |
end | |
local width = self.tmxMap.width * self.tmxMap.tilewidth | |
local height = self.tmxMap.height * self.tmxMap.tileheight | |
return width, height | |
end | |
return M end) | |
package.preload['hp/tmx/TMXObject'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- Class is a object of TMXMap. | |
-------------------------------------------------------------------------------- | |
local class = require("hp/lang/class") | |
local M = class() | |
-- constraints | |
M.ATTRIBUTE_NAMES = {"name", "type", "x", "y", "width", "height", "gid"} | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-------------------------------------------------------------------------------- | |
function M:init() | |
self.name = "" | |
self.type = "" | |
self.x = 0 | |
self.y = 0 | |
self.width = 0 | |
self.height = 0 | |
self.gid = nil | |
self.properties = {} | |
end | |
return M | |
end) | |
package.preload['hp/tmx/TMXObjectGroup'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- Class is a objectgroup of TMXMap. | |
-------------------------------------------------------------------------------- | |
local table = require "hp/lang/table" | |
local class = require "hp/lang/class" | |
local M = class() | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-------------------------------------------------------------------------------- | |
function M:init(tmxMap) | |
self.type = "objectgroup" | |
self.name = "" | |
self.width = 0 | |
self.height = 0 | |
self.tmxMap = tmxMap | |
self.objects = {} | |
self.properties = {} | |
end | |
-------------------------------------------------------------------------------- | |
-- Add the object. | |
-------------------------------------------------------------------------------- | |
function M:addObject(object) | |
return table.insertElement(self.objects, object) | |
end | |
-------------------------------------------------------------------------------- | |
-- Remove the object. | |
-------------------------------------------------------------------------------- | |
function M:removeObject(object) | |
return table.removeElement(self.objects, object) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the property. | |
-- @param key key. | |
-- @return value. | |
-------------------------------------------------------------------------------- | |
function M:getProperty(key) | |
return self.properties[key] | |
end | |
return M | |
end) | |
package.preload['hp/tmx/TMXTileset'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- Class is a tileset of TMXMap. | |
-------------------------------------------------------------------------------- | |
local class = require("hp/lang/class") | |
local M = class() | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-------------------------------------------------------------------------------- | |
function M:init(tmxMap) | |
self.tmxMap = tmxMap | |
self.name = "" | |
self.firstgid = 0 | |
self.tilewidth = 0 | |
self.tileheight = 0 | |
self.spacing = 0 | |
self.margin = 0 | |
self.image = {source = "", width = 0, height = 0} | |
self.tiles = {} | |
self.properties = {} | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the tile-index of the specified gid <br> | |
-- @param gid gid. | |
-- @return tile-index. | |
-------------------------------------------------------------------------------- | |
function M:getTileIndexByGid(gid) | |
return gid - self.firstgid + 1 | |
end | |
return M end) | |
package.preload['hp/util/CompareUtil'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This is a utility class to do a comparison of the object.<br> | |
-------------------------------------------------------------------------------- | |
local M = {} | |
-- Constant | |
M.EQ = "EQ" | |
M.NE = "NE" | |
M.LT = "LT" | |
M.LE = "LE" | |
M.GT = "GT" | |
M.GE = "GE" | |
-------------------------------------------------------------------------------- | |
-- Compare the b and a.<br> | |
-- Sets the comparison function as an argument.<br> | |
-- @param a Target. | |
-- @param b Target. | |
-- @param comp Function or a string constant. | |
-- @return True if the comparison result is matched. | |
-------------------------------------------------------------------------------- | |
function M.compare(a, b, comp) | |
comp = comp or M.EQ | |
if type(comp) == "string" then | |
comp = M["compare"] .. comp | |
end | |
return comp(a, b) | |
end | |
-------------------------------------------------------------------------------- | |
-- Compare the b and a.<br> | |
-- @param a Target. | |
-- @param b Target. | |
-- @return True if equal. | |
-------------------------------------------------------------------------------- | |
function M.compareEQ(a, b) | |
return a == b | |
end | |
-------------------------------------------------------------------------------- | |
-- Compare the b and a.<br> | |
-- @param a Target. | |
-- @param b Target. | |
-- @return True if not equal. | |
-------------------------------------------------------------------------------- | |
function M.compareNE(a, b) | |
return a ~= b | |
end | |
-------------------------------------------------------------------------------- | |
-- Compare the b and a.<br> | |
-- @param a Target. | |
-- @param b Target. | |
-- @return True if less than. | |
-------------------------------------------------------------------------------- | |
function M.compareLT(a, b) | |
return a < b | |
end | |
-------------------------------------------------------------------------------- | |
-- Compare the b and a.<br> | |
-- @param a Target. | |
-- @param b Target. | |
-- @return True if less than or equal. | |
-------------------------------------------------------------------------------- | |
function M.compareLE(a, b) | |
return a <= b | |
end | |
-------------------------------------------------------------------------------- | |
-- Compare the b and a.<br> | |
-- @param a Target. | |
-- @param b Target. | |
-- @return True if greater than. | |
-------------------------------------------------------------------------------- | |
function M.compareGT(a, b) | |
return a > b | |
end | |
-------------------------------------------------------------------------------- | |
-- Compare the b and a.<br> | |
-- @param a Target. | |
-- @param b Target. | |
-- @return True if greater than or equal. | |
-------------------------------------------------------------------------------- | |
function M.compareGE(a, b) | |
return a >= b | |
end | |
return M end) | |
package.preload['hp/util/Executors'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This is a utility class to execute. | |
-------------------------------------------------------------------------------- | |
local M = {} | |
-------------------------------------------------------------------------------- | |
-- Run the specified function looping | |
-- @param func Target function. | |
-- @param ... Argument. | |
-------------------------------------------------------------------------------- | |
function M.callLoop(func, ...) | |
local thread = MOAICoroutine.new() | |
local args = {...} | |
thread:run( | |
function() | |
while true do | |
if func(unpack(args)) then | |
break | |
end | |
coroutine.yield() | |
end | |
end | |
) | |
end | |
-------------------------------------------------------------------------------- | |
-- Run the specified function delay. <br> | |
-- @param func Target function. | |
-- @param ... Argument. | |
-------------------------------------------------------------------------------- | |
function M.callLater(func, ...) | |
M.callLaterFrame(0, func, ...) | |
end | |
-------------------------------------------------------------------------------- | |
-- Run the specified function delay. <br> | |
-- @param frame Delay frame count. | |
-- @param func Target function. | |
-- @param ... Argument. | |
-------------------------------------------------------------------------------- | |
function M.callLaterFrame(frame, func, ...) | |
local thread = MOAICoroutine.new() | |
local args = {...} | |
local count = 0 | |
thread:run( | |
function() | |
while count < frame do | |
count = count + 1 | |
coroutine.yield() | |
end | |
func(unpack(args)) | |
end | |
) | |
end | |
-------------------------------------------------------------------------------- | |
-- Run the specified function delay. <br> | |
-- @param time Delay seconds. | |
-- @param func Target function. | |
-- @param ... Argument. | |
-------------------------------------------------------------------------------- | |
function M.callLaterTime(time, func, ...) | |
local args = {...} | |
local timer = MOAITimer.new() | |
timer:setSpan(time) | |
timer:setListener(MOAITimer.EVENT_STOP, function() func(unpack(args)) end) | |
timer:start() | |
end | |
return M end) | |
package.preload['hp/util/FpsMonitor'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This class is to observe the FPS. | |
-------------------------------------------------------------------------------- | |
local class = require("hp/lang/class") | |
local Logger = require("hp/util/Logger") | |
local M = class() | |
-------------------------------------------------------------------------------- | |
-- The constructor. | |
-------------------------------------------------------------------------------- | |
function M:init(sec, onFPS) | |
self._sec = sec | |
self._onFPS = onFPS | |
self._running = false | |
self.timer = MOAITimer.new() | |
self.timer:setMode(MOAITimer.LOOP) | |
self.timer:setSpan(self._sec) | |
self.timer:setListener(MOAITimer.EVENT_TIMER_LOOP, function() self:onTimer() end) | |
end | |
function M:onTimer() | |
local fps = MOAISim.getPerformance() | |
Logger.debug("FpsMonitor:onTimer", "FPS:" .. fps) | |
if self._onFPS then | |
self._onFPS(fps) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- To start the measurement. | |
-------------------------------------------------------------------------------- | |
function M:play() | |
self.timer:start() | |
return self | |
end | |
-------------------------------------------------------------------------------- | |
-- To end the measurement. | |
-------------------------------------------------------------------------------- | |
function M:stop() | |
self.timer:stop() | |
end | |
return M end) | |
package.preload['hp/util/Logger'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This class is for log output. | |
-------------------------------------------------------------------------------- | |
local M = {} | |
-- Constraints | |
M.LEVEL_NONE = 0 | |
M.LEVEL_INFO = 1 | |
M.LEVEL_WARN = 2 | |
M.LEVEL_ERROR = 3 | |
M.LEVEL_DEBUG = 4 | |
-------------------------------------------------------------------------------- | |
-- A table to select whether to output the log. | |
-------------------------------------------------------------------------------- | |
M.selector = {} | |
M.selector[M.LEVEL_INFO] = true | |
M.selector[M.LEVEL_WARN] = true | |
M.selector[M.LEVEL_ERROR] = true | |
M.selector[M.LEVEL_DEBUG] = true | |
-------------------------------------------------------------------------------- | |
-- This is the log target. | |
-- Is the target output to the console. | |
-------------------------------------------------------------------------------- | |
M.CONSOLE_TARGET = function(...) | |
print(...) | |
end | |
-------------------------------------------------------------------------------- | |
-- This is the log target. | |
-------------------------------------------------------------------------------- | |
M.logTarget = M.CONSOLE_TARGET | |
-------------------------------------------------------------------------------- | |
-- The normal log output. | |
-------------------------------------------------------------------------------- | |
function M.info(...) | |
if M.selector[M.LEVEL_INFO] then | |
M.logTarget("[info]", ...) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- The warning log output. | |
-------------------------------------------------------------------------------- | |
function M.warn(...) | |
if M.selector[M.LEVEL_WARN] then | |
M.logTarget("[warn]", ...) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- The error log output. | |
-------------------------------------------------------------------------------- | |
function M.error(...) | |
if M.selector[M.LEVEL_ERROR] then | |
M.logTarget("[error]", ...) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- The debug log output. | |
-------------------------------------------------------------------------------- | |
function M.debug(...) | |
if M.selector[M.LEVEL_DEBUG] then | |
M.logTarget("[debug]", ...) | |
end | |
end | |
return M end) | |
package.preload['hp/util/MOAIPropUtil'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- This is a utility class for MOAIProp.<br> | |
-------------------------------------------------------------------------------- | |
local M = {} | |
-------------------------------------------------------------------------------- | |
-- Sets the position of the left. | |
-- @param prop MOAIProp instance. | |
-- @param left Position of the left. | |
-------------------------------------------------------------------------------- | |
function M.setLeft(prop, left) | |
local xMin, yMin, zMin, xMax, yMax, zMax = 0, 0, 0, 0, 0, 0 | |
if prop.getBounds then | |
xMin, yMin, zMin, xMax, yMax, zMax = prop:getBounds() | |
xMin = math.min(xMin or 0, xMax or 0) | |
end | |
local pivX, pivY, pivZ = prop:getPiv() | |
local locX, locY, locZ = prop:getLoc() | |
prop:setLoc(left + pivX - xMin, locY, locZ) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the position of the left. | |
-- @param prop MOAIProp instance. | |
-- @return Position of the left. | |
-------------------------------------------------------------------------------- | |
function M.getLeft(prop) | |
local xMin, yMin, zMin, xMax, yMax, zMax = 0, 0, 0, 0, 0, 0 | |
if prop.getBounds then | |
xMin, yMin, zMin, xMax, yMax, zMax = prop:getBounds() | |
xMin = math.min(xMin or 0, xMax or 0) | |
end | |
local pivX, pivY, pivZ = prop:getPiv() | |
local locX, locY, locZ = prop:getLoc() | |
return locX - pivX + xMin | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the position of the right. | |
-- @param prop MOAIProp instance. | |
-- @param right Position of the right. | |
-------------------------------------------------------------------------------- | |
function M.setRight(prop, right) | |
local width = M.getWidth(prop) | |
M.setLeft(prop, right - width) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the position of the right. | |
-- @param prop MOAIProp instance. | |
-- @return Position of the right. | |
-------------------------------------------------------------------------------- | |
function M.getRight(prop) | |
local left = M.getLeft(prop) | |
local width = M.getWidth(prop) | |
return left + width | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the position of the top. | |
-- @param prop MOAIProp instance. | |
-- @param top Position of the top. | |
-------------------------------------------------------------------------------- | |
function M.setTop(prop, top) | |
local xMin, yMin, zMin, xMax, yMax, zMax = 0, 0, 0, 0, 0, 0 | |
if prop.getBounds then | |
xMin, yMin, zMin, xMax, yMax, zMax = prop:getBounds() | |
yMin = math.min(yMin or 0, yMax or 0) | |
end | |
local pivX, pivY, pivZ = prop:getPiv() | |
local locX, locY, locZ = prop:getLoc() | |
prop:setLoc(locX, top + pivY - yMin, locZ) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the position of the top. | |
-- @param prop MOAIProp instance. | |
-- @return Position of the top. | |
-------------------------------------------------------------------------------- | |
function M.getTop(prop) | |
local xMin, yMin, zMin, xMax, yMax, zMax = 0, 0, 0, 0, 0, 0 | |
if prop.getBounds then | |
xMin, yMin, zMin, xMax, yMax, zMax = prop:getBounds() | |
yMin = math.min(yMin or 0, yMax or 0) | |
end | |
local pivX, pivY, pivZ = prop:getPiv() | |
local locX, locY, locZ = prop:getLoc() | |
return locY - pivY + yMin | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the position of the bottom. | |
-- @param prop MOAIProp instance. | |
-- @param bottom Position of the bottom. | |
-------------------------------------------------------------------------------- | |
function M.setBottom(prop, bottom) | |
local height = M.getHeight(prop) | |
M.setTop(prop, bottom - height) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the position of the bottom. | |
-- @param prop MOAIProp instance. | |
-- @return Position of the bottom. | |
-------------------------------------------------------------------------------- | |
function M.getBottom(prop) | |
local top = M.getTop(prop) | |
local height = M.getHeight(prop) | |
return top + height | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the position of the left and top. | |
-- @param prop MOAIProp | |
-- @param left Position of the left. | |
-- @param top Position of the top. | |
-------------------------------------------------------------------------------- | |
function M.setPos(prop, left, top) | |
M.setLeft(prop, left) | |
M.setTop(prop, top) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the position of the center. | |
-- @param prop MOAIProp instance. | |
-- @return centerX | |
-- @return centerY | |
-------------------------------------------------------------------------------- | |
function M.getCenterPos(prop) | |
local left, top = M.getPos(prop) | |
local w, h = M.getSize(prop) | |
return left + w / 2, top + h / 2 | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the position of the centeX and centerY. | |
-- @param prop MOAIProp | |
-- @param x Position of the centerX. | |
-- @param y Position of the centerY. | |
-------------------------------------------------------------------------------- | |
function M.setCenterPos(prop, x, y) | |
local w, h = M.getSize(prop) | |
M.setPos(prop, x - w / 2, y - h / 2) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the position of the left and top. | |
-- @param prop MOAIProp instance. | |
-- @return Position of the left and top. | |
-------------------------------------------------------------------------------- | |
function M.getPos(prop) | |
return M.getLeft(prop), M.getTop(prop) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the width. | |
-- @param prop MOAIProp instance. | |
-- @return width | |
-------------------------------------------------------------------------------- | |
function M.getWidth(prop) | |
local xMin, yMin, zMin, xMax, yMax, zMax = prop:getBounds() | |
return math.abs(xMax - xMin) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the height. | |
-- @param prop MOAIProp instance. | |
-- @return height | |
-------------------------------------------------------------------------------- | |
function M.getHeight(prop) | |
local xMin, yMin, zMin, xMax, yMax, zMax = prop:getBounds() | |
return math.abs(yMax - yMin) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the width and height. | |
-- @param prop MOAIProp instance. | |
-- @return width | |
-- @return height | |
-------------------------------------------------------------------------------- | |
function M.getSize(prop) | |
local xMin, yMin, zMin, xMax, yMax, zMax = prop:getBounds() | |
return math.abs(xMax - xMin), math.abs(yMax - yMin) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the color. | |
-- @param prop MOAIProp instance. | |
-- @return red | |
-- @return green | |
-- @return blue | |
-- @return alpha | |
-------------------------------------------------------------------------------- | |
function M.getColor(prop) | |
local r = prop:getAttr(MOAIColor.ATTR_R_COL) | |
local g = prop:getAttr(MOAIColor.ATTR_G_COL) | |
local b = prop:getAttr(MOAIColor.ATTR_B_COL) | |
local a = prop:getAttr(MOAIColor.ATTR_A_COL) | |
return r, g, b, a | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the red. | |
-- @param prop MOAIProp instance. | |
-- @return red | |
-------------------------------------------------------------------------------- | |
function M.getRed(prop) | |
local r = prop:getAttr(MOAIColor.ATTR_R_COL) | |
return r | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the red. | |
-- @param prop MOAIProp instance. | |
-- @param red red value | |
-------------------------------------------------------------------------------- | |
function M.setRed(prop, red) | |
prop:setAttr(MOAIColor.ATTR_R_COL, red) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the green. | |
-- @param prop MOAIProp instance. | |
-- @return green | |
-------------------------------------------------------------------------------- | |
function M.getGreen(prop) | |
local g = prop:getAttr(MOAIColor.ATTR_G_COL) | |
return g | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the green. | |
-- @param prop MOAIProp instance. | |
-- @param green green value | |
-------------------------------------------------------------------------------- | |
function M.setGreen(prop, green) | |
prop:setAttr(MOAIColor.ATTR_G_COL, green) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the blue. | |
-- @param prop MOAIProp instance. | |
-- @return blue | |
-------------------------------------------------------------------------------- | |
function M.getBlue(prop) | |
local b = prop:getAttr(MOAIColor.ATTR_B_COL) | |
return b | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the blue. | |
-- @param prop MOAIProp instance. | |
-- @param blue blue value | |
-------------------------------------------------------------------------------- | |
function M.setBlue(prop, blue) | |
prop:setAttr(MOAIColor.ATTR_B_COL, blue) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the alpha. | |
-- @param prop MOAIProp instance. | |
-- @return alpha | |
-------------------------------------------------------------------------------- | |
function M.getAlpha(prop) | |
local a = prop:getAttr(MOAIColor.ATTR_A_COL) | |
return a | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the alpha. | |
-- @param prop MOAIProp instance. | |
-- @param a alpha value | |
-------------------------------------------------------------------------------- | |
function M.setAlpha(prop, a) | |
prop:setAttr(MOAIColor.ATTR_A_COL, a) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the color by RGB255 format. | |
-- @param prop MOAIProp instance. | |
-- @param r Red(0-255). | |
-- @param g Green(0-255). | |
-- @param b Blue(0-255). | |
-------------------------------------------------------------------------------- | |
function M.setRGB(prop, r, g, b) | |
local a = MOAIPropUtil.getAlpha(prop) | |
prop:setColor(r / 255, g / 255, b / 255, a) | |
end | |
-------------------------------------------------------------------------------- | |
-- Sets the color by RGBA255 format. | |
-- @param prop MOAIProp instance. | |
-- @param r Red(0-255). | |
-- @param g Green(0-255). | |
-- @param b Blue(0-255). | |
-- @param a Alpha(0-1). | |
-------------------------------------------------------------------------------- | |
function M.setRGBA(prop, r, g, b, a) | |
a = a or MOAIPropUtil.getAlpha(prop) | |
prop:setColor(r / 255, g / 255, b / 255, a) | |
end | |
-------------------------------------------------------------------------------- | |
-- Returns the visible. | |
-- @param prop MOAIProp instance. | |
-- @return visible | |
-------------------------------------------------------------------------------- | |
function M.getVisible(prop) | |
return prop:getAttr(MOAIProp.ATTR_VISIBLE) | |
end | |
return M end) | |
package.preload['hp/util/PriorityQueue'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- 優先度付きキューです.<br> | |
-- comparetorによるソートを行いながらオブジェクトを追加します.<br> | |
-------------------------------------------------------------------------------- | |
local class = require("hp/lang/class") | |
local M = class() | |
--------------------------------------- | |
-- Functions | |
--------------------------------------- | |
---------------------------------------- | |
-- コンストラクタです. | |
-- @param comparetor | |
---------------------------------------- | |
function M:init(comparetor) | |
assert(comparetor, "comparetor is nil!") | |
self.queue = {} | |
self.comparetor = comparetor | |
end | |
---------------------------------------- | |
-- オブジェクトを順序付けて追加します. | |
-- @param object オブジェクト | |
---------------------------------------- | |
function M:push(object) | |
self:remove(object) | |
local comparetor = assert(self.comparetor) | |
local index = 0 | |
for i, v in ipairs(self.queue) do | |
index = i | |
if comparetor(object, v) > 0 then | |
break | |
end | |
end | |
index = index + 1 | |
table.insert(self.queue, index, object) | |
end | |
---------------------------------------- | |
-- キューの先頭オブジェクト削除してから返します.<br> | |
-- キューに存在しない場合はnilを返します. | |
-- @return object | |
---------------------------------------- | |
function M:poll() | |
if self:size() > 0 then | |
return table.remove(self.queue, 1) | |
end | |
return nil | |
end | |
---------------------------------------- | |
-- 指定したインデックスのオブジェクトを返します. | |
-- @param i インデックス | |
-- @return object | |
---------------------------------------- | |
function M:get(i) | |
return self.queue[i] | |
end | |
---------------------------------------- | |
-- 指定したオブジェクトが存在する場合削除します. | |
-- 存在しない場合は削除しません. | |
-- @param object オブジェクト | |
-- @return 削除した場合はそのオブジェクト | |
---------------------------------------- | |
function M:remove(object) | |
for i, v in ipairs(self.queue) do | |
if object == v then | |
return table.remove(self.queue, i) | |
end | |
end | |
return nil | |
end | |
---------------------------------------- | |
-- キューの内容をクリアします. | |
---------------------------------------- | |
function M:clear() | |
self.queue = {} | |
end | |
---------------------------------------- | |
-- for文で使用できる for each関数です.<br> | |
---------------------------------------- | |
function M:each() | |
return ipairs(self.queue) | |
end | |
---------------------------------------- | |
-- キューのサイズを返します. | |
-- @return キューのサイズ. | |
---------------------------------------- | |
function M:size() | |
return #self.queue | |
end | |
return M | |
end) | |
package.preload['hp/util/PropertyUtil'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- クラスのオブジェクトに対するユーティリティ関数です. | |
-------------------------------------------------------------------------------- | |
-- imports | |
local class = require("hp/lang/class") | |
-- class define | |
local M = {} | |
-------------------------------------------------------------------------------- | |
-- オブジェクトのsetter関数経由でパラメータを設定します. | |
-- setter関数が存在しない場合は無視します. | |
-------------------------------------------------------------------------------- | |
function M.setProperties(obj, params, unpackFlag) | |
for k, v in pairs(params) do | |
M.setProperty(obj, k, v, unpackFlag) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- オブジェクトのsetter関数経由で値を設定します. | |
-------------------------------------------------------------------------------- | |
function M.setProperty(obj, name, value, unpackFlag) | |
local setterName = M.getSetterName(name) | |
local setter = obj[setterName] | |
if setter then | |
if not unpackFlag or type(value) ~= "table" or getmetatable(value) ~= nil then | |
return setter(obj, value) | |
else | |
return setter(obj, unpack(value)) | |
end | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- オブジェクトのgetter関数経由で値を返します. | |
-------------------------------------------------------------------------------- | |
function M.getProperty(obj, name) | |
local getterName = M.getGetterName(name) | |
local getter = obj[getterName] | |
if getter then | |
return getter(obj) | |
end | |
end | |
-------------------------------------------------------------------------------- | |
-- プロパティ名からsetter関数名を返します. | |
-------------------------------------------------------------------------------- | |
function M.getSetterName(name) | |
local headName = string.upper(name:sub(1, 1)) | |
local upperName = name:len() > 1 and headName .. name:sub(2) or headName | |
local setterName = "set" .. upperName | |
return setterName | |
end | |
-------------------------------------------------------------------------------- | |
-- プロパティ名からgetter関数名を返します. | |
-------------------------------------------------------------------------------- | |
function M.getGetterName(name) | |
local headName = string.upper(name:sub(1, 1)) | |
local upperName = name:len() > 1 and headName .. name:sub(2) or headName | |
local setterName = "get" .. upperName | |
return setterName | |
end | |
return M end) | |
package.preload['hp/util/Triangulation'] = (function (...) | |
-------------------------------------------------------------------------------- | |
-- Triangulation routine is based on code by <br> | |
-- JOHN W. RATCLIFF ([email protected]), July 22, 2000 <br> | |
-------------------------------------------------------------------------------- | |
local M = {} | |
local EPSILON = 0.0000000001 | |
local function area( contour ) | |
local n = #contour | |
local A = 0 | |
local p = n | |
local q = 1 | |
while q <= n do | |
print( "n, p,q", n, p, q) | |
A = A + contour[p].x * contour[q].y - contour[q].x * contour[p].y | |
p = q | |
q = q + 1 | |
end | |
print("A=", .5 * A ) | |
return .5 * A | |
end | |
local function insideTriangle( Ax, Ay, Bx, By, Cx, Cy, Px, Py ) | |
local ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy; | |
local cCROSSap, bCROSScp, aCROSSbp; | |
ax = Cx - Bx | |
ay = Cy - By | |
bx = Ax - Cx | |
by = Ay - Cy | |
cx = Bx - Ax | |
cy = By - Ay | |
apx= Px - Ax | |
apy= Py - Ay | |
bpx= Px - Bx | |
bpy= Py - By | |
cpx= Px - Cx | |
cpy= Py - Cy | |
aCROSSbp = ax*bpy - ay*bpx | |
cCROSSap = cx*apy - cy*apx | |
bCROSScp = bx*cpy - by*cpx | |
return ( aCROSSbp >= 0 ) and ( bCROSScp >= 0 ) and ( cCROSSap >= 0 ) | |
end | |
local function snip( contour, u, v, w, n, V ) | |
local Ax, Ay, Bx, By, Cx, Cy, Px, Py | |
Ax = contour[ V[u] ].x | |
Ay = contour[ V[u] ].y | |
Bx = contour[ V[v] ].x | |
By = contour[ V[v] ].y | |
Cx = contour[ V[w] ].x | |
Cy = contour[ V[w] ].y | |
if EPSILON > (((Bx-Ax)*(Cy-Ay)) - ((By-Ay)*(Cx-Ax))) then | |
return false | |
end | |
for p=1, n do | |
if p ~= u and p ~= v and p ~= w then | |
Px = contour[ V[p] ].x | |
Py = contour[ V[p] ].y | |
if insideTriangle( Ax, Ay, Bx, By, Cx, Cy, Px, Py ) then | |
return false | |
end | |
end | |
end | |
return true | |
end | |
function M.process( contour ) | |
local result = {} | |
local n = #contour | |
local V = {} | |
-- we want a counter-clockwise polygon in V | |
if 0 < area( contour ) then | |
for v = 1, n do | |
V[v] = v | |
end | |
else | |
for v = 1, n do | |
V[v] = n - v + 1 | |
end | |
end | |
local nv = n | |
-- remove nv-2 vertices, creating 1 triangle every time | |
local count = 2 * nv | |
--for(int m=0, v=nv-1; nv>2; ) | |
local v = nv | |
local m = 1 | |
while nv > 2 do | |
count = count - 1 | |
-- if we loop, probably it's a non-simple polygon | |
-- (it crosses its own boundary) | |
if count < 0 then | |
print("ERROR: Polygon is self-intersecting. Can't triangulate.") | |
--debugger.printTable( contour, "contour" ) | |
--debugger.printTable( result, "result" ) | |
return false | |
end | |
-- 3 consecutive vertices in current polygon <u,v,w> | |
local u = v | |
if nv < u then u = 1 end -- previous (all 3 were = 0) | |
v = u + 1 | |
if nv < v then v = 1 end -- new v | |
local w = v + 1 | |
if nv < w then w = 1 end -- next | |
-- print("u, v, w, nv, count ", u, v, w, nv, count ) | |
if snip( contour, u, v, w, nv, V ) then | |
local a, b, c, s, triangles | |
a = V[u] | |
b = V[v] | |
c = V[w] | |
-- Output triangle | |
result[#result+1] = { contour[a].x, contour[a].y } | |
result[#result+1] = { contour[b].x, contour[b].y } | |
result[#result+1] = { contour[c].x, contour[c].y } | |
table.remove( V, v ) | |
nv = nv - 1 | |
-- Reset error counter | |
count = 2 * nv | |
end | |
end | |
V = nil | |
return result | |
end | |
return M end) | |
-- load everything | |
Application = require "hp/core/Application" | |
Animation = require "hp/display/Animation" | |
BackgroundSprite = require "hp/display/BackgroundSprite" | |
DisplayObject = require "hp/display/DisplayObject" | |
Graphics = require "hp/display/Graphics" | |
Group = require "hp/display/Group" | |
Layer = require "hp/display/Layer" | |
MapSprite = require "hp/display/MapSprite" | |
Mesh = require "hp/display/Mesh" | |
NinePatch = require "hp/display/NinePatch" | |
Particles = require "hp/display/Particles" | |
Resizable = require "hp/display/Resizable" | |
Scene = require "hp/display/Scene" | |
SceneAnimation = require "hp/display/SceneAnimation" | |
Sprite = require "hp/display/Sprite" | |
SpriteSheet = require "hp/display/SpriteSheet" | |
TextLabel = require "hp/display/TextLabel" | |
TextureDrawable = require "hp/display/TextureDrawable" | |
TouchProcessor = require "hp/display/TouchProcessor" | |
Event = require "hp/event/Event" | |
EventDispatcher = require "hp/event/EventDispatcher" | |
EventListener = require "hp/event/EventListener" | |
SceneFactory = require "hp/factory/SceneFactory" | |
Button = require "hp/gui/Button" | |
Component = require "hp/gui/Component" | |
DialogBox = require "hp/gui/DialogBox" | |
Joystick = require "hp/gui/Joystick" | |
MessageBox = require "hp/gui/MessageBox" | |
Panel = require "hp/gui/Panel" | |
Scroller = require "hp/gui/Scroller" | |
Slider = require "hp/gui/Slider" | |
Theme = require "hp/gui/Theme" | |
View = require "hp/gui/View" | |
array = require "hp/lang/array" | |
class = require "hp/lang/class" | |
delegate = require "hp/lang/delegate" | |
math = require "hp/lang/math" | |
string = require "hp/lang/string" | |
table = require "hp/lang/table" | |
BaseLayout = require "hp/layout/BaseLayout" | |
BoxLayout = require "hp/layout/BoxLayout" | |
HBoxLayout = require "hp/layout/HBoxLayout" | |
VBoxLayout = require "hp/layout/VBoxLayout" | |
FocusManager = require "hp/manager/FocusManager" | |
FontManager = require "hp/manager/FontManager" | |
InputManager = require "hp/manager/InputManager" | |
LayoutManager = require "hp/manager/LayoutManager" | |
ResourceManager = require "hp/manager/ResourceManager" | |
SceneManager = require "hp/manager/SceneManager" | |
ShaderManager = require "hp/manager/ShaderManager" | |
SoundManager = require "hp/manager/SoundManager" | |
TextureManager = require "hp/manager/TextureManager" | |
ThemeManager = require "hp/manager/ThemeManager" | |
PhysicsBody = require "hp/physics/PhysicsBody" | |
PhysicsFixture = require "hp/physics/PhysicsFixture" | |
PhysicsWorld = require "hp/physics/PhysicsWorld" | |
RPGMapView = require "hp/rpg/RPGMapView" | |
RPGSprite = require "hp/rpg/RPGSprite" | |
RPGMove = require "hp/rpg/move/RPGMove" | |
RPGMoveFactory = require "hp/rpg/move/RPGMoveFactory" | |
RPGRandomMove = require "hp/rpg/move/RPGRandomMove" | |
TMXLayer = require "hp/tmx/TMXLayer" | |
TMXMap = require "hp/tmx/TMXMap" | |
TMXMapLoader = require "hp/tmx/TMXMapLoader" | |
TMXMapView = require "hp/tmx/TMXMapView" | |
TMXObject = require "hp/tmx/TMXObject" | |
TMXObjectGroup = require "hp/tmx/TMXObjectGroup" | |
TMXTileset = require "hp/tmx/TMXTileset" | |
CompareUtil = require "hp/util/CompareUtil" | |
Executors = require "hp/util/Executors" | |
FpsMonitor = require "hp/util/FpsMonitor" | |
Logger = require "hp/util/Logger" | |
MOAIPropUtil = require "hp/util/MOAIPropUtil" | |
PriorityQueue = require "hp/util/PriorityQueue" | |
PropertyUtil = require "hp/util/PropertyUtil" | |
Triangulation = require "hp/util/Triangulation" | |
return _G |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment