Advertisement
DaxSoft

Dax Core i6.1

Jan 27th, 2015
671
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 181.06 KB | None | 0 0
  1. #==============================================================================
  2. # * Dax Core
  3. #==============================================================================
  4. # Autor : Dax Aquatic X
  5. # Coadjuvantes :
  6. # Gab! : Bitmap#save
  7. # Gotoken : Módulo de Benchmark.
  8. # Versão : Core i6.1
  9. # Site : www.dax-soft.weebly.com
  10. # Suporte : dax-soft@live.com
  11. #==============================================================================
  12. # Um Core com vários módulos e métodos que facilitará na hora de programar os
  13. # seus scripts, bom proveito.
  14. #==============================================================================
  15. # Conteúdo : • TAGS : Para facilitar a localização dos códigos e explicações. Para acessar
  16. # o comando para localizar, basta apertar Ctrl+F.
  17. #==============================================================================
  18. # i :
  19. # - Array :array
  20. # - Api :api
  21. # - String :string
  22. # - Integer :integer
  23. # - Numeric :numeric
  24. # - File :file
  25. # - Dir :dir
  26. # - IO :io
  27. # - Color :color
  28. # - Rect :rect
  29. # - DMath :dmath
  30. # - Key :key
  31. # - Sprite :sprite
  32. # - Bitmap :bitmap (Método #save por Gab! -> Créditos a ele)
  33. # - Mouse :mouse
  34. # - Sprite_Mouse :sprite_mouse
  35. # - Object :object
  36. # - Entries :entries
  37. # - DRGSS :drgss
  38. # - Backup :backup
  39. # - SceneManager :scenemanager
  40. # - Sprite_Text :sprite_text
  41. # - Sprite_Icon :sprite_icon
  42. # - Opacity :opacity
  43. # - Read :read
  44. # - Background :background
  45. # - Window_Base :window_base
  46. # - Sound_Base :sound_base
  47. # - Position :position
  48. # - Animation :animation
  49. # - Sprite_Anime_Horz :sprite_anime_horz
  50. # - Sprite_Anime_Vert :sprite_anime_vert
  51. # - Crypt :crypt
  52. # - Benchmark :benchmark
  53. #==============================================================================
  54. # • Adicionado comentário padrão. Veja o modo que agora os comentários dos
  55. # métodos estão.
  56. #==============================================================================
  57. # • [Classe do Retorno] : Explicação.
  58. # * Exemplo.(Se possível.)
  59. #==============================================================================
  60. module Dax
  61. extend self
  62. #----------------------------------------------------------------------------
  63. # • Constantes
  64. #----------------------------------------------------------------------------
  65. # A imagem do ícone do Mouse tem que estar na pasta [System]. Basta você
  66. # por o nome da imagem dentro das áspas. Caso você queira usar um ícone
  67. # do Rpg Maker no lugar de uma imagem, basta você por o id do ícone no lugar
  68. # das áspas.
  69. Mouse_Name = ""
  70. #----------------------------------------------------------------------------
  71. # • Variáveis
  72. #----------------------------------------------------------------------------
  73. @register = { } # Variável útilizada para registrar os scripts que fora criado.
  74. @benchmark = "" # Armazena os testes conclusos de benchmark.
  75. #----------------------------------------------------------------------------
  76. # • Método de registrar scripts :
  77. #----------------------------------------------------------------------------
  78. # ** Este método tem de ser definido alguns valores como :
  79. # symbol - nome do script, que é posto em símbolo : Ex - :arrow
  80. # name - nome do autor do script, que é posto em áspas
  81. # version - versão do script;
  82. # data - data do script;
  83. # Dax.register(symbol, name, version, data)
  84. # ** Você pode usá-lo para somente registrar o nome do script.
  85. # Dax.register(symbol)
  86. #----------------------------------------------------------------------------
  87. def register(*args)
  88. if @register.has_key?(args[0])
  89. @register[args[0]][:version] = args[1]
  90. @register[args[0]][:data] = args[2]
  91. else
  92. @register[args[0]] = {name: args[1], version: args[2], data: args[3], script: nil}
  93. end
  94. end
  95. #----------------------------------------------------------------------------
  96. # • Somente executará o bloco caso estiver registrado o script. Compatível
  97. # com o $imported. Caso não esteja registrado no Core e esteja registrado
  98. # na variável $imported, dará!
  99. #----------------------------------------------------------------------------
  100. # Exemplo:
  101. # Dax.required_script(:teste) { # Só irá executar caso estiver registrado.
  102. # methods...
  103. # }
  104. #----------------------------------------------------------------------------
  105. def required_script(symbol, &block)
  106. return unless block_given?
  107. block.call if @register.has_key?(symbol) or $imported.has_key?(symbol)
  108. end
  109. #----------------------------------------------------------------------------
  110. # • Método de verificar se o objeto existe.
  111. #----------------------------------------------------------------------------
  112. # Dax.if_defined?("Objeto") { }
  113. # Dentro das chaves você poem o script.
  114. # * Exemplo :
  115. # Dax.required_class("Window_Base") {
  116. # class Window_Base < Window
  117. # def example
  118. # self.x = self.x + self.width
  119. # end
  120. # end
  121. # }
  122. #----------------------------------------------------------------------------
  123. # Executa o bloco se o objeto existir.
  124. #----------------------------------------------------------------------------
  125. def if_defined?(name, &block)
  126. return unless defined?(name)
  127. eval("block.call if defined?(name)")
  128. end
  129. #----------------------------------------------------------------------------
  130. # • Fazer benchmark de um bloco. O resultado será impresso no Console do
  131. # Maker.
  132. #----------------------------------------------------------------------------
  133. # Dax.benchmark(name(opcional)) { BLOCO }
  134. #----------------------------------------------------------------------------
  135. def benchmark(name="", &block)
  136. time = Time.now
  137. block.call
  138. puts "Benchmark: #{name} : #{(time - Time.now).abs.to_f} segundos!"
  139. @benchmark += "#{name} : #{(time - Time.now).to_f} segundos!\r\n"
  140. end
  141. #----------------------------------------------------------------------------
  142. # • Salva os testes de benchmark num arquivo chamado 'Benchmark' de extensão
  143. # .txt.
  144. #----------------------------------------------------------------------------
  145. def benchmark_save
  146. File.open("Benchmark.txt", "a+") do |file|
  147. file.write(@benchmark)
  148. file.close
  149. end
  150. end
  151. #----------------------------------------------------------------------------
  152. # • Requirir um arquivo.
  153. # arquivo : Arquivo...
  154. #----------------------------------------------------------------------------
  155. def require(arquivo)
  156. $: << "./"
  157. Kernel.send(:require, arquivo)
  158. end
  159. #----------------------------------------------------------------------------
  160. # * Remove uma [Classe], exemplo: Dax.remove(:Scene_Menu)
  161. #----------------------------------------------------------------------------
  162. def remove(symbol_name)
  163. Object.send(:remove_const, symbol_name)
  164. end
  165. end
  166. #==============================================================================
  167. # • Array
  168. #==============================================================================
  169. Dax.register :array
  170. class Array
  171. #----------------------------------------------------------------------------
  172. # • [Array] : Sorteia os objetos em ordem crescente.
  173. #----------------------------------------------------------------------------
  174. def crescent
  175. sort { |a, b| a <=> b }
  176. end
  177. #----------------------------------------------------------------------------
  178. # • [Array] : Sorteia os objetos em ordem decrescente.
  179. #----------------------------------------------------------------------------
  180. def decrescent
  181. sort { |a, b| b <=> a }
  182. end
  183. #----------------------------------------------------------------------------
  184. # • [Object] : Retorna para o próximo objeto da id da Array.
  185. # x = [1, 8]
  186. # x.next # 1
  187. # x.next # 8
  188. #----------------------------------------------------------------------------
  189. def next(x=0)
  190. @next = (@next.nil? ? 0 : @next == self.size - 1 ? 0 : @next.next + x)
  191. return self[@next]
  192. end
  193. #----------------------------------------------------------------------------
  194. # • [Object] : Retorna para o objeto anterior da id da Array.
  195. # x = [1, 8]
  196. # x.prev # 8
  197. # x.prev # 1
  198. #----------------------------------------------------------------------------
  199. def pred(x = 0)
  200. @prev = (@prev.nil? ? self.size-1 : @prev == 0 ? self.size-1 : @prev.pred + x)
  201. return self[@prev]
  202. end
  203. #----------------------------------------------------------------------------
  204. # • [Integer] Retorna ao número do @next
  205. #----------------------------------------------------------------------------
  206. def _next
  207. return @next || 0
  208. end
  209. #----------------------------------------------------------------------------
  210. # • [Integer] Retorna ao número do @pred
  211. #----------------------------------------------------------------------------
  212. def _pred
  213. return @pred || 0
  214. end
  215. #----------------------------------------------------------------------------
  216. # • [Array] Retorna ao elemento da array que condiz com a condição
  217. # definida no bloco.
  218. # Exemplo:
  219. # [2, 4, 5, 6, 8].if { |element| element >= 4 }
  220. # # 5, 6, 8
  221. #----------------------------------------------------------------------------
  222. def if
  223. return unless block_given?
  224. getResult ||= []
  225. self.each_with_index{ |arrays| getResult << arrays if yield(arrays) }
  226. return getResult
  227. end
  228. #----------------------------------------------------------------------------
  229. # • [Mixed] : Retorna ao primeiro valor da array, que obedeça a
  230. # condição posta.
  231. # msgbox [2, 3, 4, 5, 6].first! { |n| n.is_evan? } #> 2
  232. # msgbox [2, 3, 4, 5, 6].first! { |n| n.is_odd? } #> 3
  233. #----------------------------------------------------------------------------
  234. def first!
  235. return unless block_given?
  236. return self.each { |element| return element if yield(element) }.at(0)
  237. end
  238. #----------------------------------------------------------------------------
  239. # • [Numeric] : Retorna ao valor de todos os conteúdos, desde que seja números,
  240. # somados, ou subtraidos, ou multiplicado. Por padrão é soma.
  241. # v : :+ # Somar
  242. # :- # Subtrair
  243. # :* # Multiplicar.
  244. #----------------------------------------------------------------------------
  245. def alln?(v=:+)
  246. n = v == :* ? 1 : 0
  247. self.if {|i| i.is_a?(Numeric) }.each { |content|
  248. n += content if v == :+
  249. n -= content if v == :-
  250. n *= content if v == :*
  251. }
  252. return n
  253. end
  254. end
  255. #==============================================================================
  256. # • Hash
  257. #==============================================================================
  258. Dax.register :hash
  259. class Hash
  260. #----------------------------------------------------------------------------
  261. # • [NilClass] : Pega o valor da chave específicada.
  262. # {1 => 12}.get(1) #=> 12
  263. #----------------------------------------------------------------------------
  264. def get(key)
  265. self.keys.each { |data|
  266. return self[data] if key == data
  267. }
  268. return nil
  269. end
  270. #----------------------------------------------------------------------------
  271. # • [Mix] : Retorna a última chave adicionada.
  272. #----------------------------------------------------------------------------
  273. def last_key
  274. return self.keys.last
  275. end
  276. end
  277. Dax.register :api
  278. #==============================================================================
  279. # • API : Módulo que armazena informações de algumas APIS.
  280. #==============================================================================
  281. module API
  282. extend self
  283. #----------------------------------------------------------------------------
  284. # • [String] : Tipos e seus retornos.. Pegado da internet.. Autor desconhecido
  285. #----------------------------------------------------------------------------
  286. TYPES = {
  287. struct: "p",
  288. int: "i",
  289. long: "l",
  290. INTERNET_PORT: "l",
  291. SOCKET: "p",
  292. C: "p", #– 8-bit unsigned character (byte)
  293. c: "p", # 8-bit character (byte)
  294. # "i"8 – 8-bit signed integer
  295. # "i"8 – 8-bit unsigned integer
  296. S: "N", # – 16-bit unsigned integer (Win32/API: S used for string params)
  297. s: "n", # – 16-bit signed integer
  298. # "i"16 – 16-bit unsigned integer
  299. # "i"16 – 16-bit signed integer
  300. I: "I", # 32-bit unsigned integer
  301. i: "i", # 32-bit signed integer
  302. # "i"32 – 32-bit unsigned integer
  303. # "i"32 – 32-bit signed integer
  304. L: "L", # unsigned long int – platform-specific size
  305. l: "l", # long int – platform-specific size. For discussion of platforms, see:
  306. # (http://groups.google.com/group/ruby-ffi/browse_thread/thread/4762fc77130339b1)
  307. # "i"64 – 64-bit signed integer
  308. # "i"64 – 64-bit unsigned integer
  309. # "l"_long – 64-bit signed integer
  310. # "l"_long – 64-bit unsigned integer
  311. F: "L", # 32-bit floating point
  312. D: "L", # 64-bit floating point (double-precision)
  313. P: "P", # pointer – platform-specific size
  314. p: "p", # C-style (NULL-terminated) character string (Win32API: S)
  315. B: "i", # (?? 1 byte in C++)
  316. V: "V", # For functions that return nothing (return type void).
  317. v: "v", # For functions that return nothing (return type void).
  318. LPPOINT: "p",
  319. # Windows-specific type defs (ms-help://MS.MSDNQTR.v90.en/winprog/winprog/windows_data_types.htm):
  320. ATOM: "I", # Atom ~= Symbol: Atom table stores strings and corresponding identifiers. Application
  321. # places a string in an atom table and receives a 16-bit integer, called an atom, that
  322. # can be used to access the string. Placed string is called an atom name.
  323. # See: http://msdn.microsoft.com/en-us/library/ms648708%28VS.85%29.aspx
  324. BOOL: "i",
  325. BOOLEAN: "i",
  326. BYTE: "p", # Byte (8 bits). Declared as unsigned char
  327. #CALLBACK: K, # Win32.API gem-specific ?? MSDN: #define CALLBACK __stdcall
  328. CHAR: "p", # 8-bit Windows (ANSI) character. See http://msdn.microsoft.com/en-us/library/dd183415%28VS.85%29.aspx
  329. COLORREF: "i", # Red, green, blue (RGB) color value (32 bits). See COLORREF for more info.
  330. DWORD: "i", # 32-bit unsigned integer. The range is 0 through 4,294,967,295 decimal.
  331. DWORDLONG: "i", # 64-bit unsigned integer. The range is 0 through 18,446,744,073,709,551,615 decimal.
  332. DWORD_PTR: "l", # Unsigned long type for pointer precision. Use when casting a pointer to a long type
  333. # to perform pointer arithmetic. (Also commonly used for general 32-bit parameters that have
  334. # been extended to 64 bits in 64-bit Windows.) BaseTsd.h: #typedef ULONG_PTR DWORD_PTR;
  335. DWORD32: "I",
  336. DWORD64: "I",
  337. HALF_PTR: "i", # Half the size of a pointer. Use within a structure that contains a pointer and two small fields.
  338. # BaseTsd.h: #ifdef (_WIN64) typedef int HALF_PTR; #else typedef short HALF_PTR;
  339. HACCEL: "i", # (L) Handle to an accelerator table. WinDef.h: #typedef HANDLE HACCEL;
  340. # See http://msdn.microsoft.com/en-us/library/ms645526%28VS.85%29.aspx
  341. HANDLE: "l", # (L) Handle to an object. WinNT.h: #typedef PVOID HANDLE;
  342. # todo: Platform-dependent! Need to change to "i"64 for Win64
  343. HBITMAP: "l", # (L) Handle to a bitmap: http://msdn.microsoft.com/en-us/library/dd183377%28VS.85%29.aspx
  344. HBRUSH: "l", # (L) Handle to a brush. http://msdn.microsoft.com/en-us/library/dd183394%28VS.85%29.aspx
  345. HCOLORSPACE: "l", # (L) Handle to a color space. http://msdn.microsoft.com/en-us/library/ms536546%28VS.85%29.aspx
  346. HCURSOR: "l", # (L) Handle to a cursor. http://msdn.microsoft.com/en-us/library/ms646970%28VS.85%29.aspx
  347. HCONV: "l", # (L) Handle to a dynamic data exchange (DDE) conversation.
  348. HCONVLIST: "l", # (L) Handle to a DDE conversation list. HANDLE - L ?
  349. HDDEDATA: "l", # (L) Handle to DDE data (structure?)
  350. HDC: "l", # (L) Handle to a device context (DC). http://msdn.microsoft.com/en-us/library/dd183560%28VS.85%29.aspx
  351. HDESK: "l", # (L) Handle to a desktop. http://msdn.microsoft.com/en-us/library/ms682573%28VS.85%29.aspx
  352. HDROP: "l", # (L) Handle to an internal drop structure.
  353. HDWP: "l", # (L) Handle to a deferred window position structure.
  354. HENHMETAFILE: "l", #(L) Handle to an enhanced metafile. http://msdn.microsoft.com/en-us/library/dd145051%28VS.85%29.aspx
  355. HFILE: "i", # (I) Special file handle to a file opened by OpenFile, not CreateFile.
  356. # WinDef.h: #typedef int HFILE;
  357. HFONT: "l", # (L) Handle to a font. http://msdn.microsoft.com/en-us/library/dd162470%28VS.85%29.aspx
  358. HGDIOBJ: "l", # (L) Handle to a GDI object.
  359. HGLOBAL: "l", # (L) Handle to a global memory block.
  360. HHOOK: "l", # (L) Handle to a hook. http://msdn.microsoft.com/en-us/library/ms632589%28VS.85%29.aspx
  361. HICON: "l", # (L) Handle to an icon. http://msdn.microsoft.com/en-us/library/ms646973%28VS.85%29.aspx
  362. HINSTANCE: "l", # (L) Handle to an instance. This is the base address of the module in memory.
  363. # HMODULE and HINSTANCE are the same today, but were different in 16-bit Windows.
  364. HKEY: "l", # (L) Handle to a registry key.
  365. HKL: "l", # (L) Input locale identifier.
  366. HLOCAL: "l", # (L) Handle to a local memory block.
  367. HMENU: "l", # (L) Handle to a menu. http://msdn.microsoft.com/en-us/library/ms646977%28VS.85%29.aspx
  368. HMETAFILE: "l", # (L) Handle to a metafile. http://msdn.microsoft.com/en-us/library/dd145051%28VS.85%29.aspx
  369. HMODULE: "l", # (L) Handle to an instance. Same as HINSTANCE today, but was different in 16-bit Windows.
  370. HMONITOR: "l", # (L) ?andle to a display monitor. WinDef.h: if(WINVER >= 0x0500) typedef HANDLE HMONITOR;
  371. HPALETTE: "l", # (L) Handle to a palette.
  372. HPEN: "l", # (L) Handle to a pen. http://msdn.microsoft.com/en-us/library/dd162786%28VS.85%29.aspx
  373. HRESULT: "l", # Return code used by COM interfaces. For more info, Structure of the COM Error Codes.
  374. # To test an HRESULT value, use the FAILED and SUCCEEDED macros.
  375. HRGN: "l", # (L) Handle to a region. http://msdn.microsoft.com/en-us/library/dd162913%28VS.85%29.aspx
  376. HRSRC: "l", # (L) Handle to a resource.
  377. HSZ: "l", # (L) Handle to a DDE string.
  378. HWINSTA: "l", # (L) Handle to a window station. http://msdn.microsoft.com/en-us/library/ms687096%28VS.85%29.aspx
  379. HWND: "l", # (L) Handle to a window. http://msdn.microsoft.com/en-us/library/ms632595%28VS.85%29.aspx
  380. INT: "i", # 32-bit signed integer. The range is -2147483648 through 2147483647 decimal.
  381. INT_PTR: "i", # Signed integer type for pointer precision. Use when casting a pointer to an integer
  382. # to perform pointer arithmetic. BaseTsd.h:
  383. #if defined(_WIN64) typedef __int64 INT_PTR; #else typedef int INT_PTR;
  384. INT32: "i", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
  385. INT64: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
  386. LANGID: "n", # Language identifier. For more information, see Locales. WinNT.h: #typedef WORD LANGID;
  387. # See http://msdn.microsoft.com/en-us/library/dd318716%28VS.85%29.aspx
  388. LCID: "i", # Locale identifier. For more information, see Locales.
  389. LCTYPE: "i", # Locale information type. For a list, see Locale Information Constants.
  390. LGRPID: "i", # Language group identifier. For a list, see EnumLanguageGroupLocales.
  391. LONG: "l", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
  392. LONG32: "i", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
  393. LONG64: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
  394. LONGLONG: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
  395. LONG_PTR: "l", # Signed long type for pointer precision. Use when casting a pointer to a long to
  396. # perform pointer arithmetic. BaseTsd.h:
  397. #if defined(_WIN64) typedef __int64 LONG_PTR; #else typedef long LONG_PTR;
  398. LPARAM: "l", # Message parameter. WinDef.h as follows: #typedef LONG_PTR LPARAM;
  399. LPBOOL: "i", # Pointer to a BOOL. WinDef.h as follows: #typedef BOOL far *LPBOOL;
  400. LPBYTE: "i", # Pointer to a BYTE. WinDef.h as follows: #typedef BYTE far *LPBYTE;
  401. LPCSTR: "p", # Pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters.
  402. # See Character Sets Used By Fonts. http://msdn.microsoft.com/en-us/library/dd183415%28VS.85%29.aspx
  403. LPCTSTR: "p", # An LPCWSTR if UNICODE is defined, an LPCSTR otherwise.
  404. LPCVOID: "v", # Pointer to a constant of any type. WinDef.h as follows: typedef CONST void *LPCVOID;
  405. LPCWSTR: "P", # Pointer to a constant null-terminated string of 16-bit Unicode characters.
  406. LPDWORD: "p", # Pointer to a DWORD. WinDef.h as follows: typedef DWORD *LPDWORD;
  407. LPHANDLE: "l", # Pointer to a HANDLE. WinDef.h as follows: typedef HANDLE *LPHANDLE;
  408. LPINT: "I", # Pointer to an INT.
  409. LPLONG: "L", # Pointer to an LONG.
  410. LPSTR: "p", # Pointer to a null-terminated string of 8-bit Windows (ANSI) characters.
  411. LPTSTR: "p", # An LPWSTR if UNICODE is defined, an LPSTR otherwise.
  412. LPVOID: "v", # Pointer to any type.
  413. LPWORD: "p", # Pointer to a WORD.
  414. LPWSTR: "p", # Pointer to a null-terminated string of 16-bit Unicode characters.
  415. LRESULT: "l", # Signed result of message processing. WinDef.h: typedef LONG_PTR LRESULT;
  416. PBOOL: "i", # Pointer to a BOOL.
  417. PBOOLEAN: "i", # Pointer to a BOOL.
  418. PBYTE: "i", # Pointer to a BYTE.
  419. PCHAR: "p", # Pointer to a CHAR.
  420. PCSTR: "p", # Pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters.
  421. PCTSTR: "p", # A PCWSTR if UNICODE is defined, a PCSTR otherwise.
  422. PCWSTR: "p", # Pointer to a constant null-terminated string of 16-bit Unicode characters.
  423. PDWORD: "p", # Pointer to a DWORD.
  424. PDWORDLONG: "L", # Pointer to a DWORDLONG.
  425. PDWORD_PTR: "L", # Pointer to a DWORD_PTR.
  426. PDWORD32: "L", # Pointer to a DWORD32.
  427. PDWORD64: "L", # Pointer to a DWORD64.
  428. PFLOAT: "L", # Pointer to a FLOAT.
  429. PHALF_PTR: "L", # Pointer to a HALF_PTR.
  430. PHANDLE: "L", # Pointer to a HANDLE.
  431. PHKEY: "L", # Pointer to an HKEY.
  432. PINT: "i", # Pointer to an INT.
  433. PINT_PTR: "i", # Pointer to an INT_PTR.
  434. PINT32: "i", # Pointer to an INT32.
  435. PINT64: "i", # Pointer to an INT64.
  436. PLCID: "l", # Pointer to an LCID.
  437. PLONG: "l", # Pointer to a LONG.
  438. PLONGLONG: "l", # Pointer to a LONGLONG.
  439. PLONG_PTR: "l", # Pointer to a LONG_PTR.
  440. PLONG32: "l", # Pointer to a LONG32.
  441. PLONG64: "l", # Pointer to a LONG64.
  442. POINTER_32: "l", # 32-bit pointer. On a 32-bit system, this is a native pointer. On a 64-bit system, this is a truncated 64-bit pointer.
  443. POINTER_64: "l", # 64-bit pointer. On a 64-bit system, this is a native pointer. On a 32-bit system, this is a sign-extended 32-bit pointer.
  444. POINTER_SIGNED: "l", # A signed pointer.
  445. HPSS: "l",
  446. POINTER_UNSIGNED: "l", # An unsigned pointer.
  447. PSHORT: "l", # Pointer to a SHORT.
  448. PSIZE_T: "l", # Pointer to a SIZE_T.
  449. PSSIZE_T: "l", # Pointer to a SSIZE_T.
  450. PSS_CAPTURE_FLAGS: "l",
  451. PSTR: "p", # Pointer to a null-terminated string of 8-bit Windows (ANSI) characters. For more information, see Character Sets Used By Fonts.
  452. PTBYTE: "p", # Pointer to a TBYTE.
  453. PTCHAR: "p", # Pointer to a TCHAR.
  454. PTSTR: "p", # A PWSTR if UNICODE is defined, a PSTR otherwise.
  455. PUCHAR: "p", # Pointer to a UCHAR.
  456. PUINT: "i", # Pointer to a UINT.
  457. PUINT_PTR: "i", # Pointer to a UINT_PTR.
  458. PUINT32: "i", # Pointer to a UINT32.
  459. PUINT64: "i", # Pointer to a UINT64.
  460. PULONG: "l", # Pointer to a ULONG.
  461. PULONGLONG: "l", # Pointer to a ULONGLONG.
  462. PULONG_PTR: "l", # Pointer to a ULONG_PTR.
  463. PULONG32: "l", # Pointer to a ULONG32.
  464. PULONG64: "l", # Pointer to a ULONG64.
  465. PUSHORT: "l", # Pointer to a USHORT.
  466. PVOID: "v", # Pointer to any type.
  467. PWCHAR: "p", # Pointer to a WCHAR.
  468. PWORD: "p", # Pointer to a WORD.
  469. PWSTR: "p", # Pointer to a null- terminated string of 16-bit Unicode characters.
  470. # For more information, see Character Sets Used By Fonts.
  471. SC_HANDLE: "l", # (L) Handle to a service control manager database.
  472. SERVICE_STATUS_HANDLE: "l", # (L) Handle to a service status value. See SCM Handles.
  473. SHORT: "i", # A 16-bit integer. The range is –32768 through 32767 decimal.
  474. SIZE_T: "l", # The maximum number of bytes to which a pointer can point. Use for a count that must span the full range of a pointer.
  475. SSIZE_T: "l", # Signed SIZE_T.
  476. TBYTE: "p", # A WCHAR if UNICODE is defined, a CHAR otherwise.TCHAR:
  477. # http://msdn.microsoft.com/en-us/library/c426s321%28VS.80%29.aspx
  478. TCHAR: "p", # A WCHAR if UNICODE is defined, a CHAR otherwise.TCHAR:
  479. UCHAR: "p", # Unsigned CHAR (8 bit)
  480. UHALF_PTR: "i", # Unsigned HALF_PTR. Use within a structure that contains a pointer and two small fields.
  481. UINT: "i", # Unsigned INT. The range is 0 through 4294967295 decimal.
  482. UINT_PTR: "i", # Unsigned INT_PTR.
  483. UINT32: "i", # Unsigned INT32. The range is 0 through 4294967295 decimal.
  484. UINT64: "i", # Unsigned INT64. The range is 0 through 18446744073709551615 decimal.
  485. ULONG: "l", # Unsigned LONG. The range is 0 through 4294967295 decimal.
  486. ULONGLONG: "l", # 64-bit unsigned integer. The range is 0 through 18446744073709551615 decimal.
  487. ULONG_PTR: "l", # Unsigned LONG_PTR.
  488. ULONG32: "i", # Unsigned INT32. The range is 0 through 4294967295 decimal.
  489. ULONG64: "i", # Unsigned LONG64. The range is 0 through 18446744073709551615 decimal.
  490. UNICODE_STRING: "P", # Pointer to some string structure??
  491. USHORT: "i", # Unsigned SHORT. The range is 0 through 65535 decimal.
  492. USN: "l", # Update sequence number (USN).
  493. WCHAR: "i", # 16-bit Unicode character. For more information, see Character Sets Used By Fonts.
  494. # In WinNT.h: typedef wchar_t WCHAR;
  495. #WINAPI: K, # Calling convention for system functions. WinDef.h: define WINAPI __stdcall
  496. WORD: "i", # 16-bit unsigned integer. The range is 0 through 65535 decimal.
  497. WPARAM: "i", # Message parameter. WinDef.h as follows: typedef UINT_PTR WPARAM;
  498. VOID: "v", # Any type ? Only use it to indicate no arguments or no return value
  499. vKey: "i",
  500. LPRECT: "p",
  501. char: "p",
  502. }
  503. #----------------------------------------------------------------------------
  504. # • [Array] : Pega os valores especificados no método.. depois verifica
  505. # cada um se é String ou Symbol. Se for Symbol retorna ao valor especificado
  506. # na Constante TYPES.
  507. # Exemplo: types([:BOOL, :WCHAR]) # ["i", "i"]
  508. #----------------------------------------------------------------------------
  509. def types(import)
  510. import2 = []
  511. import.each { |i|
  512. next if i.is_a?(NilClass) or i.is_a?(String)
  513. import2 << TYPES[i]
  514. }
  515. return import2
  516. end
  517. #----------------------------------------------------------------------------
  518. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  519. # Por padrão a DLL é a "user32". O valor de exportação será "i"
  520. #----------------------------------------------------------------------------
  521. def int(function, import, dll="user32")
  522. Win32API.new(dll, function, types(import), "i") rescue nil
  523. end
  524. #----------------------------------------------------------------------------
  525. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  526. # Por padrão a DLL é a "user32". O valor de exportação será "l"
  527. #----------------------------------------------------------------------------
  528. def long(function, import, dll="user32")
  529. Win32API.new(dll, function.to_s, types(import), "l") rescue nil
  530. end
  531. #----------------------------------------------------------------------------
  532. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  533. # Por padrão a DLL é a "user32". O valor de exportação será "v"
  534. #----------------------------------------------------------------------------
  535. def void(function, import, dll="user32")
  536. Win32API.new(dll, function.to_s, types(import), "v") rescue nil
  537. end
  538. #----------------------------------------------------------------------------
  539. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  540. # Por padrão a DLL é a "user32". O valor de exportação será "p"
  541. #----------------------------------------------------------------------------
  542. def char(function, import, dll="user32")
  543. Win32API.new(dll, function.to_s, types(import), "p") rescue nil
  544. end
  545. #----------------------------------------------------------------------------
  546. # • [Dll]// : Com esse método você pode especificar uma função de uma Dll.
  547. # function(export, function, import, dll)
  548. # export : Valor da exportação. Formato [Symbol]
  549. # function : Função da Dll.
  550. # import : Valor da importação.
  551. # dll : Dll. Por padrão é a User32
  552. # Esconder o Mouse.
  553. # Exemplo: function(:int, "ShowCursor", [:BOOL]).call(0)
  554. #----------------------------------------------------------------------------
  555. def function(export, function, import, dll="user32")
  556. eval("#{export}(function, import, dll)")
  557. end
  558. #----------------------------------------------------------------------------
  559. # • Especificando o método protegido.
  560. #----------------------------------------------------------------------------
  561. # Métodos privados.
  562. private :long, :int, :char, :void, :types
  563. #----------------------------------------------------------------------------
  564. # • [CopyFile]/Dll : Função da DLL Kernel32 que permite copiar arquivos.
  565. # CopyFile.call(filename_to_copy, filename_copied, replace)
  566. # filename_to_copy : Formato [String]
  567. # filename_copied : Formato [String]
  568. # replace : Formato [Integer] 0 - false 1 - true
  569. # Exemplo: CopyFile.call("System/RGSS300.dll", "./RGSS300.dll", 1)
  570. #----------------------------------------------------------------------------
  571. CopyFile = long("CopyFile", [:LPCTSTR, :LPCTSTR, :BOOL], "kernel32")
  572. #----------------------------------------------------------------------------
  573. # • [Beep]/Dll : Emitir uma frequência de um som do sistema com duração.
  574. # Beep.call(freq, duration)
  575. # freq : Formato [Integer\Hexadécimal]
  576. # duration : Formato [Integer\Hexadécimal]
  577. # Exemplo: Beep.call(2145, 51)
  578. #----------------------------------------------------------------------------
  579. Beep = long('Beep', [:DWORD, :DWORD], 'kernel32')
  580. #----------------------------------------------------------------------------
  581. # • [keybd_event]/Dll : Ela é usada para sintentizar uma combinação de teclas.
  582. # KEYBD_EVENT.call(vk, scan, fdwFlags, dwExtraInfo)
  583. # vk : Formato [Integer/Hexadécimal].
  584. # scan : Formato [Integer]
  585. # fdwFlags : Formato [Integer]
  586. # dwExtraInfo : Formato [Integer]
  587. # Exemplo: KEYBD_EVENT.call(0x01, 0, 0, 0)
  588. #----------------------------------------------------------------------------
  589. KEYBD_EVENT = void('keybd_event', [:BYTE, :BYTE, :DWORD, :ULONG_PTR])
  590. #----------------------------------------------------------------------------
  591. # • Tela chéia
  592. #----------------------------------------------------------------------------
  593. def full_screen
  594. KEYBD_EVENT.(18, 0, 0, 0)
  595. KEYBD_EVENT.(18, 0, 0, 0)
  596. KEYBD_EVENT.(13, 0, 0, 0)
  597. KEYBD_EVENT.(13, 0, 2, 0)
  598. KEYBD_EVENT.(18, 0, 2, 0)
  599. end
  600. #----------------------------------------------------------------------------
  601. # • [GetKeyState]/Dll : Pega o status da chave.
  602. # GetKeyState.call(vk)
  603. # vk : Formato [Integer/Hexadécimal].
  604. # Exemplo: GetKeyState.call(0x01)
  605. #----------------------------------------------------------------------------
  606. GetKeyState = int('GetAsyncKeyState', [:int])
  607. #----------------------------------------------------------------------------
  608. # • [MapVirtualKey] : Traduz (maps) o código de uma key para um código
  609. # escaneado ou o valor de um character.
  610. #----------------------------------------------------------------------------
  611. MapVirtualKey = int("MapVirtualKey", [:UINT, :UINT])
  612. #----------------------------------------------------------------------------
  613. # • [MouseShowCursor]/Dll : Mostrar ou desativar o cusor do Mouse.
  614. # MouseShowCursor.call(value)
  615. # value : Formato [Integer] 0 - false 1 - true
  616. # Exemplo: MouseShowCursor.call(0)
  617. #----------------------------------------------------------------------------
  618. MouseShowCursor = int("ShowCursor", [:int])
  619. #----------------------------------------------------------------------------
  620. # • [CursorPosition]/Dll : Obtem a posição do cursor do Mouse na tela.
  621. # CursorPosition.call(lpPoint)
  622. # lpPoint : Formato [Array]
  623. # Ex: CursorPosition.call([0, 0].pack('ll'))
  624. #----------------------------------------------------------------------------
  625. CursorPosition = int('GetCursorPos', [:LPPOINT])
  626. #----------------------------------------------------------------------------
  627. # • [ScreenToClient]/Dll : Converte as coordenadas da tela para um ponto
  628. # em especifico da área da tela do cliente.
  629. # ScreenToClient.call(hWnd, lpPoint)
  630. #----------------------------------------------------------------------------
  631. ScreenToClient = int('ScreenToClient', [:HWND, :LPPOINT])
  632. #----------------------------------------------------------------------------
  633. # • [GetPrivateProfileString]/Dll : */Ainda não explicado./*
  634. #----------------------------------------------------------------------------
  635. GetPrivateProfileString = long('GetPrivateProfileStringA', [:LPCTSTR, :LPCTSTR, :LPCTSTR, :LPTSTR, :DWORD, :LPCTSTR], 'kernel32')
  636. #----------------------------------------------------------------------------
  637. # • [FindWindow]/Dll : Recupera o identificador da janela superior. Cujo
  638. # o nome da janela é o nome da classe da janela se combina com as cadeias
  639. # especificas.
  640. # FindWindow.call(lpClassName, lpWindowName)
  641. # lpClassName : Formato [String]
  642. # lpWindowName : Formato [String]
  643. #----------------------------------------------------------------------------
  644. FindWindow = long('FindWindowA', [:LPCTSTR, :LPCTSTR])
  645. #----------------------------------------------------------------------------
  646. # • [Handle]/Dll : Retorna ao Handle da janela.
  647. #----------------------------------------------------------------------------
  648. def hWND(game_title=nil)
  649. return API::FindWindow.call('RGSS Player', game_title || load_data("./Data/System.rvdata2").game_title.to_s)
  650. end
  651. #----------------------------------------------------------------------------
  652. # • [Handle]/Dll : Retorna ao Handle da janela. Método protegido.
  653. #----------------------------------------------------------------------------
  654. def hwnd(*args)
  655. hWND(*args)
  656. end
  657. #----------------------------------------------------------------------------
  658. # • [ReadIni]/Dll : */Ainda não explicado./*
  659. #----------------------------------------------------------------------------
  660. ReadIni = GetPrivateProfileString
  661. #----------------------------------------------------------------------------
  662. # • [SetWindowPos]/Dll : Modifica os elementos da janela como, posição, tamanho.
  663. #----------------------------------------------------------------------------
  664. SetWindowPos = int("SetWindowPos", [:HWND, :HWND, :int, :int, :int, :int, :UINT])
  665. #----------------------------------------------------------------------------
  666. # • [GetWindowRect]/Dll : Obtem as dimensões do retângulo da janela.
  667. # GetWindowRect.call(hWnd, lpRect)
  668. #----------------------------------------------------------------------------
  669. GetWindowRect = int('GetWindowRect', [:HWND, :LPRECT])
  670. #----------------------------------------------------------------------------
  671. # • [StateKey]/Dll : Retorna ao status específico da chave.
  672. # StateKey.call(VK)
  673. # VK : Formato [Integer/Hexadécimal].
  674. #----------------------------------------------------------------------------
  675. StateKey = int("GetKeyState", [:int])
  676. #----------------------------------------------------------------------------
  677. # • [SetCursorPos]/Dll : Move o cursor do Mouse para um ponto específico
  678. # da tela.
  679. # SetCursorPos.call(x, y)
  680. # x, y : Formato [Integer/Float]
  681. #----------------------------------------------------------------------------
  682. SetCursorPos = int("SetCursorPos", [:long, :long])
  683. #----------------------------------------------------------------------------
  684. # • [GetKeyboardState]/Dll : Cópia o status das 256 chaves para um
  685. # buffer especificado.
  686. #----------------------------------------------------------------------------
  687. GetKeyboardState = Win32API.new('user32', 'GetKeyboardState', ['P'], 'V')
  688. #----------------------------------------------------------------------------
  689. # • [GetAsyncKeyState]/Dll : Determina o estado da chave no momento em que a
  690. # função é chamada.
  691. # GetAsyncKeyState.call(Vk)
  692. # VK : Formato [Integer/Hexadécimal].
  693. #----------------------------------------------------------------------------
  694. GetAsyncKeyState = int('GetAsyncKeyState', [:int])
  695. #----------------------------------------------------------------------------
  696. # • [WideCharToMultiByte] : [MultiByteToWideChar] // Comentários
  697. # não adicionados.
  698. #----------------------------------------------------------------------------
  699. WideCharToMultiByte = Win32API.new('kernel32', 'WideCharToMultiByte', 'ilpipipp', 'i')
  700. MultiByteToWideChar = Win32API.new('kernel32', 'MultiByteToWideChar', 'ilpipi', 'i')
  701. #----------------------------------------------------------------------------
  702. # • [AdjustWindowRect] : Calcula o tamanho requerido do retângulo da Janela.
  703. #----------------------------------------------------------------------------
  704. AdjustWindowRect = int("AdjustWindowRect", [:LPRECT, :DWORD, :BOOL])
  705. #----------------------------------------------------------------------------
  706. # • Constantes [SetWindowPos]
  707. #----------------------------------------------------------------------------
  708. SWP_ASYNCWINDOWPOS = 0x4000
  709. # Desenha os frames (definidos na classe da janela descrita) em torno na janela.
  710. SWP_DRAWFRAME = 0x0020
  711. # Esconde a janela.
  712. SWP_HIDEWINDOW = 0x0080
  713. # Não pode ser ativada nem movida
  714. SWP_NOACTIVATE = 0x0010
  715. # Não permite mover
  716. SWP_NOMOVE = 0x0002
  717. # Não permite redimensionar
  718. SWP_NOSIZE = 0x0001
  719. # Mostra a Janela
  720. SWP_SHOWWINDOW = 0x0040
  721. # Coloca a janela na parte inferior na ordem de Z. Se identificar uma janela
  722. # superior ela perde os seus status.
  723. HWND_BOTTOM = 1
  724. # Coloca a janela acima de todas as janelas que não estão em primeiro plano.
  725. HWND_NOTOPMOST = -2
  726. # Poem a janela no Topo na ordem de Z.
  727. HWND_TOP = 0
  728. # Poem a janela acima de todas que não estão em primeiro plano. Mantendo a
  729. # posição.
  730. HWND_TOPMOST = -1
  731. #----------------------------------------------------------------------------
  732. # • [SetActiveWindow]/ Dll : Ativa a Window.
  733. #----------------------------------------------------------------------------
  734. SetActiveWindow = long("SetActiveWindow", [:HWND])
  735. #----------------------------------------------------------------------------
  736. # • WindowFromPoint : Retorna ao handle da janela, que contém um ponto
  737. # específico.
  738. #----------------------------------------------------------------------------
  739. WindowFromPoint = long("WindowFromPoint", [:HWND])
  740. #----------------------------------------------------------------------------
  741. # • ShowWindow : Mostra a janela em um estado específico.
  742. #----------------------------------------------------------------------------
  743. ShowWindow = long("ShowWindow", [:HWND, :LONG])
  744. # Força a janela a minimizar
  745. SW_FORCEMINIMIZE = 11
  746. # Esconde a janela, ativa outra.
  747. SW_HIDE = 0
  748. # Maximiza a janela.
  749. SW_MAXIMIZE = 3
  750. # Minimiza a janela
  751. SW_MINIMIZE = 6
  752. # Restaura o estado da janela.
  753. SW_RESTORE = 9
  754. # Ativa a janela a mostrando na posição original.
  755. SW_SHOW = 5
  756. #----------------------------------------------------------------------------
  757. # • [SetWindowText] : Permite modificar o título da janela.
  758. #----------------------------------------------------------------------------
  759. SetWindowText = int("SetWindowText", [:HWND, :LPCTSTR])
  760. #----------------------------------------------------------------------------
  761. # • [GetDesktopWindow] : Retorna ao handle da janela em relação ao Desktop.
  762. #----------------------------------------------------------------------------
  763. GetDesktopWindow = long("GetDesktopWindow", [:HWND])
  764. #----------------------------------------------------------------------------
  765. # • [GetSystemMetric] : Obtem um sistema métrico específico ou a configuração
  766. # do sistema. As dimensões retornadas são em pixel.
  767. #----------------------------------------------------------------------------
  768. GetSystemMetric = int("GetSystemMetric", [:int])
  769. #----------------------------------------------------------------------------
  770. # • [GetSystemMetric]/Constantes:
  771. #----------------------------------------------------------------------------
  772. # Obtem a flag que especifica como o sistema está organizando as janelas
  773. # minimizadas.
  774. SM_ARRANGE = 56
  775. # Obtem o tamanho da borda da Janela em pixel.
  776. SM_CXBORDER = 5
  777. # Valor do tamanho da área do cliente pra uma Janela em modo de tela-chéia.
  778. # em pixel.
  779. SM_CXFULLSCREEN = 16
  780. # Para mais informações dos valores, visite :
  781. # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx
  782. #----------------------------------------------------------------------------
  783. # • [GetClientRect] : Retorna ao rect da área da Janela.
  784. # Uses :
  785. # lpRect = [0,0,0,0].pack("L*")
  786. # GetClientRect.(hwnd, lpRect)
  787. # lpRect = lpRect.unpack("L*")
  788. #----------------------------------------------------------------------------
  789. GetClientRect = int("GetClientRect", [:HWND, :LPRECT])
  790. #----------------------------------------------------------------------------
  791. # • [GetModuleHandle] : Retorna ao Handle do módulo, do módulo específicado.
  792. # Pode ser aquivo '.dll' ou '.exe'. Exemplo:
  793. # GetModuleHandle.call('System/RGSS300.dll')
  794. #----------------------------------------------------------------------------
  795. GetModuleHandle = long("GetModuleHandle", [:LPCTSTR], "kerne32")
  796. #----------------------------------------------------------------------------
  797. # • [FreeLibrary] : Libera o módulo que está carregado na DLL específica.
  798. #----------------------------------------------------------------------------
  799. FreeLibrary = long("FreeLibrary", [:HMODULE], "kernel32")
  800. #----------------------------------------------------------------------------
  801. # • [LoadLibrary] : Carrega um endereço de um módulo em específico.
  802. # LoadLibrary.call(Nome da Libraria(dll/exe))
  803. # [Handle] : Retorna ao valor do Handle do módulo caso der certo.
  804. #----------------------------------------------------------------------------
  805. LoadLibrary = long("LoadLibrary", [:LPCTSTR], "kernel32")
  806. #----------------------------------------------------------------------------
  807. # • [GetProcAddress] : Retorna ao endereço da função exportada ou a variável
  808. # de uma DLL específica.
  809. # GetProcAddress.call(hModule, lpProcName)
  810. # hModule : É o valor do handle. Você pode pega-lo usando o LoadLibrary
  811. # lpProcName : A função ou o nome da variável.
  812. #----------------------------------------------------------------------------
  813. GetProcAddress = long("GetProcAddress", [:HMODULE, :LPCSTR], "kernel32")
  814. #----------------------------------------------------------------------------
  815. # • [GetSystemMetrics] : Retorna á uma configuração específica do sistema
  816. # métrico.
  817. #----------------------------------------------------------------------------
  818. GetSystemMetrics = int("GetSystemMetrics", [:int])
  819. #----------------------------------------------------------------------------
  820. # • [GetSystemMetrics]::Constantes. #Para mais visite:
  821. # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx
  822. #----------------------------------------------------------------------------
  823. SM_CXSCREEN = 0 # O tamanho(width/largura) da janela em pixel.
  824. SM_CYSCREEN = 1 # O tamanho(height/comprimento) da janela em pixel.
  825. SM_CXFULLSCREEN = 16 # O tamanho da largura da tela chéia da janela.
  826. SM_CYFULLSCREEN = 17 # O tamanho do comprimento da tela chéia da janela.
  827. #----------------------------------------------------------------------------
  828. # • [SetPriorityClass] : Definir a classe prioritária para um processo
  829. # específico.
  830. # Para ver os processo e tal : Link abaixo.
  831. # http://msdn.microsoft.com/en-us/library/windows/desktop/ms686219(v=vs.85).aspx
  832. #----------------------------------------------------------------------------
  833. SetPriorityClass = int("SetPriorityClass", [:HANDLE, :DWORD], "kernel32")
  834. #----------------------------------------------------------------------------
  835. # • [InternetOpenA] : Inicializa o uso de uma aplicação, de uma função da
  836. # WinINet.
  837. #----------------------------------------------------------------------------
  838. InternetOpenA = function(:int, "InternetOpenA", [:LPCTSTR, :DWORD, :LPCTSTR, :LPCTSTR, :DWORD], "wininet")
  839. #----------------------------------------------------------------------------
  840. # • [RtlMoveMemory] : Movimenta um bloco de memoria para outra locação.
  841. #----------------------------------------------------------------------------
  842. RtlMoveMemory = function(:int, "RtlMoveMemory", [:char, :char, :int], "kernel32")
  843. #----------------------------------------------------------------------------
  844. # • [Método protegido] : Método usado para chamar a função LoadLibrary.
  845. #----------------------------------------------------------------------------
  846. def dlopen(name, fA=nil)
  847. l = LoadLibrary.(String(name))
  848. return l if fA.nil?
  849. return GetProcAddress.(l, String(fA))
  850. end
  851. #----------------------------------------------------------------------------
  852. # • Converte um texto para o formato UTF-8
  853. # textUTF(text)
  854. # * text : Texto.
  855. #----------------------------------------------------------------------------
  856. def textUTF(text)
  857. wC = MultiByteToWideChar.call(65001, 0, text, -1, "", 0)
  858. MultiByteToWideChar.call(65001, 0, text, -1, text = "\0\0" * wC, wC)
  859. return text
  860. end
  861. #----------------------------------------------------------------------------
  862. # • [TrueClass/FalseClass] : Retorna verdadeiro caso o Caps Lock esteja
  863. # ativo e retorna Falso caso não esteja ativo.
  864. #----------------------------------------------------------------------------
  865. def get_caps_lock
  866. return int("GetKeyState", [:vKey]).call(20) == 1
  867. end
  868. #----------------------------------------------------------------------------
  869. # • Abre a URL de um site o direcionado para o navegador padrão do usuário.
  870. #----------------------------------------------------------------------------
  871. def open_site(url)
  872. c = Win32API.new("Shell32", "ShellExecute", "pppppl", "l")
  873. c.call(nil, "open", url, nil, nil, 0)
  874. end
  875. #============================================================================
  876. # • MessageBox
  877. #============================================================================
  878. module MessageBox
  879. extend self
  880. # handle, string, title, format.
  881. FunctionMessageBox = Win32API.new("user32", "MessageBoxW", "lppl", "l")
  882. #--------------------------------------------------------------------------
  883. # • [Constantes] Botões:
  884. #--------------------------------------------------------------------------
  885. # Adiciona três botões a mensagem: Anular, Repetir e Ignorar.
  886. ABORTRETRYIGNORE = 0x00000002
  887. # Adiciona três botões a mensagem: Cancelar, Tentar e Continuar.
  888. CANCELTRYCONTINUE = 0x00000006
  889. # Adiciona o botão de ajuda.
  890. HELP = 0x00004000
  891. # Adiciona o botão Ok.
  892. OK = 0x00000000
  893. # Adiciona o botão OK e Cancelar.
  894. OKCANCEL = 0x00000001
  895. # Adiciona os botões: Repetir e Cancelar.
  896. RETRYCANCEL = 0x00000005
  897. # Adiciona os botões: Sim e Não
  898. YESNO = 0x00000004
  899. # Adiciona os botões: Sim, Não e Cancelar
  900. YESNOCANCEL = 0x00000003
  901. #--------------------------------------------------------------------------
  902. # • [Constantes] Ícones:
  903. #--------------------------------------------------------------------------
  904. # Adiciona um ícone de exclamação
  905. ICONEXCLAMATION = 0x00000030
  906. # Adiciona um ícone de informação.
  907. ICONINFORMATION = 0x00000040
  908. # Adiciona um ícone de um círculo com um ponto de interrogação.
  909. ICONQUESTION = 0x00000020
  910. # Adiciona um íconde parar na mensagem.
  911. ICONSTOP = 0x00000010
  912. #--------------------------------------------------------------------------
  913. # • [Constantes] Valores de retorno dos botões:
  914. #--------------------------------------------------------------------------
  915. ABORT = 3 # Retorno do valor do botão de Anular
  916. CANCEL = 2 # Retorno do valor do botão de Cancelar.
  917. CONTINUE = 11 # Retorno do valor do botão de Continuar.
  918. IGNORE = 5 # Retorno do valor de ignonar.
  919. NO = 7 # Retorno do valor do botão de Não.
  920. OK = 1 # Retorno do valor do botão de Ok.
  921. RETRY = 4 # Retorno do valor de repetir.
  922. TRYAGAIN = 10 # Retorno do valor de Repetir.
  923. YES = 6 # Retorno do valor do botão de Sim.
  924. #--------------------------------------------------------------------------
  925. # • [Constantes] Valores adicionais.
  926. #--------------------------------------------------------------------------
  927. RIGHT = 0x00080000 # Os textos ficarão justificados a direita.
  928. TOPMOST = 0x00040000 # O estilo da mensagem é criado como WB_EX_TOPMOST
  929. #--------------------------------------------------------------------------
  930. # • [call] : Retorna aos valores dos botões. Para serem usados
  931. # como condição, de que se ao clicar.
  932. # API::MessageBox.call(title, string, format)
  933. # title -> Título da caixa.
  934. # string -> Conteúdo da caixa.
  935. # format -> Formato, no caso seria os botões e ícones.
  936. #--------------------------------------------------------------------------
  937. def call(title, string, format)
  938. return FunctionMessageBox.call(API.hWND, API.textUTF(string), API.textUTF(title), format)
  939. end
  940. #--------------------------------------------------------------------------
  941. # • [messageBox] : Mesma função do Call a diferença é que e protegido.
  942. #--------------------------------------------------------------------------
  943. def messageBox(*args)
  944. self.call(*args)
  945. end
  946. protected :messageBox
  947. end
  948. protected :hwnd, :open, :function
  949. end
  950. #==============================================================================
  951. # * String
  952. #==============================================================================
  953. Dax.register(:string)
  954. class String
  955. #----------------------------------------------------------------------------
  956. # • [String] : Remove a extensão do nome do arquivo e assume por outra.
  957. # filename : Nome do aquivo.
  958. # extension : Nova extensão.
  959. # "Hello.rb".extn(".rvdata2") # "Hello.rvdata2"
  960. #----------------------------------------------------------------------------
  961. def extn(extension)
  962. return self.gsub(/\.(\w+)/, extension.include?(".") ? extension : "." + extension)
  963. end
  964. #--------------------------------------------------------------------------
  965. # • [String] : converter à String em UTF8
  966. #--------------------------------------------------------------------------
  967. def to_utf8
  968. API.textUTF(self)
  969. end
  970. #----------------------------------------------------------------------------
  971. # • [String] : Converter a String para wchar. Pra chamadas WinAPI.
  972. #----------------------------------------------------------------------------
  973. def wchar
  974. wstr = ""
  975. self.size.times { |i| wstr += self[i, 1] + "\0" }
  976. wstr += "\0"
  977. return wstr
  978. end
  979. #--------------------------------------------------------------------------
  980. # • [Array] : Extrai somente os números da String, e retorna a uma Array.
  981. # Exemplo: "João89".numbers # [8, 9]
  982. #--------------------------------------------------------------------------
  983. def numbers
  984. self.scan(/-*\d+/).collect{|n|n.to_i}
  985. end
  986. #----------------------------------------------------------------------------
  987. # • [String] : Aplicando Case Sensitive
  988. # "Exemplo 2" => "Exemplo_2"
  989. #----------------------------------------------------------------------------
  990. def case_sensitive
  991. return self.gsub(" ", "_")
  992. end
  993. #----------------------------------------------------------------------------
  994. # • [Symbol] : Transforma em símbolo a string.
  995. # "Ola Meu Nome É" #:ola_menu_nome_é
  996. #----------------------------------------------------------------------------
  997. def symbol
  998. return self.case_sensitive.downcase.to_sym
  999. end
  1000. #----------------------------------------------------------------------------
  1001. # • [String] : Remove o último caractere da String.
  1002. #----------------------------------------------------------------------------
  1003. def backslash
  1004. return String(self[0, self.split(//).size-1])
  1005. end
  1006. #----------------------------------------------------------------------------
  1007. # • Método xor.
  1008. #----------------------------------------------------------------------------
  1009. def ^(string)
  1010. bytes.map.with_index{|byte, index| byte ^ other[index % other.size].ord }.pack("C*")
  1011. end
  1012. alias xor ^
  1013. end
  1014. #==============================================================================
  1015. # * Integer
  1016. #==============================================================================
  1017. Dax.register(:integer)
  1018. class Integer
  1019. #----------------------------------------------------------------------------
  1020. # • [TrueClass/FalseClass] : Verifica-se e par.
  1021. #----------------------------------------------------------------------------
  1022. def is_evan?
  1023. return (self & 1) == 0
  1024. end
  1025. #----------------------------------------------------------------------------
  1026. # • [TrueClass/FalseClass] : Verifica-se e impar.
  1027. #----------------------------------------------------------------------------
  1028. def is_odd?
  1029. return (self & 1) == 1
  1030. end
  1031. #----------------------------------------------------------------------------
  1032. # • [Integer] : Aumenta o valor até chegar ao máximo(definido), quando
  1033. # chegar ao máximo(definido) retorna a zero(pode definir).
  1034. #----------------------------------------------------------------------------
  1035. def up(max, r=0)
  1036. n = self
  1037. n = n > max ? r : n.next
  1038. return n
  1039. end
  1040. #----------------------------------------------------------------------------
  1041. # • [Integer] : Diminui o valor até chegar a zero, quando chegar a zero(pode definir)
  1042. # retorna ao valor máximo(defindo).
  1043. #----------------------------------------------------------------------------
  1044. def down(max, r=0)
  1045. n = self
  1046. n = n < r ? max : n.pred
  1047. return n
  1048. end
  1049. #----------------------------------------------------------------------------
  1050. # • [Integer] : Sistema simplificado para fazer calculos factoriais.
  1051. # !4 #> 24
  1052. #----------------------------------------------------------------------------
  1053. def !@
  1054. return unless self > 0
  1055. return self.downto(1).reduce(:*)
  1056. end
  1057. alias factorial !@
  1058. #----------------------------------------------------------------------------
  1059. # • [Integer] : Formula de número randômico.
  1060. #----------------------------------------------------------------------------
  1061. def aleatory
  1062. return ((1..(self.abs)).to_a).shuffle[rand(self).to_i].to_i
  1063. end
  1064. end
  1065. #==============================================================================
  1066. # • Numeric
  1067. #==============================================================================
  1068. Dax.register(:numeric)
  1069. class Numeric
  1070. #----------------------------------------------------------------------------
  1071. # * [Numeric] : Transformar em porcentagem
  1072. # a : Valor atual.
  1073. # b : Valor máximo.
  1074. #----------------------------------------------------------------------------
  1075. def to_p(a, b)
  1076. self * a / b
  1077. end
  1078. #----------------------------------------------------------------------------
  1079. # * [Numeric] : Variação do número.
  1080. #----------------------------------------------------------------------------
  1081. def randomic(x=4)
  1082. return ( (self+rand(2)) + (self + (rand(2) == 0 ? rand(x) : -rand(x)) ) ) / 2
  1083. end
  1084. #----------------------------------------------------------------------------
  1085. # * [Boolean] : Verifica se o número é igual a um dos especificados.
  1086. # 1.if(2, 3) # false
  1087. #----------------------------------------------------------------------------
  1088. def if(*args)
  1089. args.each { |i|
  1090. if self == i
  1091. return true
  1092. else
  1093. next
  1094. end
  1095. }
  1096. return false
  1097. end
  1098. end
  1099. #==============================================================================
  1100. # • Position.
  1101. #==============================================================================
  1102. Dax.register :position
  1103. class Position
  1104. #----------------------------------------------------------------------------
  1105. # • Modificar a posição de um objeto, que deve de conter as variáveis
  1106. # x, y, width, height.
  1107. # pos : Defina aqui o valor que definirá a posição da escola. Veja abaixo
  1108. # object : Objeto que contenha as variáveis x, y, width, height.
  1109. # os valores.
  1110. # 0 : Ficará no canto esquerdo superior.
  1111. # 1 : Posição X mudará para o centro da tela.
  1112. # 2 : Ficará no canto direito superior.
  1113. # 3 : Ficará no canto esquerdo inferior.
  1114. # 4 : Posição Y mudará para o centro da tela.
  1115. # 5 : Ficará no canto direito inferior.
  1116. # :center : Mudar a posição para o centro da tela.
  1117. # :center_left : Centralizar à esquerda da tela.
  1118. # :center_right : Centralizar à direita da tela.
  1119. # :center_up : Centralizar no centro superior.
  1120. # :center_down : Centralizar no centro inferior.
  1121. #----------------------------------------------------------------------------
  1122. def self.[](pos, object)
  1123. return if object.nil? or pos.nil?
  1124. return object.x, object.y = pos[0], pos[1] if pos.is_a?(Array)
  1125. return object.x, object.y = pos.x, pos.y if pos.is_a?(Position)
  1126. case pos
  1127. when 0 then object.x, object.y = 0, 0
  1128. when 1 then object.x = DMath.get_x_center_screen(object.width)
  1129. when 2 then object.x, object.y = Graphics.width - object.width, 0
  1130. when 3 then object.x, object.y = 0, Graphics.height - object.height
  1131. when 4 then object.y = DMath.get_y_center_screen(object.height)
  1132. when 5 then object.x, object.y = Graphics.width - object.width, Graphics.height - object.height
  1133. when :center
  1134. object.x = (Graphics.width - object.width) / 2
  1135. object.y = (Graphics.height - object.height) / 2
  1136. when :center_left
  1137. object.x = 0
  1138. object.y = (Graphics.height - object.height) / 2
  1139. when :center_right
  1140. object.x = Graphics.width - object.width
  1141. object.y = (Graphics.height - object.height) / 2
  1142. when :center_up
  1143. object.x = (Graphics.width - object.width) / 2
  1144. object.y = 0
  1145. when :center_down
  1146. object.x = (Graphics.width - object.width) / 2
  1147. object.y = Graphics.height - object.height
  1148. end
  1149. end
  1150. #----------------------------------------------------------------------------
  1151. # • Variáveis públicas da instância.
  1152. #----------------------------------------------------------------------------
  1153. attr_accessor :x # Variável que retorna ao valor que indica a posição X.
  1154. attr_accessor :y # Variável que retorna ao valor que indica a posição Y.
  1155. #----------------------------------------------------------------------------
  1156. # • Inicialização dos objetos.
  1157. #----------------------------------------------------------------------------
  1158. def initialize(x, y)
  1159. @x = x || 0
  1160. @y = y || 0
  1161. end
  1162. #----------------------------------------------------------------------------
  1163. # • Somar com outra posição.
  1164. #----------------------------------------------------------------------------
  1165. def +(position)
  1166. position = position.position unless position.is_a?(Position)
  1167. Position.new(self.x + position.x, self.y + position.y)
  1168. end
  1169. #----------------------------------------------------------------------------
  1170. # • Subtrair com outra posição.
  1171. #----------------------------------------------------------------------------
  1172. def -(position)
  1173. position = position.position unless position.is_a?(Position)
  1174. Position.new(self.x - position.x, self.y - position.y)
  1175. end
  1176. #----------------------------------------------------------------------------
  1177. # • Multiplicar com outra posição.
  1178. #----------------------------------------------------------------------------
  1179. def *(position)
  1180. position = position.position unless position.is_a?(Position)
  1181. Position.new(self.x * position.x, self.y * position.y)
  1182. end
  1183. #----------------------------------------------------------------------------
  1184. # • Dividir com outra posição.
  1185. #----------------------------------------------------------------------------
  1186. def /(position)
  1187. position = position.position unless position.is_a?(Position)
  1188. return if (self.x or position.x or self.y or position.y) <= 0
  1189. Position.new(self.x / position.x, self.y / position.y)
  1190. end
  1191. #----------------------------------------------------------------------------
  1192. # • Comparar com outra posição.
  1193. #----------------------------------------------------------------------------
  1194. def ==(position)
  1195. position = position.position unless position.is_a?(Position)
  1196. return self.x == position.x && self.y == position.y
  1197. end
  1198. #----------------------------------------------------------------------------
  1199. # • Distância de um ponto de posição com relação a outro.
  1200. # other : Outro ponto de posição.
  1201. #----------------------------------------------------------------------------
  1202. def distance(other)
  1203. other = other.position unless other.is_a?(Position)
  1204. (self.x - other.x).abs + (self.y - other.y).abs
  1205. end
  1206. #----------------------------------------------------------------------------
  1207. # • Converter em string.
  1208. #----------------------------------------------------------------------------
  1209. def to_s
  1210. return "position x: #{self.x}\nposition y: #{self.y}"
  1211. end
  1212. #----------------------------------------------------------------------------
  1213. # • Converter em array.
  1214. #----------------------------------------------------------------------------
  1215. def to_a
  1216. return [@x, @y]
  1217. end
  1218. #----------------------------------------------------------------------------
  1219. # • Converter em hash.
  1220. #----------------------------------------------------------------------------
  1221. def to_h
  1222. return {x: @x, y: @y}
  1223. end
  1224. #----------------------------------------------------------------------------
  1225. # • Clonar
  1226. #----------------------------------------------------------------------------
  1227. def clone
  1228. return Position.new(@x, @y)
  1229. end
  1230. end
  1231. #==============================================================================
  1232. # • IO
  1233. #==============================================================================
  1234. Dax.register(:io)
  1235. class << IO
  1236. #----------------------------------------------------------------------------
  1237. # • [Array] : Obtêm a largura e a altura da imagem.
  1238. # filename : Nome do arquivo.
  1239. # [Retorna Nil, caso o arquivo não exista]
  1240. #----------------------------------------------------------------------------
  1241. def size_picture(filename)
  1242. return nil unless FileTest.exist?(filename)
  1243. return IO.read(filename, 8, 16).unpack("NN")
  1244. end
  1245. end
  1246. #==============================================================================
  1247. # • File
  1248. #==============================================================================
  1249. Dax.register(:file)
  1250. class << File
  1251. #----------------------------------------------------------------------------
  1252. # • [NilClass] : Executa o script que está no arquivo.
  1253. #----------------------------------------------------------------------------
  1254. def eval(filename)
  1255. return unless filename.match(/.rb|.rvdata2/) or FileTest.exist?(filename)
  1256. script = ""
  1257. nilcommand = false
  1258. IO.readlines(filename).each { |i|
  1259. if i.match(/^=begin/)
  1260. nilcommand = true
  1261. elsif i.match(/^=end/) and nilcommand
  1262. nilcommand = false
  1263. elsif !nilcommand
  1264. script += i.gsub(/#(.*)/, "").to_s + "\n"
  1265. end
  1266. }
  1267. Kernel.eval(script)
  1268. return nil
  1269. end
  1270. end
  1271. #==============================================================================
  1272. # • Dir
  1273. #==============================================================================
  1274. Dax.register(:dir)
  1275. class << Dir
  1276. #----------------------------------------------------------------------------
  1277. # • [NilClass] Cria pasta e subpasta em conjunto.
  1278. # Separe todo com vírgulas. A primeira que você definir será a pasta,
  1279. # o resto será as subpasta.
  1280. # Dir.mksdir("Pasta", "Subpasta1, Subpasta2")
  1281. #----------------------------------------------------------------------------
  1282. def mksdir(dir="", subdir="")
  1283. self.mkdir(dir) unless File.directory?(dir)
  1284. subdir = subdir.split(/,/)
  1285. subdir.each { |data| self.mkdir(dir + "/" + data.strip) unless File.directory?(dir + "/" + data.gsub(" ", "")) }
  1286. return nil
  1287. end
  1288. end
  1289. #==============================================================================
  1290. # * Color
  1291. #==============================================================================
  1292. Dax.register(:color)
  1293. class Color
  1294. #----------------------------------------------------------------------------
  1295. # • [Color] : Permite você modificar a opacidade da cor.
  1296. # Color.new(r, g, b).opacity([alpha])
  1297. # O valor padrão do alpha e 128.. não é preciso espeficar.
  1298. #----------------------------------------------------------------------------
  1299. def opacity(alpha=nil)
  1300. self.set(self.red, self.green, self.blue, alpha || 128)
  1301. end
  1302. #----------------------------------------------------------------------------
  1303. # • [Color] : Inverte as cores.
  1304. # Color.new(r, g, b[, a).invert!
  1305. #----------------------------------------------------------------------------
  1306. def invert!
  1307. self.set(255-self.red, 255-self.green, 255-self.blue, self.alpha)
  1308. end
  1309. #----------------------------------------------------------------------------
  1310. # • [Color] : Reverte as cores.
  1311. # Color.new(r, g, b[, a).revert
  1312. #----------------------------------------------------------------------------
  1313. def revert
  1314. self.set(*[self.red, self.green, self.blue, self.alpha].reverse!)
  1315. end
  1316. #----------------------------------------------------------------------------
  1317. # • [String] : Converte para string as informações dos valores das cores.
  1318. # Color.new(0, 0, 0).to_s
  1319. # red: 0
  1320. # blue: 0
  1321. # green: 0
  1322. # alpha: 255
  1323. #----------------------------------------------------------------------------
  1324. def to_s
  1325. "red: #{self.red}\nblue: #{self.blue}\ngreen: #{self.green}\nalpha: #{self.alpha}"
  1326. end
  1327. #----------------------------------------------------------------------------
  1328. # • [TrueClass/FalseClass] : Comparar cores, retorna a [true] se for igual..
  1329. # retorna a [false] se não for igual.
  1330. #----------------------------------------------------------------------------
  1331. def ==(color)
  1332. return (self.red == color.red and self.green == color.green and self.blue == color.blue and
  1333. self.alpha == color.alpha) ? true : false
  1334. end
  1335. #----------------------------------------------------------------------------
  1336. # • [Hash] : Retorna aos valores das cores em formato de Hash.
  1337. # Color.new(0, 0, 0).to_h
  1338. # {:red => 0, :green => 0, :blue => 0, :alpha => 255}
  1339. #----------------------------------------------------------------------------
  1340. def to_h
  1341. return {
  1342. red: self.red, green: self.green, blue: self.blue, alpha: self.alpha,
  1343. }
  1344. end
  1345. #----------------------------------------------------------------------------
  1346. # • [Array] : Retorna aos valores das cores em formato de Array.
  1347. # includeAlpha : Incluir o valor alpha?
  1348. # Color.new(0, 0, 0).to_a
  1349. # [0, 0, 0, 255]
  1350. #----------------------------------------------------------------------------
  1351. def to_a(includeAlpha=false)
  1352. array = [self.red, self.green, self.blue]
  1353. array += [self.alpha] if includeAlpha
  1354. return array
  1355. end
  1356. #----------------------------------------------------------------------------
  1357. # • [Color] : Dispoem os valores das cores em ordem crescente e cria uma
  1358. # nova cor.
  1359. # includeAlpha : Incluir o valor alpha?
  1360. #----------------------------------------------------------------------------
  1361. def crescent(includeAlpha=false)
  1362. set(*to_a(includeAlpha).crescent)
  1363. end
  1364. #----------------------------------------------------------------------------
  1365. # • [Color] : Dispoem os valores das cores em ordem decrescente e cria uma
  1366. # nova cor.
  1367. # includeAlpha : Incluir o valor alpha?
  1368. #----------------------------------------------------------------------------
  1369. def decrescent(includeAlpha=false)
  1370. set(*to_a(includeAlpha).decrescent)
  1371. end
  1372. #----------------------------------------------------------------------------
  1373. # • [Color] Soma os valores das cores com os valores de outras cores.
  1374. # Ex: color + Color.new(21,54,255)
  1375. #----------------------------------------------------------------------------
  1376. def +(color)
  1377. return unless color.is_a?(Color)
  1378. self.set(
  1379. *color.to_a(false).each_with_index { |i, n| i + to_a[n] }
  1380. )
  1381. end
  1382. #----------------------------------------------------------------------------
  1383. # • [Color] Subtrai os valores das cores com os valores de outras cores.
  1384. # Ex: color - Color.new(21,54,255)
  1385. #----------------------------------------------------------------------------
  1386. def -(color)
  1387. return unless color.is_a?(Color)
  1388. self.set(
  1389. *color.to_a(false).each_with_index { |i, n| i - to_a[n] }
  1390. )
  1391. end
  1392. #----------------------------------------------------------------------------
  1393. # • [Color] Multiplica os valores das cores com os valores de outras cores.
  1394. # Ex: color * Color.new(21,54,255)
  1395. #----------------------------------------------------------------------------
  1396. def *(color)
  1397. return unless color.is_a?(Color)
  1398. self.set(
  1399. *color.to_a(false).each_with_index { |i, n| (i * to_a[n]) / 255.0 }
  1400. )
  1401. end
  1402. #----------------------------------------------------------------------------
  1403. # • [Color] Divide os valores das cores com os valores de outras cores.
  1404. # Ex: color / Color.new(21,54,255)
  1405. #----------------------------------------------------------------------------
  1406. def /(color)
  1407. return unless color.is_a?(Color)
  1408. self.set(
  1409. *color.to_a(false).each_with_index { |i, n| i.zero? ? 0 : to_a[n] / i }
  1410. )
  1411. end
  1412. #----------------------------------------------------------------------------
  1413. # • [Color] : Aumentar/Diminuir as cores em porcento.
  1414. # value : Valor da porcentagem. Vai de 0~100
  1415. # includeAlpha : Incluir o valor alpha?
  1416. #----------------------------------------------------------------------------
  1417. def percent(value, includeAlpha=true)
  1418. value = DMath.clamp(value, 0, 100)
  1419. Color.new(
  1420. *to_a(includeAlpha).collect! { |i| i.to_p(value * 2.55, 255) }
  1421. )
  1422. end
  1423. #----------------------------------------------------------------------------
  1424. # • [Numeric] : Retorna a lumonisidade das cores.
  1425. #----------------------------------------------------------------------------
  1426. def luminosity
  1427. return to_a(false).each_with_index { |i, n| i * [0.21, 0.71, 0.07][n] }.alln?
  1428. end
  1429. #----------------------------------------------------------------------------
  1430. # • [Numeric] : Retorna a media entre os valores(canais).
  1431. # includeAlpha : Incluir o valor alpha?
  1432. #----------------------------------------------------------------------------
  1433. def avarange(includeAlpha=true)
  1434. n = includeAlpha ? 4 : 3
  1435. return to_a(includeAlpha).alln? / n
  1436. end
  1437. #----------------------------------------------------------------------------
  1438. # • [Numeric] : Retorna ao valor mais alto que tiver, dentre os valores
  1439. # especificados das cores.
  1440. #----------------------------------------------------------------------------
  1441. def max
  1442. [red, green, blue].max
  1443. end
  1444. #----------------------------------------------------------------------------
  1445. # • [Numeric] : Retorna ao valor menor que tiver, dentre os valores
  1446. # especificados das cores.
  1447. #----------------------------------------------------------------------------
  1448. def min
  1449. [red, green, blue].min
  1450. end
  1451. #----------------------------------------------------------------------------
  1452. # • [Color] : Define uma cor aleatória:
  1453. # Exemplo: Color.new.random
  1454. #----------------------------------------------------------------------------
  1455. def random
  1456. self.set(rand(256), rand(256), rand(256))
  1457. end
  1458. #----------------------------------------------------------------------------
  1459. # • [Color] : Define uma cor em hexadécimal.
  1460. # Exemplo : Color.new.hex("ffffff")
  1461. #----------------------------------------------------------------------------
  1462. def hex(string)
  1463. self.set(*string.scan(/../).map { |color| color.to_i(16)})
  1464. end
  1465. #----------------------------------------------------------------------------
  1466. # • [Color] : Retorna a cor padrão.
  1467. # Exemplo : Color.new.default
  1468. #----------------------------------------------------------------------------
  1469. def default
  1470. self.hex("ffffff")
  1471. end
  1472. end
  1473. #==============================================================================
  1474. # • Rect
  1475. #==============================================================================
  1476. Dax.register(:rect)
  1477. class Rect
  1478. #----------------------------------------------------------------------------
  1479. # • [TrueClass/FalseClass] : Verificar se algo está na área.
  1480. #----------------------------------------------------------------------------
  1481. def in?(x, y)
  1482. x.between?(self.x, self.x + self.width) &&
  1483. y.between?(self.y, self.y + self.height)
  1484. end
  1485. #----------------------------------------------------------------------------
  1486. # • [NilClass] : Cada elemento em um bloco.
  1487. # rect.each { |x, y, w, h| }
  1488. #----------------------------------------------------------------------------
  1489. def each
  1490. yield(self.x, self.y, self.width, self.height)
  1491. return nil
  1492. end
  1493. #----------------------------------------------------------------------------
  1494. # • [NilClass] : Retorna a cada parte do rect definida por ti, ponto-a-ponto.
  1495. # p : Ponto A.
  1496. # q : Ponto B.
  1497. # Rect.new(0, 0, 1, 1).step(1.0, 1.0) { |i, j| p [i, j] }
  1498. # [0.0, 0.0]
  1499. # [0.0, 1.0]
  1500. # [1.0, 0.0]
  1501. # [1.0, 1.0]
  1502. #----------------------------------------------------------------------------
  1503. def step(p=1, q=1)
  1504. (self.x..(self.x + self.width)).step(p) { |i|
  1505. (self.y..(self.y + self.height)).step(q) { |j|
  1506. yield(i, j)
  1507. }
  1508. }
  1509. return nil
  1510. end
  1511. end
  1512. #==============================================================================
  1513. # • DMath
  1514. #==============================================================================
  1515. Dax.register(:dmath, 'Dax', 1.5, '04/05/13')
  1516. module DMath
  1517. extend self
  1518. #----------------------------------------------------------------------------
  1519. # • Constantes para fórmula de dano.
  1520. #----------------------------------------------------------------------------
  1521. MAX_VALUE_PARAM = 256
  1522. MAX_VALUE_PARAM_AXE = 128
  1523. MAX_VALUE_PARAM_DAGGER = 218
  1524. MAX_VALUE_PARAM_GUN = 99
  1525. MAX_VALUE_MAGIC = 218
  1526. #----------------------------------------------------------------------------
  1527. # • [Float] : Cálcula a raíz quadrada que qualquer grau.
  1528. # n : Número que será calculado.
  1529. # g : Grau da raíz.
  1530. # Dmath.sqrt(27, 3) # Cálculo da raíz cúbica de 27 => 3.0
  1531. #----------------------------------------------------------------------------
  1532. def sqrt(n, g)
  1533. raise(ArgumentError) if n < 0 && n.is_evan?
  1534. x, count, num = 1.0, 0.0, 0.0
  1535. while
  1536. num = x - ( ( x ** g - n ) / ( g * ( x ** g.pred ) ) )
  1537. (x == num) || (count > 20) ? break : eval("x = num; count += 1")
  1538. end
  1539. return num
  1540. end
  1541. #----------------------------------------------------------------------------
  1542. # • [Numeric] : Clamp | Delimitar o inteiro
  1543. # num : Número.
  1544. # low : Número minímo. Sê o 'num' for menor que min retorna a low.
  1545. # high : Número máximo. Sê o 'num' for maior que hight retorna a high, caso
  1546. # não retorna ao próprio número(num).
  1547. #----------------------------------------------------------------------------
  1548. def clamp(num, low, high)
  1549. num, low, high = num.to_i, low.to_i, high.to_i
  1550. num = num < low ? low : num > high ? high : num
  1551. num
  1552. end
  1553. #----------------------------------------------------------------------------
  1554. # • [Array] : Centralizar um objeto n'outro.
  1555. # object : Objeto, tem que ser do tipo [Sprite] ou [Window_Base]
  1556. # object_for_centralize : Objeto que irá se centralizar no 'object', tem
  1557. # que ser do tipo [Sprite] ou [Window_Base]
  1558. # * Retorna a uma Array contendo as informações das novas posições em X e Y.
  1559. #----------------------------------------------------------------------------
  1560. def centralize_object(object, object_for_centralize)
  1561. x = object.x + (object.width - object_for_centralize.width) / 2
  1562. y = object.y + (object.height - object_for_centralize.height) / 2
  1563. return x, y
  1564. end
  1565. #----------------------------------------------------------------------------
  1566. # • [Numeric] : Centralizar um objeto n'outro, obtendo somente a posição X.
  1567. # objectx : Valor da posição X do objeto número 1.
  1568. # objectwidth : Valor da largura do objeto número 1.
  1569. # object_for_centralizewidth : Valor da largura do objeto que irá se
  1570. # centralizar no objeto número 1.
  1571. # * Retorna ao valor da posição X.
  1572. #----------------------------------------------------------------------------
  1573. def centralize_x(objectx, objectwidth, object_for_centralizewidth)
  1574. return objectx + (objectwidth - object_for_centralizewidth) / 2
  1575. end
  1576. #----------------------------------------------------------------------------
  1577. # • [Numeric] : Centralizar um objeto n'outro, obtendo somente a posição Y.
  1578. # objecty : Valor da posição Y do objeto número 1.
  1579. # objectheight : Valor da altura do objeto número 1.
  1580. # object_for_centralizeheight : Valor da altura do objeto que irá se
  1581. # centralizar no objeto número 1.
  1582. # * Retorna ao valor da posição Y.
  1583. #----------------------------------------------------------------------------
  1584. def centralize_y(objecty, objectheight, object_for_centralizeheight)
  1585. return objecty + (objectheight - object_for_centralizeheight) / 2
  1586. end
  1587. #----------------------------------------------------------------------------
  1588. # • [Numeric] : Obter a posição X do centro da tela referente a largura do objeto X.
  1589. # Exemplo: get_x_center_screen(sprite.width) : Irá retornar ao valor da posição
  1590. # X para que o objeto fique no centro da tela.
  1591. # Exemplo: sprite.x = get_x_center_screen(sprite.width)
  1592. #----------------------------------------------------------------------------
  1593. def get_x_center_screen(width)
  1594. return (Graphics.width - width) / 2
  1595. end
  1596. #----------------------------------------------------------------------------
  1597. # • [Numeric] : Obter a posição Y do centro da tela referente a altura do objeto X.
  1598. # Exemplo: get_y_center_screen(sprite.height) : Irá retornar ao valor da posição
  1599. # Y para que o objeto fique no centro da tela.
  1600. # Exemplo: sprite.y = get_y_center_screen(sprite.height)
  1601. #----------------------------------------------------------------------------
  1602. def get_y_center_screen(height)
  1603. return (Graphics.height - height) / 2
  1604. end
  1605. #--------------------------------------------------------------------------
  1606. # • [TrueClass/FalseClass] : Verifica se um objeto está na área de um círculo.
  1607. # object : Objeto do tipo da classe [Sprite].
  1608. # object2 : Objeto do tipo da classe [Sprite].
  1609. # size : Tamanho geral do círculo.
  1610. #--------------------------------------------------------------------------
  1611. def circle(object, object2, size)
  1612. ( (object.x - object2.x) ** 2) + ( (object.y - object2.y) ** 2) <= (size ** 2)
  1613. end
  1614. #----------------------------------------------------------------------------
  1615. # • [Numeric] : Converter o valor em graus.
  1616. #----------------------------------------------------------------------------
  1617. def graus
  1618. 360 / (2 * Math::PI)
  1619. end
  1620. #----------------------------------------------------------------------------
  1621. # • [Numeric] : Converte o valor em radiano.
  1622. #----------------------------------------------------------------------------
  1623. def radian(degree)
  1624. return (degree.to_f/180) * Math::PI
  1625. end
  1626. #----------------------------------------------------------------------------
  1627. # • [Numeric] : Converte o valor em grau.
  1628. #----------------------------------------------------------------------------
  1629. def degree(radian)
  1630. return (radian.to_f/Math::PI) * 180
  1631. end
  1632. #----------------------------------------------------------------------------
  1633. # • [Numeric] : Retorna pra base de 4 decimais.
  1634. #----------------------------------------------------------------------------
  1635. def to_4_dec(n)
  1636. ((n * 1000).ceil) / 1000
  1637. end
  1638. #----------------------------------------------------------------------------
  1639. # • [Numeric] : Retorna a área do triângulo.
  1640. # x : x : Posição x do ponto 1
  1641. # y : Posição y do ponto 1
  1642. # x2 : Posição x do ponto 2
  1643. # y2 : Posição y do ponto 2
  1644. # x3 : Posição x do ponto 3
  1645. # y3 : Posição y do ponto 3
  1646. #----------------------------------------------------------------------------
  1647. def triangle_area(*args)
  1648. x, y, x2, y2, x3, y3 = *args
  1649. return (x2 - x) * (y3 - y) - (x3 - x) * (y2 - y)
  1650. end
  1651. #----------------------------------------------------------------------------
  1652. # • [Numeric] : Método para calcular a distância de um objeto para com outro.
  1653. #----------------------------------------------------------------------------
  1654. def distance_sensor(target, target2)
  1655. return (target.x - target2.x).abs + (target.y - target2.y).abs
  1656. end
  1657. #----------------------------------------------------------------------------
  1658. # • [Integer] : Método euclidiano para mediar a distância de um ponto
  1659. # para outro ponto. Primeira dimensão.
  1660. # p : Ponto A. [x, y]
  1661. # q : Ponto B. [x, y]
  1662. # euclidean_distance_1d(5, 1) #4
  1663. #----------------------------------------------------------------------------
  1664. def euclidean_distance_1d(p, q)
  1665. return sqrt( (p - q) ** 2, 2 ).floor
  1666. end
  1667. #----------------------------------------------------------------------------
  1668. # • [Integer] : Método euclidiano para mediar a distância de um ponto
  1669. # para outro ponto. Segunda dimensão.
  1670. # p : Ponto A. [x, y]
  1671. # q : Ponto B. [x, y]
  1672. # euclidean_distance_2d([1, 3], [1, 5]) #2
  1673. #----------------------------------------------------------------------------
  1674. def euclidean_distance_2d(p, q)
  1675. p = p.position unless p.is_a?(Position)
  1676. q = q.position unless q.is_a?(Position)
  1677. return sqrt( ((p.x - q.x) ** 2) + ((p.y - q.y) ** 2), 2 ).floor
  1678. end
  1679. #----------------------------------------------------------------------------
  1680. # • [Numeric] : Dentro do círculo.
  1681. #----------------------------------------------------------------------------
  1682. def circle_in(t, b, c, d)
  1683. return -c * (Math.sqrt(1 - (t /= d.to_f) * t) - 1) + b
  1684. end
  1685. #----------------------------------------------------------------------------
  1686. # • [Numeric] : Fora do círculo
  1687. #----------------------------------------------------------------------------
  1688. def circle_out(t, b, c, d)
  1689. return c * Math.sqrt(1 - (t=t/d.to_f-1)*t) + b
  1690. end
  1691. #----------------------------------------------------------------------------
  1692. # • [Numeric] : Retorna ao valor minímo, do valor máximo de min & v, com o
  1693. # valor de max.
  1694. #----------------------------------------------------------------------------
  1695. def force_range(v, min, max)
  1696. [[min, v].max, max].min
  1697. end
  1698. #----------------------------------------------------------------------------
  1699. # • Cálculo de variação para o dano. Para equilibrar.
  1700. #----------------------------------------------------------------------------
  1701. def random
  1702. (1 + 2.aleatory) ** 0.125
  1703. end
  1704. #----------------------------------------------------------------------------
  1705. # • Resultado final.
  1706. #----------------------------------------------------------------------------
  1707. def lastResult(x)
  1708. return x <= 0 ? 0 : x.round
  1709. end
  1710. #----------------------------------------------------------------------------
  1711. # • [Formula de dano] : Espadas(1 & 2 mão), lanças, bestas, cajado.
  1712. #----------------------------------------------------------------------------
  1713. def sword(attack, strength, defense, level)
  1714. str = strength.randomic
  1715. return lastResult((attack.randomic * random - defense.randomic) * (1 + str * (level + str) / MAX_VALUE_PARAM))
  1716. end
  1717. #----------------------------------------------------------------------------
  1718. # • [Formula de dano] : Desarmado.
  1719. #----------------------------------------------------------------------------
  1720. def unarmed(strength, defense, level)
  1721. str = strength.randomic
  1722. lastResult((11 * random - defense.randomic) * str * (level + str) / MAX_VALUE_PARAM)
  1723. end
  1724. #----------------------------------------------------------------------------
  1725. # • [Formula de dano] : Desarmado com luva.
  1726. #----------------------------------------------------------------------------
  1727. def unarmed_brawler(strength, defense, level)
  1728. str = strength.randomic
  1729. lastResult(((level + str) / 2 * random - defense.randomic) * str * (level + str) / MAX_VALUE_PARAM)
  1730. end
  1731. #----------------------------------------------------------------------------
  1732. # • [Formula de dano] : Cajado de mágia.
  1733. #----------------------------------------------------------------------------
  1734. def pole(attack, strength, defense, level, magicDefense)
  1735. str = strength.randomic
  1736. lastResult((attack.randomic * random - magicDefense.randomic) * (1 + str * (level + str))/ MAX_VALUE_PARAM)
  1737. end
  1738. #----------------------------------------------------------------------------
  1739. # • [Formula de dano] : Maças..
  1740. #----------------------------------------------------------------------------
  1741. def mace(attack, defense, magic, level)
  1742. mag = magic.randomic
  1743. lastResult((attack.randomic * random - defense.randomic) * (1 + mag * (level + mag)) / MAX_VALUE_PARAM)
  1744. end
  1745. #----------------------------------------------------------------------------
  1746. # • [Formula de dano] : Katanas, staves..
  1747. #----------------------------------------------------------------------------
  1748. def katana(attack, defense, strength, magic, level)
  1749. lastResult((attack.randomic * random - defense.randomic) * (1 + strength.randomic * (level + magic.randomic) / MAX_VALUE_PARAM))
  1750. end
  1751. #----------------------------------------------------------------------------
  1752. # • [Formula de dano] : Machados, marretas..
  1753. #----------------------------------------------------------------------------
  1754. def axe(attack, strength, defense, level, vitality)
  1755. lastResult((attack.randomic * random - defense.randomic) * (1 + strength.randomic * (level+vitality.randomic)/MAX_VALUE_PARAM_AXE))
  1756. end
  1757. #----------------------------------------------------------------------------
  1758. # • [Formula de dano] : Adagas, espadas ninjas e arco..
  1759. #----------------------------------------------------------------------------
  1760. def dagger(attack, defense, strength, level, speed)
  1761. lastResult ((attack.randomic * random) - defense.randomic) * (1 + strength.randomic * (level + speed.randomic) / 218)
  1762. end
  1763. #----------------------------------------------------------------------------
  1764. # • [Formula de dano] : Revolvers
  1765. #----------------------------------------------------------------------------
  1766. def gun(attack,defense,strength, level)
  1767. str = strength.randomic
  1768. lastResult ( (((attack.randomic * random) - defense.randomic) ** 2) / 64 ) * (1 + str * (level + str) / MAX_VALUE_PARAM_GUN)
  1769. end
  1770. #----------------------------------------------------------------------------
  1771. # • [Formula de dano] : Mágicas de ataques.
  1772. #----------------------------------------------------------------------------
  1773. def magicAttack(magicDefense, level, magicAttack, attackMagic)
  1774. mag = magicAttack.randomic
  1775. lastResult ( (attackMagic.randomic * random) - magicDefense.randomic ) * (2 + mag.randomic * (level + mag) / MAX_VALUE_MAGIC)
  1776. end
  1777. #----------------------------------------------------------------------------
  1778. # • [Formula de dano] : Mágicas de cura;
  1779. #----------------------------------------------------------------------------
  1780. def magicHeal(strengthMagic, magicAttack, level)
  1781. mag = magicAttack.randomic
  1782. lastResult (strengthMagic * random) * (2 + mag * (level + mag) / MAX_VALUE_MAGIC)
  1783. end
  1784. #----------------------------------------------------------------------------
  1785. # • [Formula de EXP] : Gerador de curva de exp.
  1786. # minlv : Level minimo.
  1787. # maxlv : Level máximo.
  1788. # stvalue : Valor inicial.
  1789. # infl : Inflação.
  1790. #----------------------------------------------------------------------------
  1791. def generate_curve_exp(minlv, maxlv, stvalue, infl)
  1792. table = []
  1793. (minlv..maxlv).each { |i| table[i] = (stvalue + (infl + (Random.new.rand(infl..(infl+i)).to_i % i )) * i).to_i.round}
  1794. table
  1795. end
  1796. end
  1797. #==============================================================================
  1798. # • Keyboard | Método para usar todas as teclas do teclado.
  1799. #==============================================================================
  1800. Dax.register(:key, "Dax", 2.0)
  1801. module Key
  1802. #----------------------------------------------------------------------------
  1803. # • Extensão & Variáveis da instância do módulo.
  1804. #----------------------------------------------------------------------------
  1805. extend self
  1806. attr_accessor :_cacheText # Armazena os textos.
  1807. #----------------------------------------------------------------------------
  1808. # • Chaves.
  1809. #----------------------------------------------------------------------------
  1810. KEY = {
  1811. # Chaves diversas.
  1812. CANCEL: 0x03, BACKSPACE: 0x08, TAB: 0x09, CLEAR: 0x0C,
  1813. ENTER: 0x0D, SHIFT: 0x10, CONTROL: 0x11, MENU: 0x12,
  1814. PAUSE: 0x13, ESC: 0x1B, CONVERT: 0x1C, NONCONVERT: 0x1D,
  1815. ACCEPT: 0x1E, SPACE: 0x20, PRIOR: 0x21, NEXT: 0x22,
  1816. ENDS: 0x23, HOME: 0x24, LEFT: 0x25, UP: 0x26, RIGHT: 0x27,
  1817. DOWN: 0x28, SELECT: 0x29, PRINT: 0x2A, EXECUTE: 0x2B,
  1818. SNAPSHOT: 0x2C, DELETE: 0x2E, HELP: 0x2F, LSHIFT: 0xA0, RSHIFT: 0xA1,
  1819. LCONTROL: 0xA2, RCONTROL: 0xA3, LALT: 0xA4, RALT: 0xA5, PACKET: 0xE7,
  1820. MOUSE_RIGHT: 0x01, MOUSE_LEFT: 0x02, MOUSE_MIDDLE: 0x04,
  1821. # Chaves de números.
  1822. N0: 0x30, N1: 0x31, N2: 0x32, N3: 0x33, N4: 0x34, N5: 0x35, N6: 0x36,
  1823. N7: 0x37, N8: 0x38, N9: 0x39,
  1824. # Chaves de letras.
  1825. A: 0x41, B: 0x42, C: 0x43, D: 0x44, E: 0x45,
  1826. F: 0x46, G: 0x47, H: 0x48, I: 0x49, J: 0x4A,
  1827. K: 0x4B, L: 0x4C, M: 0x4D, N: 0x4E, O: 0x4F,
  1828. P: 0x50, Q: 0x51, R: 0x52, S: 0x53, T: 0x54,
  1829. U: 0x55, V: 0x56, W: 0x57, X: 0x58, Y: 0x59,
  1830. Z: 0x5A, Ç: 0xBA,
  1831. # Chaves do window.
  1832. LWIN: 0x5B, RWIN: 0x5C, APPS: 0x5D, SLEEP: 0x5F, BROWSER_BACK: 0xA6,
  1833. BROWSER_FORWARD: 0xA7, BROWSER_REFRESH: 0xA8, BROWSER_STOP: 0xA9,
  1834. BROWSER_SEARCH: 0xAA, BROWSER_FAVORITES: 0xAB, BROWSER_HOME: 0xAC,
  1835. VOLUME_MUTE: 0xAD, VOLUME_DOWN: 0xAE, VOLUME_UP: 0xAF,
  1836. MEDIA_NEXT_TRACK: 0xB0, MEDIA_PREV_TRACK: 0xB1, MEDIA_STOP: 0xB2,
  1837. MEDIA_PLAY_PAUSE: 0xB3, LAUNCH_MAIL: 0xB4, LAUNCH_MEDIA_SELECT: 0xB5,
  1838. LAUNCH_APP1: 0xB6, LAUNCH_APP2: 0xB7, PROCESSKEY: 0xE5, ATIN: 0xF6,
  1839. CRSEL: 0xF7, EXSEL: 0xF8, EREOF: 0xF9, PLAY: 0xFA, ZOOM: 0xFB,
  1840. PA1: 0xFD,
  1841. # Chaves do NUMPAD
  1842. NUMPAD0: 0x60, NUMPAD1: 0x61, NUMPAD2: 0x62,
  1843. NUMPAD3: 0x63, NUMPAD4: 0x64, NUMPAD5: 0x65,
  1844. NUMPAD6: 0x66, NUMPAD7: 0x67, NUMPAD8: 0x68, NUMPAD9: 0x69,
  1845. MULTIPLY: 0x6A, ADD: 0x6B, SEPARATOR: 0x6C,
  1846. SUBTRACT: 0x6D, DECIMAL: 0x6E, DIVIDE: 0x6F,
  1847. # Caches de função.
  1848. F1: 0x70, F2: 0x71, F3: 0x72, F4: 0x73, F5: 0x74, F6: 0x75,
  1849. F7: 0x76, F8: 0x77, F9: 0x78, F10: 0x79, F11: 0x7A, F12: 0x7B,
  1850. F13: 0x7C, F14: 0x7D, F15: 0x7E, F16: 0x7F, F17: 0x80, F18: 0x81,
  1851. F19: 0x82, F20: 0x83, F21: 0x84, F22: 0x85, F23: 0x86, F24: 0x87,
  1852. # Chaves alternativas.
  1853. CAPS: 0x14, INSERT: 0x2D, NUMLOCK: 0x90, SCROLL: 0x91,
  1854. # Chaves OEM, variadas.
  1855. OEM_1: 0xC1, OEM_PLUS: 0xBB, OEM_COMMA: 0xBC,
  1856. OEM_MINUS: 0xBD, OEM_PERIOD: 0xBE,
  1857. OEM_2: 0xBF, QUOTE: 0xC0,
  1858. ACCUTE: 0xDB, OEM_6: 0xDD, OEM_7: 0xDC, TIL: 0xDE,
  1859. OEM_102: 0xE2, OEM_CLEAR: 0xFE,
  1860. }
  1861. #----------------------------------------------------------------------------
  1862. # • Chave dos números. (Símbolos)
  1863. #----------------------------------------------------------------------------
  1864. KEY_NUMBER = %W(NUMPAD0 NUMPAD1 NUMPAD2 NUMPAD3 NUMPAD4 NUMPAD5 NUMPAD6
  1865. NUMPAD7 NUMPAD8 NUMPAD9 N0 N1 N2 N3 N4 N5 N6 N7 N8 N9 MULTIPLY OEM_PERIOD
  1866. OEM_COMMA ADD SEPARATOR DIVIDE SUBTRACT DECIMAL).collect!(&:intern)
  1867. SPECIAL_CHAR_NUMBER = {
  1868. N1: %w(! ¹), N2: %w(@ ²), N3: %w(# ³), N4: %w($ £),
  1869. N5: %w(% ¢), N6: %w(¨ ¬), N7: %w(&), N8: %w(*),
  1870. N9: ["("], N0: [")"], OEM_PERIOD: %w(>), OEM_COMMA: %w(<)
  1871. }
  1872. #----------------------------------------------------------------------------
  1873. # • Chave das letras. (Símbolos)
  1874. #----------------------------------------------------------------------------
  1875. KEY_CHAR = %W(A B C D E F G H I J L K M N O P Q R S T U V W X Y Z Ç).collect!(&:intern)
  1876. KEY_CHAR_ACCUTE = %W(A E I O U Y).collect!(&:intern)
  1877. KEY_CHAR_ACCUTE_STR = {
  1878. UPCASE: {
  1879. A: %w(Â Ã À Á), E: %w(Ê ~E È É), I: %w(Î ~I Ì Í), O: %w(Ô Õ Ò Ó),
  1880. Y: %w(^Y ~Y `Y Ý), U: %w(Û ~U Ù Ú)
  1881. },
  1882. DOWNCASE: {
  1883. A: %w(â ã à á), E: %w(ê ~e è é), I: %w(î ~i ì í), O: %w(ô õ ò ó),
  1884. Y: %w(^y ~y `y ý), U: %w(û ~u ù ú)
  1885. }
  1886. }
  1887. #----------------------------------------------------------------------------
  1888. # • Chaves especiais.
  1889. #----------------------------------------------------------------------------
  1890. KEY_SPECIAL = %w(SPACE OEM_1 OEM_PLUS OEM_MINUS OEM_2
  1891. OEM_6 OEM_7 OEM_102).collect!(&:intern)
  1892. SKEY_SPECIAL = {
  1893. OEM_1: %w(? °), OEM_2: %w(:), OEM_7: %w(} º), OEM_6: %w({ ª),
  1894. OEM_PLUS: %w(+ §), OEM_MINUS: %w(_), OEM_102: %w(|)
  1895. }
  1896. #----------------------------------------------------------------------------
  1897. # • Chaves especiais. [^~ ´` '"]
  1898. #----------------------------------------------------------------------------
  1899. KEY_SPECIAL2 = %w(ACCUTE TIL QUOTE N6).collect!(&:intern)
  1900. #----------------------------------------------------------------------------
  1901. # • Variáveis do módulo.
  1902. #----------------------------------------------------------------------------
  1903. @_cacheText = ""
  1904. @til = 0
  1905. @tils = false
  1906. @accute = 0
  1907. @accutes = false
  1908. @unpack_string = 'b'*256
  1909. @last_array = '0'*256
  1910. @press = Array.new(256, false)
  1911. @trigger = Array.new(256, false)
  1912. @repeat = Array.new(256, false)
  1913. @release = Array.new(256, false)
  1914. @repeat_counter = Array.new(256, 0)
  1915. @getKeyboardState = API::GetKeyboardState
  1916. @getAsyncKeyState = API::GetAsyncKeyState
  1917. @getKeyboardState.call(@last_array)
  1918. @last_array = @last_array.unpack(@unpack_string)
  1919. for i in 0...@last_array.size
  1920. @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
  1921. end
  1922. #----------------------------------------------------------------------------
  1923. # • Atualização.
  1924. #----------------------------------------------------------------------------
  1925. def update
  1926. @trigger = Array.new(256, false)
  1927. @repeat = Array.new(256, false)
  1928. @release = Array.new(256, false)
  1929. array = '0'*256
  1930. @getKeyboardState.call(array)
  1931. array = array.unpack(@unpack_string)
  1932. for i in 0...array.size
  1933. if array[i] != @last_array[i]
  1934. @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
  1935. if @repeat_counter[i] <= 0 && @press[i]
  1936. @repeat[i] = true
  1937. @repeat_counter[i] = 15
  1938. end
  1939. if !@press[i]
  1940. @release[i] = true
  1941. else
  1942. @trigger[i] = true
  1943. end
  1944. else
  1945. if @press[i] == true
  1946. @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
  1947. @release[i] = true if !@press[i]
  1948. end
  1949. if @repeat_counter[i] > 0 && @press[i] == true
  1950. @repeat_counter[i] -= 1
  1951. elsif @repeat_counter[i] <= 0 && @press[i] == true
  1952. @repeat[i] = true
  1953. @repeat_counter[i] = 3
  1954. elsif @repeat_counter[i] != 0
  1955. @repeat_counter[i] = 0
  1956. end
  1957. end
  1958. end
  1959. @last_array = array
  1960. end
  1961. #--------------------------------------------------------------------------
  1962. # * [TrueClass/FalseClass] Obter o estado quando a chave for pressionada.
  1963. # key : key index
  1964. #--------------------------------------------------------------------------
  1965. def press?(key)
  1966. return @press[ key.is_a?(Symbol) ? KEY.get(key) : key ]
  1967. end
  1968. #--------------------------------------------------------------------------
  1969. # * [TrueClass/FalseClass] Obter o estado quando a chave for teclada.
  1970. # key : key index
  1971. #--------------------------------------------------------------------------
  1972. def trigger?(key)
  1973. return @trigger[ key.is_a?(Symbol) ? KEY.get(key) : key ]
  1974. end
  1975. #--------------------------------------------------------------------------
  1976. # * [TrueClass/FalseClass] Obter o estado quando a chave for teclada repetidamente.
  1977. # key : key index
  1978. #--------------------------------------------------------------------------
  1979. def repeat?(key)
  1980. return @repeat[ key.is_a?(Symbol) ? KEY.get(key) : key ]
  1981. end
  1982. #--------------------------------------------------------------------------
  1983. # * [TrueClass/FalseClass] Obter o estado quando a chave for "lançada"
  1984. # key : key index
  1985. #--------------------------------------------------------------------------
  1986. def release?(key)
  1987. return @release[ key.is_a?(Symbol) ? KEY.get(key) : key ]
  1988. end
  1989. #----------------------------------------------------------------------------
  1990. # • [String] Obtêm a string correspondente à tecla do número. Às Strings ficará
  1991. # armazenada na varíavel _cacheText
  1992. #----------------------------------------------------------------------------
  1993. def get_number(special=false)
  1994. KEY_NUMBER.each { |key|
  1995. unless special
  1996. next @_cacheText.concat(API::MapVirtualKey.call(KEY.get(key), 2)) if trigger?(key)
  1997. else
  1998. if shift?
  1999. next @_cacheText += SPECIAL_CHAR_NUMBER[key][0] || "" if trigger?(key)
  2000. elsif ctrl_alt?
  2001. next @_cacheText += SPECIAL_CHAR_NUMBER[key][1] || "" if trigger?(key)
  2002. else
  2003. next @_cacheText.concat(API::MapVirtualKey.call(KEY.get(key), 2)) if trigger?(key)
  2004. end
  2005. end
  2006. }
  2007. end
  2008. #----------------------------------------------------------------------------
  2009. # • [String] Obtêm a string correspondente à tecla do teclado pressionado.
  2010. # Às Strings ficará armazenada na varíavel _cacheText
  2011. #----------------------------------------------------------------------------
  2012. def get_string(backslash=:trigger)
  2013. get_number(true)
  2014. KEY_CHAR.each { |key|
  2015. next unless trigger?(key)
  2016. x = "".concat(API::MapVirtualKey.call(KEY.get(key), 2))
  2017. if @tils
  2018. n = shift? ? 0 : 1 if @tils
  2019. x = KEY_CHAR_ACCUTE_STR[caps? ? :UPCASE : :DOWNCASE][key][n] || "" if KEY_CHAR_ACCUTE.include?(key) and !n.nil?
  2020. @tils = false
  2021. @accutes = false
  2022. elsif @accutes
  2023. n = shift? ? 2 : 3 if @accutes
  2024. x = KEY_CHAR_ACCUTE_STR[caps? ? :UPCASE : :DOWNCASE][key][n] || "" if KEY_CHAR_ACCUTE.include?(key) and !n.nil?
  2025. @tils = false
  2026. @accutes = false
  2027. end
  2028. @_cacheText += (caps? ? x : x.downcase)
  2029. }
  2030. KEY_SPECIAL.each { |key|
  2031. if shift?
  2032. next @_cacheText += SKEY_SPECIAL[key][0] || "" if trigger?(key)
  2033. elsif ctrl_alt?
  2034. next @_cacheText += SKEY_SPECIAL[key][1] || "" if trigger?(key)
  2035. else
  2036. next @_cacheText.concat(API::MapVirtualKey.call(KEY.get(key), 2)) if trigger?(key)
  2037. end
  2038. }
  2039. KEY_SPECIAL2.each { |key|
  2040. if trigger?(key)
  2041. if key == :TIL
  2042. @tils = !@tils
  2043. @accutes = false if @tils
  2044. elsif key == :ACCUTE
  2045. @accutes = !@accutes
  2046. @tils = false if @accutes
  2047. end
  2048. @til = @til == 3 ? @til : @til + 1 if key == :TIL
  2049. @accute = @accute == 3 ? @accute : @accute + 1 if key == :ACCUTE
  2050. if shift?
  2051. next @_cacheText += '"' if key == :QUOTE
  2052. next unless @til == 3 or @accute == 3
  2053. @_cacheText += "^" if key == :TIL
  2054. @_cacheText += "`" if key == :ACCUTE
  2055. next @til = 0 if key == :TIL
  2056. next @accute = 0 if key == :ACCUTE
  2057. else
  2058. next @_cacheText.concat(API::MapVirtualKey.call(KEY.get(key), 2)) if key == :QUOTE
  2059. next unless @til == 3 or @accute == 3
  2060. @_cacheText += "~" if key == :TIL
  2061. @_cacheText += "´" if key == :ACCUTE
  2062. next @til = 0 if key == :TIL
  2063. next @accute = 0 if key == :ACCUTE
  2064. end
  2065. end
  2066. }
  2067. if backslash == :press
  2068. @_cacheText = @_cacheText.backslash if press?(:BACKSPACE)
  2069. else
  2070. @_cacheText = @_cacheText.backslash if trigger?(:BACKSPACE)
  2071. end
  2072. @_cacheText += " " * 4 if trigger?(:TAB)
  2073. end
  2074. #----------------------------------------------------------------------------
  2075. # • Verificar se o CAPS LOCK está ativado ou desativado.
  2076. #----------------------------------------------------------------------------
  2077. def caps?
  2078. API.get_caps_lock
  2079. end
  2080. #----------------------------------------------------------------------------
  2081. # • Verificar se o Shift está pressionado
  2082. #----------------------------------------------------------------------------
  2083. def shift?
  2084. press?(:SHIFT)
  2085. end
  2086. #----------------------------------------------------------------------------
  2087. # • Verificar se o CTRL + ALT está pressionado.
  2088. #----------------------------------------------------------------------------
  2089. def ctrl_alt?
  2090. (press?(:LCONTROL) and press?(:LALT)) or press?(:RALT)
  2091. end
  2092. #----------------------------------------------------------------------------
  2093. # • [Boolean] : Retorna true caso alguma tecla foi teclada.
  2094. #----------------------------------------------------------------------------
  2095. def any?
  2096. Key::KEY.each_value { |i|
  2097. next if i == 25
  2098. return true if trigger?(i)
  2099. }
  2100. return false
  2101. end
  2102. #----------------------------------------------------------------------------
  2103. # • Para movimento WSAD
  2104. #----------------------------------------------------------------------------
  2105. def wsad
  2106. return 8 if press?(:W)
  2107. return 4 if press?(:A)
  2108. return 6 if press?(:D)
  2109. return 2 if press?(:S)
  2110. return 0
  2111. end
  2112. end
  2113. #==============================================================================
  2114. # • Sprite
  2115. #==============================================================================
  2116. Dax.register(:sprite)
  2117. class Sprite
  2118. #----------------------------------------------------------------------------
  2119. # • Variáveis públicas da instância.
  2120. #----------------------------------------------------------------------------
  2121. attr_accessor :clone_sprite
  2122. attr_accessor :outline_fill_rect
  2123. #----------------------------------------------------------------------------
  2124. # • Novo método. Modos de usos abaixo:
  2125. # * [normal] : É o método normal, na qual você não define nada. Sprite.new
  2126. # * [viewport] : É o método na qual você define um viewport.
  2127. # Sprite.new(Viewport)
  2128. # * [system] : É o método na qual você já define um bitmap que irá carregar
  2129. # uma imagem já direto da pasta System, através do Cache.
  2130. # Sprite.new("S: Nome do Arquivo")
  2131. # * [picture] : É o método na qual você já define um bitmap que irá carregar
  2132. # uma imagem já direito da pasta Pictures, através do Cache.
  2133. # Sprite.new("P: Nome do Arquivo")
  2134. # * [graphics] : É o método na qual você já define um bitmap com uma imagem
  2135. # que está dentro da pasta Graphics, através do Cache.
  2136. # Sprite.new("G: Nome do Arquivo.")
  2137. # * [width, height] : É o método na qual você já define a largura e altura
  2138. # do bitmap. Sprite.new([width, height])
  2139. # * [elements] : É o método na qual você já define a largura, altura,
  2140. # posição X, posição Y e Prioridade do bitmap.
  2141. # Sprite.new([width, height, x, y, z])
  2142. #----------------------------------------------------------------------------
  2143. alias new_initialize initialize
  2144. def initialize(viewport=nil)
  2145. @clone_sprite = []
  2146. @outline_fill_rect = nil
  2147. if viewport.is_a?(String)
  2148. new_initialize(nil)
  2149. if viewport.match(/S: ([^>]*)/)
  2150. self.bitmap = Cache.system($1.to_s)
  2151. elsif viewport.match(/P: ([^>]*)/)
  2152. self.bitmap = Cache.picture($1.to_s)
  2153. elsif viewport.match(/G: ([^>]*)/)
  2154. self.bitmap = Cache.load_bitmap("Graphics/", $1.to_s)
  2155. else
  2156. self.bitmap = Bitmap.new(viewport)
  2157. end
  2158. elsif viewport.is_a?(Array)
  2159. if viewport.size == 2
  2160. new_initialize(nil)
  2161. self.bitmap = Bitmap.new(viewport[0], viewport[1])
  2162. elsif viewport.size == 5
  2163. new_initialize(nil)
  2164. self.bitmap = Bitmap.new(viewport[0], viewport[1])
  2165. self.x, self.y, self.z = viewport[2], viewport[3], viewport[4]
  2166. end
  2167. elsif viewport.is_a?(Viewport) or viewport.nil?
  2168. new_initialize(viewport)
  2169. end
  2170. end
  2171. #----------------------------------------------------------------------------
  2172. # • Renovação do Sprite.
  2173. #----------------------------------------------------------------------------
  2174. alias :dax_core_dispose :dispose
  2175. def dispose
  2176. dax_core_dispose
  2177. @outline_fill_rect.dispose unless @outline_fill_rect.nil? or @outline_fill_rect.disposed?
  2178. end
  2179. #----------------------------------------------------------------------------
  2180. # • Definir um contorno no Sprite em forma de retângulo.
  2181. # color : Cor do contorno.
  2182. # size : Tamanho da linha do contorno.
  2183. # vis : Visibilidade. true - visível | false - invisível.
  2184. #----------------------------------------------------------------------------
  2185. def set_outline(color=Color.new.default, size=2, vis=true)
  2186. @outline_fill_rect = Sprite.new([self.width, self.height, self.x, self.y, self.z+2])
  2187. @outline_fill_rect.bitmap.fill_rect(0, 0, self.width, size, color)
  2188. @outline_fill_rect.bitmap.fill_rect(0, self.height-size, self.width, size, color)
  2189. @outline_fill_rect.bitmap.fill_rect(0, 0, size, self.height, color)
  2190. @outline_fill_rect.bitmap.fill_rect(self.width-size, 0, size, self.height, color)
  2191. @outline_fill_rect.visible = vis
  2192. end
  2193. #----------------------------------------------------------------------------
  2194. # • Atualização do contorno.
  2195. # vis : Visibilidade. true - visível | false - invisível.
  2196. #----------------------------------------------------------------------------
  2197. def update_outline(vis=true)
  2198. @outline_fill_rect.visible = vis
  2199. @outline_fill_rect.x, @outline_fill_rect.y = self.x, self.y
  2200. end
  2201. #----------------------------------------------------------------------------
  2202. # • Slide pela direita.
  2203. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  2204. #----------------------------------------------------------------------------
  2205. def slide_right(speed, point)
  2206. self.x += speed unless self.x >= point
  2207. end
  2208. #----------------------------------------------------------------------------
  2209. # • Slide pela esquerda.
  2210. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  2211. #----------------------------------------------------------------------------
  2212. def slide_left(speed, point)
  2213. self.x -= speed unless self.x <= point
  2214. end
  2215. #----------------------------------------------------------------------------
  2216. # • Slide por cima.
  2217. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  2218. #----------------------------------------------------------------------------
  2219. def slide_up(speed, point)
  2220. self.y -= speed unless self.y <= point
  2221. end
  2222. #----------------------------------------------------------------------------
  2223. # • Slide por baixo.
  2224. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  2225. #----------------------------------------------------------------------------
  2226. def slide_down(speed, point)
  2227. self.y += speed unless self.y >= point
  2228. end
  2229. #----------------------------------------------------------------------------
  2230. # • Define aqui uma posição fixa para um objeto.
  2231. # command : Veja na classe Position.
  2232. #----------------------------------------------------------------------------
  2233. def position(command=0)
  2234. return if command.nil?
  2235. Position[command, self]
  2236. end
  2237. #----------------------------------------------------------------------------
  2238. # • [Numeric] : Tamanho geral
  2239. #----------------------------------------------------------------------------
  2240. def size
  2241. return self.width + self.height
  2242. end
  2243. #----------------------------------------------------------------------------
  2244. # • [Rect] : Retorna ao Rect do Bitmap.
  2245. #----------------------------------------------------------------------------
  2246. def rect
  2247. return self.bitmap.rect
  2248. end
  2249. #----------------------------------------------------------------------------
  2250. # • Base para clonar um Sprite.
  2251. # * depht : Prioridade no mapa.
  2252. # * clone_bitmap : Se irá clonar o bitmap.
  2253. # Exemplo: sprite = sprite2.clone
  2254. #----------------------------------------------------------------------------
  2255. def clone(depht=0, clone_bitmap=false)
  2256. @clone_sprite.delete_if { |bitmap| bitmap.disposed? }
  2257. cloned = Sprite.new(self.viewport)
  2258. cloned.x, cloned.y = self.x, self.y
  2259. cloned.bitmap = self.bitmap
  2260. cloned.bitmap = self.bitmap.clone if clone_bitmap
  2261. unless depht == 0
  2262. cloned.z = self.z + depht
  2263. else
  2264. @clone_sprite.each { |sprite| sprite.z -= 1 }
  2265. cloned.z = self.z - 1
  2266. end
  2267. cloned.src_rect.set(self.src_rect)
  2268. ["zoom_x", "zoom_y", "angle", "mirror", "opacity", "blend_type", "visible",
  2269. "ox", "oy"].each { |meth|
  2270. eval("cloned.#{meth} = self.#{meth}")
  2271. }
  2272. cloned.color.set(color)
  2273. cloned.tone.set(tone)
  2274. after_clone(cloned)
  2275. @clone_sprite.push(cloned)
  2276. return cloned
  2277. end
  2278. #----------------------------------------------------------------------------
  2279. # • Efeito após ter clonado o Sprite.
  2280. #----------------------------------------------------------------------------
  2281. def after_clone(clone)
  2282. end
  2283. #----------------------------------------------------------------------------
  2284. # • O que irá acontecer sê o mouse estiver em cima do sprite?
  2285. #----------------------------------------------------------------------------
  2286. def mouse_over
  2287. end
  2288. #----------------------------------------------------------------------------
  2289. # • O que irá acontecer sê o mouse não estiver em cima do sprite?
  2290. #----------------------------------------------------------------------------
  2291. def mouse_no_over
  2292. end
  2293. #----------------------------------------------------------------------------
  2294. # • O que irá acontecer sê o mouse clicar no objeto
  2295. #----------------------------------------------------------------------------
  2296. def mouse_click
  2297. end
  2298. #----------------------------------------------------------------------------
  2299. # • Atualização dos sprites.
  2300. #----------------------------------------------------------------------------
  2301. alias :dax_update :update
  2302. def update(*args, &block)
  2303. dax_update(*args, &block)
  2304. unless Mouse.cursor.nil?
  2305. self.if_mouse_over { |over| over ? mouse_over : mouse_no_over }
  2306. self.if_mouse_click { mouse_click }
  2307. end
  2308. end
  2309. #----------------------------------------------------------------------------
  2310. # • Inverter o lado do sprite.
  2311. #----------------------------------------------------------------------------
  2312. def mirror!
  2313. self.mirror = !self.mirror
  2314. end
  2315. #----------------------------------------------------------------------------
  2316. # • Inverter o ângulo do sprite em 180°(Pode ser mudado.).
  2317. #----------------------------------------------------------------------------
  2318. def angle!(ang=180)
  2319. self.ox, self.oy = self.bitmap.width, self.bitmap.height
  2320. self.angle += ang
  2321. self.angle += 360 while self.angle < 0
  2322. self.angle %= 360
  2323. end
  2324. end
  2325. #==============================================================================
  2326. # • Bitmap
  2327. #==============================================================================
  2328. Dax.register(:bitmap)
  2329. class Bitmap
  2330. #----------------------------------------------------------------------------
  2331. # • Criar uma barra.
  2332. # color : Objeto de Cor [Color]
  2333. # actual : Valor atual da barra.
  2334. # max : Valor máximo da barra.
  2335. # borda : Tamanho da borda da barra.
  2336. #----------------------------------------------------------------------------
  2337. def bar(color, actual, max, borda=1)
  2338. rate = self.width.to_p(actual, max)
  2339. self.fill_rect(borda, borda, rate-(borda*2), self.height-(borda*2),
  2340. color)
  2341. end
  2342. #----------------------------------------------------------------------------
  2343. # • Barra em forma de gradient.
  2344. # color : Objeto de Cor, em forma de [Array] para conter 2 [Color]
  2345. # exemplo -> [Color.new(x), Color.new(y)]
  2346. # actual : Valor atual da barra.
  2347. # max : Valor máximo da barra.
  2348. # borda : Tamanho da borda da barra.
  2349. #----------------------------------------------------------------------------
  2350. def gradient_bar(color, actual, max, borda=1)
  2351. rate = self.width.to_p(actual, max)
  2352. self.gradient_fill_rect(borda, borda, rate-(borda*2), self.height-(borda*2),
  2353. color[0], color[1], 2)
  2354. end
  2355. #----------------------------------------------------------------------------
  2356. # • Limpar uma área num formato de um círculo.
  2357. #----------------------------------------------------------------------------
  2358. def clear_rect_circle(x, y, r)
  2359. rr = r*r
  2360. for i in 0...r
  2361. adj = Math.sqrt(rr - (i*i)).ceil
  2362. xd = x - adj
  2363. wd = 2 * adj
  2364. self.clear_rect(xd, y-i, wd, 1)
  2365. self.clear_rect(xd, y+i, wd, 1)
  2366. end
  2367. end
  2368. #----------------------------------------------------------------------------
  2369. # • Novo modo de desenhar textos. Configurações já especificadas.
  2370. #----------------------------------------------------------------------------
  2371. def draw_text_rect(*args)
  2372. self.draw_text(self.rect, *args)
  2373. end
  2374. #----------------------------------------------------------------------------
  2375. # • Salvar em png.
  2376. # --- Autor : Gab! ---
  2377. #----------------------------------------------------------------------------
  2378. def save(file_name)
  2379. def chunk(type, data)
  2380. [data.size, type, data, Zlib.crc32(type + data)].pack("NA4A*N")
  2381. end
  2382. img_data = ""
  2383. width, height = self.width, self.height
  2384. for j in 0...(height)
  2385. img_data << "\0"
  2386. for i in 0...(width)
  2387. pos_c = self.get_pixel(i, j)
  2388. img_data << [pos_c.red, pos_c.green, pos_c.blue, pos_c.alpha].pack("C*")
  2389. end
  2390. end
  2391. c = [
  2392. "\x89PNG\r\n\x1a\n",
  2393. chunk("IHDR", [width, height, 8, 6, 0, 0, 0].pack("N2C5")),
  2394. chunk("IDAT", Zlib::Deflate.deflate(img_data)),
  2395. chunk("IEND", "")
  2396. ]
  2397. File.open(file_name << ".png", "wb"){|file| c.each{|chunk| file.write(chunk) }}
  2398. end
  2399. #----------------------------------------------------------------------------
  2400. # • Permite salvar várias imagens em cima de outra.
  2401. # Exemplo de comando:
  2402. # Bitmap.overSave("Pictures/Nova", "Pictures/1", "Characters/2",
  2403. # "Pictures/3", "Characters/4", "Pictures/5")
  2404. # NÃO ESQUEÇA DE ESPECIFICAR ÀS PASTAS.
  2405. #----------------------------------------------------------------------------
  2406. def self.overSave(newfile, first, *args)
  2407. return if first.empty? || first.nil? || args.empty? || args.nil?
  2408. firstB = Bitmap.new("Graphics/"+first)
  2409. args.each { |outhers|
  2410. firstB.stretch_blt(firstB.rect, Bitmap.new("Graphics/"+outhers), firstB.rect)
  2411. }
  2412. firstB.save("Graphics/"+newfile)
  2413. end
  2414. #----------------------------------------------------------------------------
  2415. # • Modificar as cores do [Bitmap] para ficarem Negativas.
  2416. #----------------------------------------------------------------------------
  2417. def negative
  2418. self.rect.step(1.0, 1.0) { |i, j|
  2419. pix = self.get_pixel(i, j)
  2420. pix.red = (pix.red - 255) * -1
  2421. pix.blue = (pix.blue - 255) * -1
  2422. pix.green = (pix.green - 255) * -1
  2423. self.set_pixel(i, j, pix)
  2424. }
  2425. end
  2426. #----------------------------------------------------------------------------
  2427. # • Grayscale : Modificar as cores do [Bitmap] para cor cinza. Efeito cinza.
  2428. #----------------------------------------------------------------------------
  2429. def grayscale(rect = Rect.new(0, 0, self.width, self.height))
  2430. self.rect.step(1, 1) { |i, j|
  2431. colour = self.get_pixel(i,j)
  2432. grey_pixel = (colour.red*0.3 + colour.green*0.59 + colour.blue*0.11)
  2433. colour.red = colour.green = colour.blue = grey_pixel
  2434. self.set_pixel(i,j,colour)
  2435. }
  2436. end
  2437. #----------------------------------------------------------------------------
  2438. # • Converter as cores para sepia.
  2439. #----------------------------------------------------------------------------
  2440. def sepia2
  2441. self.rect.step(1, 1) { |w, h|
  2442. nrow = row = get_pixel(w, h)
  2443. row.red = [(0.393 * nrow.red) + (0.769 * nrow.green) + (0.189 * nrow.blue), 255].min
  2444. row.green = [(0.349 * nrow.red) + (0.689 * nrow.green) + (0.168 * nrow.blue), 255].min
  2445. row.blue = [(0.272 * nrow.red) + (0.534 * nrow.green) + (0.131 * nrow.blue), 255].min
  2446. set_pixel(w, h, row)
  2447. }
  2448. end
  2449. #----------------------------------------------------------------------------
  2450. # • Suavidade nas cores do bitmap. Converte as cores em preto e branco.
  2451. # crlz : Controle da iluminidade.
  2452. #----------------------------------------------------------------------------
  2453. def black_whiteness(ctlz=2.0)
  2454. self.rect.step(1, 1) { |w, h|
  2455. row = get_pixel(w, h)
  2456. getArray__row = row.to_a(false)
  2457. lightCalc_ = (getArray__row.max + getArray__row.min) / ctlz
  2458. row.red = row.green = row.blue = lightCalc_
  2459. set_pixel(w, h, row)
  2460. }
  2461. end
  2462. #----------------------------------------------------------------------------
  2463. # • Novo fornecedor de pixel.
  2464. #----------------------------------------------------------------------------
  2465. def set_pixel_s(x, y, color, size)
  2466. for i in 0...size
  2467. self.set_pixel(x+i, y, color)
  2468. self.set_pixel(x-i, y, color)
  2469. self.set_pixel(x, y+i, color)
  2470. self.set_pixel(x, y-i, color)
  2471. self.set_pixel(x+i, y+i, color)
  2472. self.set_pixel(x-i, y-i, color)
  2473. self.set_pixel(x+i, y-i, color)
  2474. self.set_pixel(x-i, y+i, color)
  2475. end
  2476. end
  2477. #----------------------------------------------------------------------------
  2478. # • Desenhar uma linha.
  2479. # start_x : Início da linha em X.
  2480. # start_y : Início da linha em Y.
  2481. # end_x : Finalização da linha em X.
  2482. # end_y : Finalização da linha em Y.
  2483. #----------------------------------------------------------------------------
  2484. def draw_line(start_x, start_y, end_x, end_y, color, size=1)
  2485. set_pixel_s(start_x, start_y, color, size)
  2486. distance = (start_x - end_x).abs + (start_y - end_y).abs
  2487. for i in 1..distance
  2488. x = (start_x + 1.0 * (end_x - start_x) * i / distance).to_i
  2489. y = (start_y + 1.0 * (end_y - start_y) * i / distance).to_i
  2490. set_pixel_s(x, y, color, size)
  2491. end
  2492. set_pixel_s(end_x, end_y, color, size)
  2493. end
  2494. #----------------------------------------------------------------------------
  2495. # • draw_bar_gauge(x, y, current, current_max, border, colors)
  2496. # x : Coordenadas X.
  2497. # y : Coordenadas Y.
  2498. # current : Valor atual da barra.
  2499. # current_max : Valor maxímo da barra.
  2500. # border : Expressura da borda.
  2501. # colors : Cores. [0, 1]
  2502. #----------------------------------------------------------------------------
  2503. # Permite adicionar uma barra.
  2504. #----------------------------------------------------------------------------
  2505. def draw_bar_gauge(x, y, current, current_max, colors=[])
  2506. cw = self.width.to_p(current, current_max)
  2507. ch = self.height
  2508. self.gradient_fill_rect(x, y, self.width, self.height, colors[0], colors[1])
  2509. src_rect = Rect.new(0, 0, cw, ch)
  2510. self.blt(x, y, self, src_rect)
  2511. end
  2512. #----------------------------------------------------------------------------
  2513. # • draw_icon(icon_index, x, y, enabled)
  2514. # icon_index : ID do ícone.
  2515. # x : Coordenadas X.
  2516. # y : Coordenadas Y.
  2517. # enabled : Habilitar flag, translucido quando false
  2518. # filename : Podes definir uma imagem: Basta
  2519. # por o nome da imagem, ela deve estar na pasta System.
  2520. #----------------------------------------------------------------------------
  2521. def draw_icon(icon_index, x, y, enabled = true, filename="IconSet")
  2522. icon_index = icon_index.nil? ? 0 : icon_index
  2523. bitmap = Cache.system(filename)
  2524. rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)
  2525. self.blt(x, y, bitmap, rect, enabled ? 255 : 128)
  2526. end
  2527. #----------------------------------------------------------------------------
  2528. # • draw_gradation_gauge(x, y, width, height, current, current_max, border, colors, align)
  2529. # x : Coordenadas X.
  2530. # y : Coordenadas Y.
  2531. # width : Largura da barra.
  2532. # height : Altura da barra.
  2533. # current : Valor atual da barra.
  2534. # current_max : Valor maxímo da barra.
  2535. # border : Expressura da borda.
  2536. # colors : Cores. [0, 1]
  2537. # align : Alinhamento.
  2538. #----------------------------------------------------------------------------
  2539. # Permite adicionar uma barra.
  2540. #----------------------------------------------------------------------------
  2541. def draw_gradation_gauge(x, y, current, current_max, border, colors=[])
  2542. cw = self.width.to_p(current, current_max)
  2543. ch = self.height
  2544. self.fill_rect(x, y, self.width, self.height, colors[0])
  2545. self.gradient_fill_rect(x+border, y+border, self.width-(border/2), self.height-(border/2), colors[1], colors[2])
  2546. src_rect = Rect.new(0, 0, cw, ch)
  2547. self.blt(x, y, self, src_rect)
  2548. end
  2549. #----------------------------------------------------------------------------
  2550. # • Desenhar um círuclo preenchido.
  2551. #----------------------------------------------------------------------------
  2552. def fill_circle(x, y, r, c)
  2553. rr = r*r
  2554. for i in 0...r
  2555. adj = Math.sqrt(rr - (i*i)).ceil
  2556. xd = x - adj
  2557. wd = 2 * adj
  2558. self.fill_rect(xd, y-i, wd, 1, c)
  2559. self.fill_rect(xd, y+i, wd, 1, c)
  2560. end
  2561. end
  2562. #----------------------------------------------------------------------------
  2563. # • [Brilho] : Aumentar/Diminuir o brilho do sprite.
  2564. #----------------------------------------------------------------------------
  2565. def brightness(vl = 100)
  2566. self.rect.step(1.0, 1.0) { |i, j|
  2567. pix = self.get_pixel(i, j)
  2568. pix = pix.percent(vl)
  2569. self.set_pixel(i, j, pix)
  2570. }
  2571. end
  2572. end
  2573. #==============================================================================
  2574. # • Mouse
  2575. #==============================================================================
  2576. Dax.register(:mouse)
  2577. module Mouse
  2578. extend self
  2579. #--------------------------------------------------------------------------
  2580. # • Inicialização dos objetos.
  2581. #--------------------------------------------------------------------------
  2582. def start
  2583. @cursor = Sprite_Mouse.new(Dax::Mouse_Name, -128, -128, 100000)
  2584. @graphic = Dax::Mouse_Name
  2585. x = Dax::Mouse_Name == "" ? 1 : 0
  2586. API::MouseShowCursor.call(x)
  2587. @visible = false
  2588. end
  2589. #----------------------------------------------------------------------------
  2590. # • visible = (boolean)
  2591. # * boolean : true ou false
  2592. # Tornar vísivel ou não o cursor do Mouse.
  2593. #----------------------------------------------------------------------------
  2594. def visible=(boolean)
  2595. @visible = boolean
  2596. end
  2597. #--------------------------------------------------------------------------
  2598. # • graphic(graphic_set)
  2599. # graphic_set : Se for número é um ícone; Se for string é uma imagem.
  2600. #--------------------------------------------------------------------------
  2601. def graphic(graphic_set)
  2602. visible = false
  2603. @graphic = graphic_set
  2604. @cursor.set_graphic = graphic_set
  2605. end
  2606. #--------------------------------------------------------------------------
  2607. # • show(visible)
  2608. # visible : True - para mostrar o mouse | False - para esconder o mouse.
  2609. #--------------------------------------------------------------------------
  2610. def show(vis=true)
  2611. @cursor.visible = vis
  2612. end
  2613. #--------------------------------------------------------------------------
  2614. # • update (Atualização das coordenadas)
  2615. #--------------------------------------------------------------------------
  2616. def update
  2617. return if @cursor.nil?
  2618. API::MouseShowCursor.call(@visible.boolean)
  2619. if @cursor.disposed?
  2620. @cursor = Sprite_Mouse.new(@graphic, 0, 0, 100000)
  2621. end
  2622. @cursor.update
  2623. @cursor.x, @cursor.y = position
  2624. end
  2625. #--------------------------------------------------------------------------
  2626. # • Retorna a variável '@cursor' que tem como valor a classe [Sprite].
  2627. #--------------------------------------------------------------------------
  2628. def cursor
  2629. @cursor
  2630. end
  2631. #--------------------------------------------------------------------------
  2632. # • Clear.
  2633. #--------------------------------------------------------------------------
  2634. def clear
  2635. @cursor.dispose
  2636. end
  2637. #--------------------------------------------------------------------------
  2638. # • x (Coordenada X do Mouse)
  2639. #--------------------------------------------------------------------------
  2640. def x
  2641. @cursor.x
  2642. end
  2643. #--------------------------------------------------------------------------
  2644. # • y (Coordenada Y do Mouse)
  2645. #--------------------------------------------------------------------------
  2646. def y
  2647. @cursor.y
  2648. end
  2649. #--------------------------------------------------------------------------
  2650. # • position (Posição do Mouse!)
  2651. #--------------------------------------------------------------------------
  2652. def position
  2653. x, y = get_client_position
  2654. return x, y
  2655. end
  2656. #--------------------------------------------------------------------------
  2657. # • Grid do mapa.
  2658. #--------------------------------------------------------------------------
  2659. def map_grid
  2660. return unless defined?($game_map)
  2661. return nil if x == nil or y == nil
  2662. rx = ($game_map.display_x).to_i + (x / 32)
  2663. ry = ($game_map.display_y).to_i + (y / 32)
  2664. return [rx.to_i, ry.to_i]
  2665. end
  2666. #--------------------------------------------------------------------------
  2667. # • get_client_position (Posição original do Mouse!)
  2668. #--------------------------------------------------------------------------
  2669. def get_client_position
  2670. pos = [0, 0].pack('ll')
  2671. API::CursorPosition.call(pos)
  2672. API::ScreenToClient.call(find_window, pos)
  2673. return pos.unpack('ll')
  2674. end
  2675. #--------------------------------------------------------------------------
  2676. # • find_window (Tamanho da window)
  2677. #--------------------------------------------------------------------------
  2678. def find_window
  2679. game_name = '\0' * 256
  2680. API::ReadIni.call('Game', 'Title', '', game_name, 255, '.\\Game.ini')
  2681. game_name.delete!('\0') ensure game_name
  2682. return API::FindWindow.call('RGSS Player', game_name)
  2683. end
  2684. #--------------------------------------------------------------------------
  2685. # • Verificação se o mouse está na área de um determinado objeto.
  2686. #--------------------------------------------------------------------------
  2687. def in_area?(object_sprite)
  2688. return if @cursor.disposed?
  2689. return unless object_sprite.is_a?(Sprite) or object_sprite.is_a?(Window)
  2690. return @cursor.x.between?(object_sprite.x, object_sprite.x + object_sprite.width) &&
  2691. @cursor.y.between?(object_sprite.y, object_sprite.y + object_sprite.height)
  2692. end
  2693. #----------------------------------------------------------------------------
  2694. # • Verificar se o mouse está em determinada área
  2695. #----------------------------------------------------------------------------
  2696. def area?(x, y, width, height)
  2697. return @cursor.x.between?(x, x + width) &&
  2698. @cursor.y.between?(y, y + height)
  2699. end
  2700. #----------------------------------------------------------------------------
  2701. # • Mudar posição do cursor.
  2702. #----------------------------------------------------------------------------
  2703. def set_mouse(pos)
  2704. SetCursorPos.call(pos.x, pos.y)
  2705. update
  2706. @cursor.x = @pos.x
  2707. @cursor.y = @pos.y
  2708. end
  2709. #----------------------------------------------------------------------------
  2710. # • Verifica se clicou com o botão esquerdo do Mouse.
  2711. #----------------------------------------------------------------------------
  2712. def left?
  2713. return Key.trigger?(0x01)
  2714. end
  2715. #----------------------------------------------------------------------------
  2716. # • Verifica se clicou com o botão direito do Mouse.
  2717. #----------------------------------------------------------------------------
  2718. def right?
  2719. return Key.trigger?(0x02)
  2720. end
  2721. end
  2722. #==============================================================================
  2723. # • Sprite_Mouse
  2724. #==============================================================================
  2725. Dax.register(:sprite_mouse)
  2726. class Sprite_Mouse < Sprite
  2727. #----------------------------------------------------------------------------
  2728. # • Variáveis públicas da instância.
  2729. #----------------------------------------------------------------------------
  2730. attr_accessor :set_graphic # definir o gráfico.
  2731. #----------------------------------------------------------------------------
  2732. # • Inicialização dos objetos.
  2733. #----------------------------------------------------------------------------
  2734. def initialize(graphic, x, y, z)
  2735. super(nil)
  2736. @set_graphic = graphic
  2737. if @set_graphic.is_a?(Fixnum)
  2738. self.bitmap = Bitmap.new(24, 24)
  2739. self.bitmap.draw_icon(@set_graphic, 0, 0)
  2740. elsif @set_graphic.is_a?(NilClass) or @set_graphic == ""
  2741. self.bitmap = Bitmap.new(1, 1)
  2742. elsif @set_graphic.is_a?(String)
  2743. self.bitmap = Cache.system(@set_graphic)
  2744. end
  2745. self.x, self.y, self.z = x, y, z
  2746. @older = @set_graphic
  2747. end
  2748. #----------------------------------------------------------------------------
  2749. # • Renovação dos objetos.
  2750. #----------------------------------------------------------------------------
  2751. def dispose
  2752. self.bitmap.dispose
  2753. super
  2754. end
  2755. #----------------------------------------------------------------------------
  2756. # • Atualização dos objetos.
  2757. #----------------------------------------------------------------------------
  2758. def update
  2759. super
  2760. unless @older == @set_graphic
  2761. if @set_graphic.is_a?(Fixnum)
  2762. self.bitmap = Bitmap.new(24, 24)
  2763. self.bitmap.draw_icon(@set_graphic, 0, 0)
  2764. elsif @set_graphic.is_a?(NilClass) or @set_graphic == ""
  2765. self.bitmap = Bitmap.new(1, 1)
  2766. elsif @set_graphic.is_a?(String)
  2767. self.bitmap = Cache.system(@set_graphic)
  2768. end
  2769. @older = @set_graphic
  2770. end
  2771. end
  2772. end
  2773. Mouse.start
  2774. #==============================================================================
  2775. # • Object
  2776. #==============================================================================
  2777. Dax.register(:object)
  2778. class Object
  2779. #----------------------------------------------------------------------------
  2780. # • [Hex] : Retorna ao id do objeto em hexadécimal.
  2781. #----------------------------------------------------------------------------
  2782. def __hexid__
  2783. "0x" + ('%.X' % (self.__id__ * 2))
  2784. end
  2785. #----------------------------------------------------------------------------
  2786. # • O que irá ocorrer caso o mouse esteja sobre uma sprite.
  2787. # Tem que ser um objeto Sprite.
  2788. #----------------------------------------------------------------------------
  2789. def if_mouse_over(&block)
  2790. return if Mouse.cursor.nil?
  2791. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  2792. over ||= false
  2793. if Mouse.in_area?(self)
  2794. block.call
  2795. over = true
  2796. else
  2797. over = false
  2798. end
  2799. yield over
  2800. end
  2801. #----------------------------------------------------------------------------
  2802. # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao clicar.
  2803. # Tem que ser um objeto Sprite.
  2804. # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
  2805. # EXPLICAÇÕES NO FINAL DO SCRIPT.
  2806. #----------------------------------------------------------------------------
  2807. def if_mouse_click(button=:left, &block)
  2808. return if Mouse.cursor.nil?
  2809. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  2810. button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
  2811. block.call if Mouse.in_area?(self) and trigger?(button)
  2812. end
  2813. #----------------------------------------------------------------------------
  2814. # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao pressionar.
  2815. # Tem que ser um objeto Sprite.
  2816. # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
  2817. #----------------------------------------------------------------------------
  2818. def if_mouse_press(button=:left, &block)
  2819. return if Mouse.cursor.nil?
  2820. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  2821. button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
  2822. block.call if Mouse.in_area?(self) and press?(button)
  2823. end
  2824. #----------------------------------------------------------------------------
  2825. # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao ficar clicando.
  2826. # Tem que ser um objeto Sprite.
  2827. # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
  2828. #----------------------------------------------------------------------------
  2829. def if_mouse_repeat(button=:left, &block)
  2830. return if Mouse.cursor.nil?
  2831. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  2832. button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
  2833. block.call if Mouse.in_area?(self) and repeat?(button)
  2834. end
  2835. #----------------------------------------------------------------------------
  2836. # • Trigger
  2837. # * key : Chave.
  2838. # Você também pode usá-lo como condição para executar tal bloco;
  2839. #----------------------------------------------------------------------------
  2840. # trigger?(key) { bloco que irá executar }
  2841. #----------------------------------------------------------------------------
  2842. def trigger?(key, &block)
  2843. if key == :C or key == :B
  2844. ckey = Input.trigger?(key)
  2845. else
  2846. ckey = Key.trigger?(key)
  2847. end
  2848. return ckey unless block_given?
  2849. block.call if ckey
  2850. end
  2851. #----------------------------------------------------------------------------
  2852. # • Press
  2853. # * key : Chave.
  2854. # Você também pode usá-lo como condição para executar tal bloco;
  2855. #----------------------------------------------------------------------------
  2856. # press?(key) { bloco que irá executar. }
  2857. #----------------------------------------------------------------------------
  2858. def press?(key, &block)
  2859. if key == :C or key == :B
  2860. ckey = Input.press?(key)
  2861. else
  2862. ckey = Key.press?(key)
  2863. end
  2864. return ckey unless block_given?
  2865. block.call if ckey
  2866. end
  2867. #----------------------------------------------------------------------------
  2868. # • Repeat
  2869. # * key : Chave.
  2870. # Você também pode usá-lo como condição para executar tal bloco;
  2871. #----------------------------------------------------------------------------
  2872. # repeat?(key) { bloco que irá executar. }
  2873. #----------------------------------------------------------------------------
  2874. def repeat?(key, &block)
  2875. if key == :C or key == :B
  2876. ckey = Input.repeat?(key)
  2877. else
  2878. ckey = Key.repeat?(key)
  2879. end
  2880. return ckey unless block_given?
  2881. block.call if ckey
  2882. end
  2883. #----------------------------------------------------------------------------
  2884. # • Retorna em forma de número os valores true ou false. E caso seja
  2885. # 0 ou 1.. retorna a true ou false.
  2886. # Se for true, retorna a 1.
  2887. # Se for false, retorna a 0.
  2888. # Se for 1, retorna a true.
  2889. # Se for 0, retorna a false.
  2890. #----------------------------------------------------------------------------
  2891. def boolean
  2892. return self.is_a?(Integer) ? self == 0 ? false : 1 : self ? 1 : 0
  2893. end
  2894. #----------------------------------------------------------------------------
  2895. # • Converte para a classe Position.
  2896. #----------------------------------------------------------------------------
  2897. def position
  2898. return Position.new(self, self) if self.is_a?(Numeric)
  2899. return Position.new(self.x, self.y) if self.is_a?(Sprite) or self.is_a?(Window_Base) or self.is_a?(Rect)
  2900. return Position.new(self[0], self[1]) if self.is_a?(Array)
  2901. return Position.new(self[:x], self[:y]) if self.is_a?(Hash)
  2902. return Position.new(0, 0)
  2903. end
  2904. #----------------------------------------------------------------------------
  2905. # • Transforma em cor.
  2906. # Se for uma Array. Exemplo: [128, 174, 111].color =># Color.new(128, 174, 111)
  2907. # Se for uma String. Exemplo: "ffffff".color =># Color.new(255,255,255)
  2908. #----------------------------------------------------------------------------
  2909. def color
  2910. return Color.new(*self) if self.is_a?(Array)
  2911. return Color.new.hex(self) if self.is_a?(String)
  2912. end
  2913. end
  2914. #==============================================================================
  2915. # • Entries
  2916. #==============================================================================
  2917. Dax.register(:entries)
  2918. class Entries
  2919. #----------------------------------------------------------------------------
  2920. # • [Array] : Irá retornar a todos os nomes dos arquivos da pasta, dentro de
  2921. # uma Array em formato de String.
  2922. #----------------------------------------------------------------------------
  2923. attr_accessor :file
  2924. #----------------------------------------------------------------------------
  2925. # • [Integer] : Retorna a quantidade total de arquivos que têm na pasta.
  2926. #----------------------------------------------------------------------------
  2927. attr_reader :size
  2928. #----------------------------------------------------------------------------
  2929. # • Inicialização dos objetos.
  2930. # directory : Nome da pasta. Não ponha '/' no final do nome. Ex: 'Data/'
  2931. # typefile : Nome da extensão do arquivo. Não ponha '.' no começo. Ex: '.txt'
  2932. #----------------------------------------------------------------------------
  2933. def initialize(directory, typefile)
  2934. return unless FileTest.directory?(directory)
  2935. @file = Dir.glob(directory + "/*.{" + typefile + "}")
  2936. @file.each_index { |i| @size = i.to_i }
  2937. @name = split @file[0]
  2938. end
  2939. #----------------------------------------------------------------------------
  2940. # • [String] : Separar o nome do arquivo do nome da pasta.
  2941. #----------------------------------------------------------------------------
  2942. def split(file)
  2943. file.to_s.split('/').last
  2944. end
  2945. #----------------------------------------------------------------------------
  2946. # • [String] : Obtêm o nome do arquivo correspondente ao id configurado,
  2947. # separado do nome da pasta.
  2948. #----------------------------------------------------------------------------
  2949. def name(id)
  2950. return if @file.nil?
  2951. return split(@file[id])
  2952. end
  2953. end
  2954. #==============================================================================
  2955. # • DRGSS | Comandos do RGSS...
  2956. #==============================================================================
  2957. Dax.register(:drgss)
  2958. module DRGSS
  2959. extend self
  2960. #----------------------------------------------------------------------------
  2961. # • Extrair scripts do Database para um arquivo de extensão de texto.
  2962. # options : Caso você deixe assim: {folder: "NM"}
  2963. # NM => Nome da pasta na qual os arquivos irão.
  2964. #----------------------------------------------------------------------------
  2965. def extract_scripts(type=".txt",options={})
  2966. except = options[:except] || []
  2967. folder = options[:folder] || ""
  2968. id = 0 #
  2969. $RGSS_SCRIPTS.each do |script|
  2970. name = script[1]
  2971. data = script[3]
  2972. next if except.include? name or name.empty? or data.empty?
  2973. filename = sprintf("%03d", id) + "_" + name
  2974. p "Writing: #{filename}"
  2975. File.open(folder+filename+"#{type}", "wb") do |file|
  2976. file.write data
  2977. end
  2978. id += 1
  2979. end
  2980. end
  2981. #----------------------------------------------------------------------------
  2982. # • Guarda todos os scripts do Database num arquivo;
  2983. #----------------------------------------------------------------------------
  2984. def keep_scripts_in_file(filename="RGSS.rvdata2")
  2985. unless FileTest.exist?(filename)
  2986. self.extract_scripts(".txt")
  2987. file = File.open(filename, "wb")
  2988. Dir.glob("./*.{txt}").each_with_index { |v,i|
  2989. next unless v.match(/(\d+){3}_(\w*)/)
  2990. file.write(IO.readlines(v).to_s)
  2991. File.delete(v)
  2992. }
  2993. file.close
  2994. end
  2995. end
  2996. end
  2997. #==============================================================================
  2998. # • Backup Complete
  2999. #==============================================================================
  3000. Dax.register(:backup)
  3001. module Backup
  3002. extend self
  3003. #----------------------------------------------------------------------------
  3004. # • Criar as pastas.
  3005. #----------------------------------------------------------------------------
  3006. def make_past
  3007. Dir.mksdir("Backup", "Data, System, Movies, Graphics, Audio")
  3008. Dir.mksdir("Backup/Audio", "BGM, BGS, ME, SE")
  3009. Dir.mksdir("Backup/Graphics", "Animations, Battlebacks1, Battlebacks2, Battlers, Characters, Faces, Parallaxes, Pictures, System, Titles1, Titles2, Tilesets")
  3010. end
  3011. #----------------------------------------------------------------------------
  3012. # • Copiar a pasta system.
  3013. #----------------------------------------------------------------------------
  3014. def system
  3015. list = Dir.glob('System/*')
  3016. list.size.times { |i|API::CopyFile.call(list[i], "Backup/" + list[i], true.boolean)}
  3017. end
  3018. #----------------------------------------------------------------------------
  3019. # • Copiar a pasta movie.
  3020. #----------------------------------------------------------------------------
  3021. def movies
  3022. movies = Dir.glob("Movies/*")
  3023. movies.size.times { |i| API::CopyFile.call(movies[i], "Backup/" + movies[i], true.boolean)}
  3024. end
  3025. #----------------------------------------------------------------------------
  3026. # • Copiar a pasta audio
  3027. #----------------------------------------------------------------------------
  3028. def audio
  3029. bgm = Dir.glob('Audio/BGM/*')
  3030. bgs = Dir.glob('Audio/BGS/*')
  3031. me = Dir.glob('Audio/ME/*')
  3032. se = Dir.glob('Audio/SE/*')
  3033. bgm.size.times { |i| API::CopyFile.call(bgm[i], "Backup/" + bgm[i], true.boolean)}
  3034. bgs.size.times { |i| API::CopyFile.call(bgs[i], "Backup/" + bgs[i], true.boolean) }
  3035. me.size.times { |i| API::CopyFile.call(me[i], "Backup/" + me[i], true.boolean) }
  3036. se.size.times { |i| API::CopyFile.call(se[i], "Backup/" + se[i], true.boolean) }
  3037. end
  3038. #----------------------------------------------------------------------------
  3039. # • Copiar a pasta Data.
  3040. #----------------------------------------------------------------------------
  3041. def data
  3042. data = Dir.glob('Data/*')
  3043. data.size.times { |i| API::CopyFile.call(data[i], "Backup/" + data[i], true.boolean) }
  3044. end
  3045. #----------------------------------------------------------------------------
  3046. # • Copiar a pasta Graphic.
  3047. #----------------------------------------------------------------------------
  3048. def graphics
  3049. ["Animations", "Battlebacks1", "Battlebacks2", "Battlers", "Characters",
  3050. "Faces", "Parallaxes", "Pictures", "System", "Titles1", "Titles2",
  3051. "Tilesets"].each { |dirs|
  3052. d = Dir.glob("Graphics/#{dirs}/*")
  3053. d.size.times { |v| API::CopyFile.call(d[v], "Backup/" + d[v], true.boolean) }
  3054. }
  3055. end
  3056. #----------------------------------------------------------------------------
  3057. # • Executar
  3058. #----------------------------------------------------------------------------
  3059. def run(audios=false, graphic=false)
  3060. if $TEST
  3061. make_past
  3062. movies
  3063. data
  3064. system
  3065. audio if audios
  3066. graphics if graphic
  3067. end
  3068. end
  3069. end
  3070. #==============================================================================
  3071. # * SceneManager
  3072. #==============================================================================
  3073. Dax.register :scenemanager
  3074. if defined?("SceneManager")
  3075. class << SceneManager
  3076. #--------------------------------------------------------------------------
  3077. # • **** Método ainda não explicado ****
  3078. #--------------------------------------------------------------------------
  3079. def symbol(scene_symbol)
  3080. eval("self.call(#{scene_symbol.to_s})")
  3081. end
  3082. end
  3083. end
  3084. #==============================================================================
  3085. # • Sprite_Text
  3086. #==============================================================================
  3087. Dax.register(:sprite_text)
  3088. class Sprite_Text < Sprite
  3089. #----------------------------------------------------------------------------
  3090. # • Variáveis públicas da instância.
  3091. #----------------------------------------------------------------------------
  3092. attr_accessor :text # Mudar de texto...
  3093. attr_accessor :align
  3094. #----------------------------------------------------------------------------
  3095. # • Inicialização dos objetos.
  3096. #----------------------------------------------------------------------------
  3097. def initialize(x, y, width, height, text, align=0)
  3098. super([width, height])
  3099. self.x, self.y = x, y
  3100. @text = text
  3101. @align = align
  3102. self.bitmap.draw_text_rect(@text, align)
  3103. end
  3104. #----------------------------------------------------------------------------
  3105. # • Renovação dos objetos.
  3106. #----------------------------------------------------------------------------
  3107. def dispose
  3108. self.bitmap.dispose
  3109. super
  3110. end
  3111. #----------------------------------------------------------------------------
  3112. # • Atualização dos objetos.
  3113. #----------------------------------------------------------------------------
  3114. def update
  3115. self.bitmap.clear
  3116. super
  3117. self.bitmap.draw_text_rect(@text, @align)
  3118. end
  3119. def size=(value=18)
  3120. self.bitmap.font.size = value
  3121. end
  3122. def name=(value=nil)
  3123. self.bitmap.font.name = value || "Arial"
  3124. end
  3125. #----------------------------------------------------------------------------
  3126. # • Negrito na fonte?
  3127. #----------------------------------------------------------------------------
  3128. def bold=(value=nil)
  3129. self.bitmap.font.bold = value || true
  3130. end
  3131. #----------------------------------------------------------------------------
  3132. # • Itálico na fonte?
  3133. #----------------------------------------------------------------------------
  3134. def italic=(value=nil)
  3135. self.bitmap.font.italic = value || true
  3136. end
  3137. #----------------------------------------------------------------------------
  3138. # • Sombra na fonte?
  3139. #----------------------------------------------------------------------------
  3140. def shadow=(value=nil)
  3141. self.bitmap.font.shadow = value || true
  3142. end
  3143. #----------------------------------------------------------------------------
  3144. # • Borda na fonte?
  3145. #----------------------------------------------------------------------------
  3146. def outline=(value=nil)
  3147. self.bitmap.font.outline = value || true
  3148. end
  3149. #----------------------------------------------------------------------------
  3150. # • Mudar a cor da fonte:
  3151. #----------------------------------------------------------------------------
  3152. def color=(color=nil)
  3153. self.bitmap.font.color = color || Color.new.default
  3154. end
  3155. #----------------------------------------------------------------------------
  3156. # • Mudar a cor da borda da fonte.
  3157. #----------------------------------------------------------------------------
  3158. def out_color=(out_color=nil)
  3159. self.bitmap.font.out_color = out_color || Color.new.hex("000000")
  3160. end
  3161. end
  3162. #==============================================================================
  3163. # • Sprite_Icon
  3164. #==============================================================================
  3165. Dax.register(:sprite_icon)
  3166. class Sprite_Icon < Sprite
  3167. #----------------------------------------------------------------------------
  3168. # • Variáveis públicas da instância.
  3169. #----------------------------------------------------------------------------
  3170. attr_accessor :icon_index # Mudar de ícone.
  3171. attr_accessor :enabled # Tornar opaco ou não.
  3172. attr_accessor :filename # Nome do arquivo.
  3173. #----------------------------------------------------------------------------
  3174. # • Inicialização dos objetos.
  3175. #----------------------------------------------------------------------------
  3176. def initialize(icon_index, x, y, enabled=true)
  3177. super([24, 24])
  3178. self.x, self.y = x, y
  3179. @icon_index = icon_index.to_i
  3180. @enabled = enabled
  3181. self.bitmap.draw_icon(@icon_index, 0, 0, @enabled)
  3182. end
  3183. #----------------------------------------------------------------------------
  3184. # • Renovação dos objetos.
  3185. #----------------------------------------------------------------------------
  3186. def dispose
  3187. self.bitmap.dispose
  3188. super
  3189. end
  3190. #----------------------------------------------------------------------------
  3191. # • Atualização dos objetos.
  3192. #----------------------------------------------------------------------------
  3193. def update
  3194. self.bitmap.clear
  3195. super
  3196. self.bitmap.draw_icon(@icon_index, 0, 0, @enabled, @filename)
  3197. end
  3198. end
  3199. #==============================================================================
  3200. # • Opacity
  3201. #==============================================================================
  3202. Dax.register(:opacity)
  3203. module Opacity
  3204. extend self
  3205. @key ||= {}
  3206. #----------------------------------------------------------------------------
  3207. # • Efeito de opacidade que vai aumentando e diminuindo.
  3208. # sprite : Objeto na qual sofrerá o efeito. [Sprite]
  3209. # speed : Velocidade na qual o efeito irá acontencer.
  3210. # max : Valor máximo na qual irá ser atingido.
  3211. # min : Valor minímo na qual irá ser atingido.
  3212. #----------------------------------------------------------------------------
  3213. def sprite_opacity(sprite, speed, max, min, hash=nil)
  3214. @key[hash.nil? ? hash.__id__ : hash] || false
  3215. unless @key[hash]
  3216. sprite.opacity += speed unless sprite.opacity >= max
  3217. @key[hash] = sprite.opacity >= max
  3218. else
  3219. sprite.opacity -= speed unless sprite.opacity <= min
  3220. @key[hash] = false if sprite.opacity <= min
  3221. end
  3222. end
  3223. #----------------------------------------------------------------------------
  3224. # • Efeito de opacidade por fora.
  3225. # sprite : Objeto na qual sofrerá o efeito. [Sprite]
  3226. # speed : Velocidade na qual o efeito irá acontencer.
  3227. # max : Valor máximo na qual irá ser atingido.
  3228. #----------------------------------------------------------------------------
  3229. def sprite_opacity_out(sprite, speed, max)
  3230. return if sprite.nil?
  3231. sprite.opacity += speed unless sprite.opacity >= max
  3232. end
  3233. #----------------------------------------------------------------------------
  3234. # • Efeito de opacidade por dentro.
  3235. # sprite : Objeto na qual sofrerá o efeito. [Sprite]
  3236. # speed : Velocidade na qual o efeito irá acontencer.
  3237. # min : Valor minímo na qual irá ser atingido.
  3238. #----------------------------------------------------------------------------
  3239. def sprite_opacity_in(sprite, speed, min)
  3240. sprite.opacity -= speed unless sprite.opacity <= min
  3241. end
  3242. #----------------------------------------------------------------------------
  3243. # • Limpar variável.
  3244. #----------------------------------------------------------------------------
  3245. def clear
  3246. @key.clear
  3247. end
  3248. end
  3249. #==============================================================================
  3250. # • Read
  3251. #==============================================================================
  3252. Dax.register(:read, "Dax")
  3253. module Read
  3254. extend self
  3255. #----------------------------------------------------------------------------
  3256. # • Verificar valor numérico após uma palavra em um arquivo.
  3257. #----------------------------------------------------------------------------
  3258. def numeric(file, tag)
  3259. IO.readlines(file).each do |line|
  3260. return $1.to_i if line.match(/#{tag} (\d+)/)
  3261. end
  3262. end
  3263. #----------------------------------------------------------------------------
  3264. # • Verificar valor de uma palavra(string única) após uma palavra em um arquivo
  3265. #----------------------------------------------------------------------------
  3266. def string(file, tag)
  3267. IO.readlines(file).each do |line|
  3268. return $1.to_s if line.match(/#{tag} (\w+)/)
  3269. end
  3270. end
  3271. #----------------------------------------------------------------------------
  3272. # • Verificar um conteúdo após uma palavra de um arquivo.
  3273. #----------------------------------------------------------------------------
  3274. def content(file, tag)
  3275. IO.readlines(file).each do |line|
  3276. return $1 if line.match(/#{tag} ([^>]*)/)
  3277. end
  3278. end
  3279. #----------------------------------------------------------------------------
  3280. # • Multiplo número..
  3281. #----------------------------------------------------------------------------
  3282. def multiple_numeric(file, tag)
  3283. IO.readlines(file).each do |line|
  3284. return [$1.to_i, $2.to_i] if line.match(/#{tag} (\d+), (\d+)/)
  3285. end
  3286. end
  3287. #----------------------------------------------------------------------------
  3288. # • Multiplo string..
  3289. #----------------------------------------------------------------------------
  3290. def multiple_string(file, tag)
  3291. IO.readlines(file).each do |line|
  3292. return [$1.to_s, $2.to_s] if line.match(/#{tag} (\w+), (\w+)/)
  3293. end
  3294. end
  3295. #----------------------------------------------------------------------------
  3296. # • Triplo número.
  3297. #----------------------------------------------------------------------------
  3298. def triple_numeric(file, tag)
  3299. IO.readlines(file).each do |line|
  3300. return [$1.to_i, $2.to_i, $3.to_i] if line.match(/#{tag} (\d+), (\d+), (\d+)/)
  3301. end
  3302. end
  3303. #----------------------------------------------------------------------------
  3304. # • Triplo string.
  3305. #----------------------------------------------------------------------------
  3306. def triple_string(file, tag)
  3307. IO.readlines(file).each do |line|
  3308. return [$1.to_s, $2.to_s, $3.to_s] if line.match(/#{tag} (\w+), (\w+), (\w+)/)
  3309. end
  3310. end
  3311. #----------------------------------------------------------------------------
  3312. # • Se é verdairo ou falo.
  3313. #----------------------------------------------------------------------------
  3314. def of(file, tag)
  3315. IO.readlines(file).each do |line|
  3316. return $1.to_s == "true" ? true : false if line.match(/#{tag} ([^>]*)/)
  3317. end
  3318. end
  3319. end
  3320. #==============================================================================
  3321. # • Crypt
  3322. #==============================================================================
  3323. Dax.register(:crypt)
  3324. module Crypt
  3325. extend self
  3326. #----------------------------------------------------------------------------
  3327. # • Constantes
  3328. #---------------------------------------------------------------------------
  3329. # Chave de encriptação. 32-bit esse é o limite: 0xFFFFFFF ou 4294967295
  3330. KEY = 0xFFFFFFF
  3331. EXTN = ".drvd2" # Extensão do aquivo encriptado.
  3332. #----------------------------------------------------------------------------
  3333. # • Método de encriptação.
  3334. # string : String que será encriptado.
  3335. #----------------------------------------------------------------------------
  3336. def encrypt(string)
  3337. string.unpack("U*").collect! { |i|i^KEY}.compact.pack("U*").unpack("C*").pack("U*")
  3338. end
  3339. #----------------------------------------------------------------------------
  3340. # • Método de desencriptação.
  3341. # string : String que será desencriptado.
  3342. #----------------------------------------------------------------------------
  3343. def decrypt(string)
  3344. string.unpack("U*").pack("C*").unpack("U*").collect! {|i|i^KEY}.compact.pack("U*")
  3345. end
  3346. #----------------------------------------------------------------------------
  3347. # • [NilClass] : Método de encriptação de arquivos.
  3348. # filename : Nome do arquivo que será encriptado.
  3349. # delete : Deletar o arquivo não-encriptado. Por padrão é false.
  3350. #----------------------------------------------------------------------------
  3351. def enfile(filename, delete=false)
  3352. return unless FileTest.exist?(filename)
  3353. open(filename.extn(EXTN), "wb") { |file|
  3354. IO.readlines(filename).each { |i| file.write(encrypt(i)) }
  3355. file.close
  3356. }
  3357. File.delete(filename) if delete
  3358. return nil
  3359. end
  3360. #----------------------------------------------------------------------------
  3361. # • [NilClass] : Método de desencriptação de arquivos.
  3362. # filename : Nome do arquivo que será desencriptado.
  3363. # extension : Extensão do novo arquivo. Do arquivo com o conteúdo desencriptado.
  3364. # delete : Deletar o arquivo encriptado. Por padrão é false.
  3365. #----------------------------------------------------------------------------
  3366. def defile(filename, extension="rb", delete=false)
  3367. return unless FileTest.exist?(filename)
  3368. open(filename.extn(extension), "wb") { |file|
  3369. IO.readlines(filename).each { |i| file.write(decrypt(i)) }
  3370. file.close
  3371. }
  3372. File.delete(filename) if delete
  3373. return nil
  3374. end
  3375. #----------------------------------------------------------------------------
  3376. # • [String] : Método que lê o arquivo encriptado.
  3377. # filename : Nome do arquivo que será desencriptado.
  3378. #----------------------------------------------------------------------------
  3379. def rdefile(filename)
  3380. return unless FileTest.exist?(filename)
  3381. str = ""
  3382. IO.readlines(filename).each { |i| str << decrypt(i) }
  3383. str
  3384. end
  3385. end
  3386. #==============================================================================
  3387. # • Background
  3388. #==============================================================================
  3389. Dax.register :background
  3390. module Background
  3391. extend self
  3392. #----------------------------------------------------------------------------
  3393. # • Plano de fundo padrão...
  3394. #----------------------------------------------------------------------------
  3395. def default(alpha=128)
  3396. @background = Sprite.new
  3397. @background.bitmap = SceneManager.background_bitmap
  3398. @background.color.set(16, 16, 16, alpha)
  3399. end
  3400. #----------------------------------------------------------------------------
  3401. # • Plano de fundo padrão renovado.
  3402. #----------------------------------------------------------------------------
  3403. def default_dispose
  3404. return if @background.nil?
  3405. @background.dispose
  3406. end
  3407. end
  3408. #==============================================================================
  3409. # * Window_Base
  3410. #==============================================================================
  3411. Dax.register(:window_base)
  3412. Dax.if_defined?("Window_Base") {
  3413. class Window_Base < Window
  3414. #----------------------------------------------------------------------------
  3415. # • Slide pela direita.
  3416. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  3417. #----------------------------------------------------------------------------
  3418. def slide_right(speed, point)
  3419. self.x += speed unless self.x >= point
  3420. end
  3421. #----------------------------------------------------------------------------
  3422. # • Slide pela esquerda.
  3423. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  3424. #----------------------------------------------------------------------------
  3425. def slide_left(speed, point)
  3426. self.x -= speed unless self.x <= point
  3427. end
  3428. #----------------------------------------------------------------------------
  3429. # • Slide por cima.
  3430. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  3431. #----------------------------------------------------------------------------
  3432. def slide_up(speed, point)
  3433. self.y -= speed unless self.y <= point
  3434. end
  3435. #----------------------------------------------------------------------------
  3436. # • Slide por baixo.
  3437. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  3438. #----------------------------------------------------------------------------
  3439. def slide_down(speed, point)
  3440. self.y += speed unless self.y >= point
  3441. end
  3442. #----------------------------------------------------------------------------
  3443. # • Define aqui uma posição fixa para um objeto.
  3444. # command : Retorna a uma base padrão.
  3445. #----------------------------------------------------------------------------
  3446. def position(command=0)
  3447. return if command.nil?
  3448. Position[command, self]
  3449. end
  3450. end
  3451. }
  3452. #==============================================================================
  3453. # • Sound Base
  3454. #==============================================================================
  3455. Dax.register(:sound_base)
  3456. module Sound_Base
  3457. #----------------------------------------------------------------------------
  3458. # • Função do módulo.
  3459. #----------------------------------------------------------------------------
  3460. module_function
  3461. #----------------------------------------------------------------------------
  3462. # • Executar um som.
  3463. #----------------------------------------------------------------------------
  3464. def play(name, volume, pitch, type = :se)
  3465. case type
  3466. when :se ; RPG::SE.new(name, volume, pitch).play rescue valid?(name)
  3467. when :me ; RPG::ME.new(name, volume, pitch).play rescue valid?(name)
  3468. when :bgm ; RPG::BGM.new(name, volume, pitch).play rescue valid?(name)
  3469. when :bgs ; RPG::BGS.new(name, volume, pitch).play rescue valid?(name)
  3470. end
  3471. end
  3472. #----------------------------------------------------------------------------
  3473. # • Validar som.
  3474. #----------------------------------------------------------------------------
  3475. def valid?(name)
  3476. raise("Arquivo de som não encontrado: #{name}")
  3477. exit
  3478. end
  3479. end
  3480. #==============================================================================
  3481. # • Animation
  3482. #==============================================================================
  3483. Dax.register :animation
  3484. class Animation
  3485. attr_reader :size, :frame_size, :index, :max_width, :max_height
  3486. #----------------------------------------------------------------------------
  3487. # • Inicialização.
  3488. #----------------------------------------------------------------------------
  3489. def initialize(size, frame_size, wait=1)
  3490. @size = size
  3491. @frame_size = frame_size
  3492. @index = 0
  3493. @max_width = @size[0] / @frame_size[0]
  3494. @max_height = @size[1] / @frame_size[1]
  3495. @wait = wait
  3496. @time = 0
  3497. end
  3498. #----------------------------------------------------------------------------
  3499. # • Animação na horizontal.
  3500. #----------------------------------------------------------------------------
  3501. def horz
  3502. @time += 1 unless @time >= @wait
  3503. if @time >= @wait
  3504. @index = @index.up(@index, @max_width)
  3505. @time = 0
  3506. end
  3507. end
  3508. #----------------------------------------------------------------------------
  3509. # • Animação na vertical.
  3510. #----------------------------------------------------------------------------
  3511. def vert
  3512. @time += 1 unless @time >= @wait
  3513. if @time >= @wait
  3514. @index = @index.up(@index, @max_height)
  3515. @time = 0
  3516. end
  3517. end
  3518. end
  3519. #==============================================================================
  3520. # • Sprite_Anime_Horz
  3521. #==============================================================================
  3522. Dax.register :sprite_anime_horz
  3523. class Sprite_Anime_Horz < Sprite
  3524. #----------------------------------------------------------------------------
  3525. # • Inicialização dos objetos
  3526. # filename : Nome do arquivo.
  3527. # frame_size : Tamanho de cada frame.
  3528. # wait : Tempo de espera para mudar de um frame para outro.
  3529. #----------------------------------------------------------------------------
  3530. def initialize(filename, frame_size, wait=1)
  3531. @bitmap = Bitmap.new(filename)
  3532. super(frame_size)
  3533. @animation = Animation.new([@bitmap.width, @bitmap.height],
  3534. frame_size, wait)
  3535. end
  3536. #----------------------------------------------------------------------------
  3537. # • Renovação dos objetos.
  3538. #----------------------------------------------------------------------------
  3539. def dispose
  3540. self.bitmap.dispose
  3541. super
  3542. end
  3543. #----------------------------------------------------------------------------
  3544. # • Atualização dos objetos.
  3545. #----------------------------------------------------------------------------
  3546. def update
  3547. self.bitmap.clear
  3548. super
  3549. @animation.horz
  3550. rect = Rect.new(@animation.index % @animation.max_width * @animation.frame_size[0],
  3551. 0, *@animation.frame_size)
  3552. self.bitmap.blt(0, 0, @bitmap, rect)
  3553. end
  3554. end
  3555. #==============================================================================
  3556. # • Sprite_Anime_Vert
  3557. #==============================================================================
  3558. Dax.register :sprite_anime_vert
  3559. class Sprite_Anime_Vert < Sprite
  3560. #----------------------------------------------------------------------------
  3561. # • Inicialização dos objetos
  3562. # filename : Nome do arquivo.
  3563. # frame_size : Tamanho de cada frame.
  3564. # wait : Tempo de espera para mudar de um frame para outro.
  3565. #----------------------------------------------------------------------------
  3566. def initialize(filename, frame_size, wait=1)
  3567. @bitmap = Bitmap.new(filename)
  3568. super(frame_size)
  3569. @animation = Animation.new([@bitmap.width, @bitmap.height],
  3570. frame_size, wait)
  3571. end
  3572. #----------------------------------------------------------------------------
  3573. # • Renovação dos objetos.
  3574. #----------------------------------------------------------------------------
  3575. def dispose
  3576. self.bitmap.dispose
  3577. super
  3578. end
  3579. #----------------------------------------------------------------------------
  3580. # • Atualização dos objetos.
  3581. #----------------------------------------------------------------------------
  3582. def update
  3583. self.bitmap.clear
  3584. super
  3585. @animation.vert
  3586. rect = Rect.new(0,
  3587. @animation.index % @animation.max_height * @animation.frame_size[1], *@animation.frame_size)
  3588. self.bitmap.blt(0, 0, @bitmap, rect)
  3589. end
  3590. end
  3591. #==============================================================================
  3592. # • Benchmark
  3593. #==============================================================================
  3594. Dax.register(:benchmark)
  3595. module Benchmark
  3596. extend self
  3597. #----------------------------------------------------------------------------
  3598. # • Constantes.
  3599. #----------------------------------------------------------------------------
  3600. CAPTION = " user system total real\n"
  3601. FMTSTR = "%10.6u %10.6y %10.6t %10.6r\n"
  3602. def Benchmark::times() # :nodoc:
  3603. Process::times()
  3604. end
  3605. #----------------------------------------------------------------------------
  3606. # • Método do benchmark.:.
  3607. # ** Exemplo:.:
  3608. # n = 50000
  3609. # Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x|
  3610. # tf = x.report("for:") { for i in 1..n; a = "1"; end }
  3611. # tt = x.report("times:") { n.times do ; a = "1"; end }
  3612. # tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end }
  3613. # [tf+tt+tu, (tf+tt+tu)/3]
  3614. # end
  3615. # ** Gera:.:
  3616. # user system total real
  3617. # for: 1.016667 0.016667 1.033333 ( 0.485749)
  3618. # times: 1.450000 0.016667 1.466667 ( 0.681367)
  3619. # upto: 1.533333 0.000000 1.533333 ( 0.722166)
  3620. # >total: 4.000000 0.033333 4.033333 ( 1.889282)
  3621. # >avg: 1.333333 0.011111 1.344444 ( 0.629761)
  3622. #----------------------------------------------------------------------------
  3623. def benchmark(caption = "", label_width = nil, fmtstr = nil, *labels) # :yield: report
  3624. sync = STDOUT.sync
  3625. STDOUT.sync = true
  3626. label_width ||= 0
  3627. fmtstr ||= FMTSTR
  3628. raise ArgumentError, "no block" unless iterator?
  3629. print caption
  3630. results = yield(Report.new(label_width, fmtstr))
  3631. Array === results and results.grep(Tms).each {|t|
  3632. print((labels.shift || t.label || "").ljust(label_width),
  3633. t.format(fmtstr))
  3634. }
  3635. STDOUT.sync = sync
  3636. end
  3637. #----------------------------------------------------------------------------
  3638. # • Versão simplificada para benchmark.
  3639. # ** Exemplo:.:
  3640. # n = 50000
  3641. # Benchmark.bm(7) do |x|
  3642. # x.report("for:") { for i in 1..n; a = "1"; end }
  3643. # x.report("times:") { n.times do ; a = "1"; end }
  3644. # x.report("upto:") { 1.upto(n) do ; a = "1"; end }
  3645. # end
  3646. # ** Gera:.:
  3647. # user system total real
  3648. # for: 1.050000 0.000000 1.050000 ( 0.503462)
  3649. # times: 1.533333 0.016667 1.550000 ( 0.735473)
  3650. # upto: 1.500000 0.016667 1.516667 ( 0.711239)
  3651. #----------------------------------------------------------------------------
  3652. def bm(label_width = 0, *labels, &blk) # :yield: report
  3653. benchmark(" "*label_width + CAPTION, label_width, FMTSTR, *labels, &blk)
  3654. end
  3655. #----------------------------------------------------------------------------
  3656. # • Retorna ao tempo usado para executar o bloco como um objeto Benchmark::Tms
  3657. #----------------------------------------------------------------------------
  3658. def measure(label = "") # :yield:
  3659. t0, r0 = Benchmark.times, Time.now
  3660. yield
  3661. t1, r1 = Benchmark.times, Time.now
  3662. Benchmark::Tms.new(t1.utime - t0.utime,
  3663. t1.stime - t0.stime,
  3664. t1.cutime - t0.cutime,
  3665. t1.cstime - t0.cstime,
  3666. r1.to_f - r0.to_f,
  3667. label)
  3668. end
  3669. #----------------------------------------------------------------------------
  3670. # • Retorna ao tempo real decorrido, o tempo usado para executar o bloco.
  3671. #----------------------------------------------------------------------------
  3672. def realtime(&blk) # :yield:
  3673. r0 = Time.now
  3674. yield
  3675. r1 = Time.now
  3676. r1.to_f - r0.to_f
  3677. end
  3678. #============================================================================
  3679. # • Report ::
  3680. #============================================================================
  3681. class Report
  3682. #--------------------------------------------------------------------------
  3683. # • Retorna uma instância inicializada.
  3684. # Usualmente não é bom chamar esse método diretamente.
  3685. #--------------------------------------------------------------------------
  3686. def initialize(width = 0, fmtstr = nil)
  3687. @width, @fmtstr = width, fmtstr
  3688. end
  3689. #--------------------------------------------------------------------------
  3690. # • Imprime o _label_ e o tempo marcado pelo bloco, formatado por _fmt_.
  3691. #--------------------------------------------------------------------------
  3692. def item(label = "", *fmt, &blk) # :yield:
  3693. print label.ljust(@width)
  3694. res = Benchmark::measure(&blk)
  3695. print res.format(@fmtstr, *fmt)
  3696. res
  3697. end
  3698. #--------------------------------------------------------------------------
  3699. # • Método :alias:
  3700. #--------------------------------------------------------------------------
  3701. alias :report :item
  3702. end
  3703. #============================================================================
  3704. # • Tms
  3705. #============================================================================
  3706. class Tms
  3707. #--------------------------------------------------------------------------
  3708. # • Constantes
  3709. #--------------------------------------------------------------------------
  3710. CAPTION = " user system total real\n"
  3711. FMTSTR = "%10.6u %10.6y %10.6t %10.6r\n"
  3712. #--------------------------------------------------------------------------
  3713. # • Variáveis da instância.
  3714. #--------------------------------------------------------------------------
  3715. attr_reader :utime # Tempo da CPU do Usuário.
  3716. attr_reader :stime # Tempo da CPU do Sistema.
  3717. attr_reader :cutime # Tempo da CPU do usuário-criança.
  3718. attr_reader :cstime # Tempo da CPU do sistema-criança.
  3719. attr_reader :real # Tempo real corrido.
  3720. attr_reader :total # Tempo total, que é _utime_ + _stime_ + _cutime_ + _cstime_
  3721. attr_reader :label # Label.
  3722. #--------------------------------------------------------------------------
  3723. # • Retorna ao objeto inicializado na qual tem _u_ como tempo dá CPU do
  3724. # usuário, _s_ como o tempo da CPU do sistema, _cu_ como tempo dá CPU
  3725. # do usuário-criança, _cs_ como o tempo dá CPU sistema-criança, _real_
  3726. # como o tempo real corrido e _l_ como label.
  3727. #--------------------------------------------------------------------------
  3728. def initialize(u = 0.0, s = 0.0, cu = 0.0, cs = 0.0, real = 0.0, l = nil)
  3729. @utime, @stime, @cutime, @cstime, @real, @label = u, s, cu, cs, real, l
  3730. @total = @utime + @stime + @cutime + @cstime
  3731. end
  3732. #--------------------------------------------------------------------------
  3733. # • Retorna a um novo objeto Tms, na qual os tempos são somados num todo
  3734. # pelo objeto Tms.
  3735. #--------------------------------------------------------------------------
  3736. def add(&blk) # :yield:
  3737. self + Benchmark::measure(&blk)
  3738. end
  3739. #--------------------------------------------------------------------------
  3740. # • Uma versão no lugar do método #add
  3741. #--------------------------------------------------------------------------
  3742. def add!
  3743. t = Benchmark::measure(&blk)
  3744. @utime = utime + t.utime
  3745. @stime = stime + t.stime
  3746. @cutime = cutime + t.cutime
  3747. @cstime = cstime + t.cstime
  3748. @real = real + t.real
  3749. self
  3750. end
  3751. #--------------------------------------------------------------------------
  3752. # • Soma com outro objeto do mesmo.
  3753. #--------------------------------------------------------------------------
  3754. def +(other); memberwise(:+, other) end
  3755. #--------------------------------------------------------------------------
  3756. # • Subtrai com outro objeto do mesmo.
  3757. #--------------------------------------------------------------------------
  3758. def -(other); memberwise(:-, other) end
  3759. #--------------------------------------------------------------------------
  3760. # • Multiplica com outro objeto do mesmo.
  3761. #--------------------------------------------------------------------------
  3762. def *(x); memberwise(:*, x) end
  3763. #--------------------------------------------------------------------------
  3764. # • Divide com outro objeto do mesmo.
  3765. #--------------------------------------------------------------------------
  3766. def /(x); memberwise(:/, x) end
  3767. #--------------------------------------------------------------------------
  3768. # • Retorna ao conteudo dos objetos formatados como uma string.
  3769. #--------------------------------------------------------------------------
  3770. def format(arg0 = nil, *args)
  3771. fmtstr = (arg0 || FMTSTR).dup
  3772. fmtstr.gsub!(/(%[-+\.\d]*)n/){"#{$1}s" % label}
  3773. fmtstr.gsub!(/(%[-+\.\d]*)u/){"#{$1}f" % utime}
  3774. fmtstr.gsub!(/(%[-+\.\d]*)y/){"#{$1}f" % stime}
  3775. fmtstr.gsub!(/(%[-+\.\d]*)U/){"#{$1}f" % cutime}
  3776. fmtstr.gsub!(/(%[-+\.\d]*)Y/){"#{$1}f" % cstime}
  3777. fmtstr.gsub!(/(%[-+\.\d]*)t/){"#{$1}f" % total}
  3778. fmtstr.gsub!(/(%[-+\.\d]*)r/){"(#{$1}f)" % real}
  3779. arg0 ? Kernel::format(fmtstr, *args) : fmtstr
  3780. end
  3781. #--------------------------------------------------------------------------
  3782. # • Mesmo que o método formato.
  3783. #--------------------------------------------------------------------------
  3784. def to_s
  3785. format
  3786. end
  3787. #--------------------------------------------------------------------------
  3788. # • Retorna a uma array contendo os elementos:
  3789. # @label, @utime, @stime, @cutime, @cstime, @real
  3790. #--------------------------------------------------------------------------
  3791. def to_a
  3792. [@label, @utime, @stime, @cutime, @cstime, @real]
  3793. end
  3794. protected
  3795. def memberwise(op, x)
  3796. case x
  3797. when Benchmark::Tms
  3798. Benchmark::Tms.new(utime.__send__(op, x.utime),
  3799. stime.__send__(op, x.stime),
  3800. cutime.__send__(op, x.cutime),
  3801. cstime.__send__(op, x.cstime),
  3802. real.__send__(op, x.real)
  3803. )
  3804. else
  3805. Benchmark::Tms.new(utime.__send__(op, x),
  3806. stime.__send__(op, x),
  3807. cutime.__send__(op, x),
  3808. cstime.__send__(op, x),
  3809. real.__send__(op, x)
  3810. )
  3811. end
  3812. end
  3813. CAPTION = Benchmark::Tms::CAPTION
  3814. FMTSTR = Benchmark::Tms::FMTSTR
  3815. end
  3816. end
  3817. #==============================================================================
  3818. # • Desativar scripts : Para fazer, basta por no nome do script da lista,
  3819. # [D].
  3820. # • Salvar script em arquivo de texto : Para fazer, basta por no nome do script da lista,
  3821. # [S].
  3822. #==============================================================================
  3823. Dax.register(:disable_script)
  3824. $RGSS_SCRIPTS.each_with_index { |data, index|
  3825. if data.at(1).include?("[S]")
  3826. File.open("#{rgss.at(1)}.txt", "wb") { |file|
  3827. file.write(String($RGSS_SCRIPTS.at(index)[3]))
  3828. file.close
  3829. }
  3830. end
  3831. $RGSS_SCRIPTS.at(index)[2] = $RGSS_SCRIPTS.at(index)[3] = "" if data.at(1).include?("[D]")
  3832. }
  3833. #==============================================================================
  3834. # * Input
  3835. #==============================================================================
  3836. class << Input
  3837. alias :upft :update
  3838. def update
  3839. upft
  3840. Key.update
  3841. end
  3842. end
  3843. #==============================================================================
  3844. # • Graphics
  3845. #==============================================================================
  3846. class << Graphics
  3847. attr_reader :fps
  3848. alias :uptf :update
  3849. def update
  3850. @fps ||= 0
  3851. @fps_temp ||= []
  3852. time = Time.now
  3853. uptf
  3854. Mouse.update
  3855. @fps_temp[frame_count % frame_rate] = Time.now != time
  3856. @fps = 0
  3857. frame_rate.times { |i| @fps += 1 if @fps_temp[i] }
  3858. end
  3859. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement