Advertisement
DaxSoft

Dax Core i4.2

Sep 29th, 2014
397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 151.64 KB | None | 0 0
  1. #==============================================================================
  2. # * Dax Core
  3. #==============================================================================
  4. # Autor : Dax Aquatic X
  5. # Versão : Core i4.2
  6. # Site : www.dax-soft.weebly.com
  7. # Suporte : dax-soft@live.com
  8. #==============================================================================
  9. # Um Core com vários módulos e métodos que facilitará na hora de programar os
  10. # seus scripts, bom proveito.
  11. #==============================================================================
  12. # Conteúdo : • TAGS : Para facilitar a localização dos códigos e explicações. Para acessar
  13. # o comando para localizar, basta apertar Ctrl+F.
  14. #==============================================================================
  15. # i :
  16. # - Array :array
  17. # - Api :api
  18. # - String :string
  19. # - Integer :integer
  20. # - Numeric :numeric
  21. # - Color :color
  22. # - Rect :rect
  23. # - DMath :dmath
  24. # - Key :key
  25. # - Sprite :sprite
  26. # - Bitmap :bitmap (Método #save por Gab! -> Créditos a ele)
  27. # - Mouse :mouse
  28. # - Sprite_Mouse :sprite_mouse
  29. # - Object :object
  30. # - Entries :entries
  31. # - DRGSS :drgss
  32. # - Backup :backup
  33. # - SceneManager :scenemanager
  34. # - Sprite_Text :sprite_text
  35. # - Sprite_Icon :sprite_icon
  36. # - Opacity :opacity
  37. # - Read :read
  38. # - Background :background
  39. # - Window_Base :window_base
  40. # - Sound_Base :sound_base
  41. # - Position :position
  42. # - Animation :animation
  43. # - Sprite_Anime_Horz :sprite_anime_horz
  44. # - Sprite_Anime_Vert :sprite_anime_vert
  45. #==============================================================================
  46. # • Adicionado comentário padrão. Veja o modo que agora os comentários dos
  47. # métodos estão.
  48. #==============================================================================
  49. # • [Classe do Retorno] : Explicação.
  50. # * Exemplo.(Se possível.)
  51. #==============================================================================
  52. module Dax
  53. extend self
  54. #----------------------------------------------------------------------------
  55. # • Constantes
  56. #----------------------------------------------------------------------------
  57. # A imagem do ícone do Mouse tem que estar na pasta [System]. Basta você
  58. # por o nome da imagem dentro das áspas. Caso você queira usar um ícone
  59. # do Rpg Maker no lugar de uma imagem, basta você por o id do ícone no lugar
  60. # das áspas.
  61. Mouse_Name = ""
  62. #----------------------------------------------------------------------------
  63. # • Variáveis
  64. #----------------------------------------------------------------------------
  65. @register = { } # Variável útilizada para registrar os scripts que fora criado.
  66. @benchmark = "" # Armazena os testes conclusos de benchmark.
  67. #----------------------------------------------------------------------------
  68. # • Método de registrar scripts :
  69. #----------------------------------------------------------------------------
  70. # ** Este método tem de ser definido alguns valores como :
  71. # symbol - nome do script, que é posto em símbolo : Ex - :arrow
  72. # name - nome do autor do script, que é posto em áspas
  73. # version - versão do script;
  74. # data - data do script;
  75. # Dax.register(symbol, name, version, data)
  76. # ** Você pode usá-lo para somente registrar o nome do script.
  77. # Dax.register(symbol)
  78. #----------------------------------------------------------------------------
  79. def register(*args)
  80. if @register.has_key?(args[0])
  81. @register[args[0]][:version] = args[1]
  82. @register[args[0]][:data] = args[2]
  83. else
  84. @register[args[0]] = {name: args[1], version: args[2], data: args[3], script: nil}
  85. end
  86. end
  87. #----------------------------------------------------------------------------
  88. # • Somente executará o bloco caso estiver registrado o script. Compatível
  89. # com o $imported. Caso não esteja registrado no Core e esteja registrado
  90. # na variável $imported, dará!
  91. #----------------------------------------------------------------------------
  92. # Exemplo:
  93. # Dax.required_script(:teste) { # Só irá executar caso estiver registrado.
  94. # methods...
  95. # }
  96. #----------------------------------------------------------------------------
  97. def required_script(symbol, &block)
  98. return unless block_given?
  99. block.call if @register.has_key?(symbol) or $imported.has_key?(symbol)
  100. end
  101. #----------------------------------------------------------------------------
  102. # • Método de verificar se o objeto existe.
  103. #----------------------------------------------------------------------------
  104. # Dax.if_defined?("Objeto") { }
  105. # Dentro das chaves você poem o script.
  106. # * Exemplo :
  107. # Dax.required_class("Window_Base") {
  108. # class Window_Base < Window
  109. # def example
  110. # self.x = self.x + self.width
  111. # end
  112. # end
  113. # }
  114. #----------------------------------------------------------------------------
  115. # Executa o bloco se o objeto existir.
  116. #----------------------------------------------------------------------------
  117. def if_defined?(name, &block)
  118. return unless defined?(name)
  119. eval("block.call if defined?(name)")
  120. end
  121. #----------------------------------------------------------------------------
  122. # • Fazer benchmark de um bloco. O resultado será impresso no Console do
  123. # Maker.
  124. #----------------------------------------------------------------------------
  125. # Dax.benchmark(name(opcional)) { BLOCO }
  126. #----------------------------------------------------------------------------
  127. def benchmark(name="", &block)
  128. time = Time.now
  129. block.call
  130. print "Benchmark: #{(time - Time.now).abs.to_f} segundos!\r\n"
  131. @benchmark += "#{name} : #{(time - Time.now).to_f} segundos!\r\n"
  132. end
  133. #----------------------------------------------------------------------------
  134. # • Salva os testes de benchmark num arquivo chamado 'Benchmark' de extensão
  135. # .txt.
  136. #----------------------------------------------------------------------------
  137. def benchmark_save
  138. self.required_file("Benchmark.txt") { File.delete("Benchmark.txt") }
  139. File.open("Benchmark.txt", "a+") do |file|
  140. file.write(@benchmark)
  141. file.close
  142. end
  143. end
  144. #----------------------------------------------------------------------------
  145. # • Requirir um arquivo.
  146. # arquivo : Arquivo...
  147. #----------------------------------------------------------------------------
  148. def require(arquivo)
  149. $: << "./"
  150. Kernel.send(:require, arquivo)
  151. end
  152. #----------------------------------------------------------------------------
  153. # • Somente executa um bloco case existir um arquivo.
  154. #----------------------------------------------------------------------------
  155. # Dax.required_file("arquivo.tipo") { # Exemplo.
  156. # Métodos;
  157. # }
  158. #----------------------------------------------------------------------------
  159. def required_file(filename, &block)
  160. return unless FileTest.exist?(filename)
  161. block.call
  162. end
  163. #----------------------------------------------------------------------------
  164. # • Somente executa um bloco case existir uma pasta.
  165. #----------------------------------------------------------------------------
  166. # Dax.required_dir("arquivo.tipo") { # Exemplo.
  167. # Métodos;
  168. # }
  169. #----------------------------------------------------------------------------
  170. def required_dir(directory, &block)
  171. return unless File.directory?(directory) and block_given?
  172. block.call
  173. end
  174. #----------------------------------------------------------------------------
  175. # * Remove uma [Classe], exemplo: Dax.remove(:Scene_Menu)
  176. #----------------------------------------------------------------------------
  177. def remove(symbol_name)
  178. Object.send(:remove_const, symbol_name)
  179. end
  180. #----------------------------------------------------------------------------
  181. # • Tela chéia
  182. #----------------------------------------------------------------------------
  183. def full_screen
  184. res = Win32API.new 'user32', 'keybd_event', %w(l l l l), ''
  185. res.call(18,0,0,0)
  186. res.call(13,0,0,0)
  187. res.call(13,0,2,0)
  188. res.call(18,0,2,0)
  189. end
  190. end
  191. #==============================================================================
  192. # • Array
  193. #==============================================================================
  194. Dax.register :array
  195. class Array
  196. #----------------------------------------------------------------------------
  197. # • [Array] Retorna ao elemento da array que condiz com a condição
  198. # definida no bloco.
  199. # Exemplo:
  200. # [2, 4, 5, 6, 8].rIf { |element| element >= 4 }
  201. # # 5, 6, 8
  202. #----------------------------------------------------------------------------
  203. def rIf
  204. return unless block_given?
  205. getResult ||= []
  206. self.each_with_index{ |arrays|
  207. getResult << arrays if yield(arrays)
  208. }
  209. return getResult
  210. end
  211. #----------------------------------------------------------------------------
  212. # • [Mixed] : Retorna ao primeiro valor da array, que obedeça a
  213. # condição posta.
  214. # msgbox [2, 3, 4, 5, 6].first! { |n| n.is_evan? } #> 2
  215. # msgbox [2, 3, 4, 5, 6].first! { |n| n.is_odd? } #> 3
  216. #----------------------------------------------------------------------------
  217. def first!
  218. return unless block_given?
  219. return self.each { |element| return element if yield(element) }.at(0)
  220. end
  221. end
  222. #==============================================================================
  223. # • API : Módulo que armazena informações de algumas APIS.
  224. #==============================================================================
  225. module API
  226. extend self
  227. #----------------------------------------------------------------------------
  228. # • [String] : Tipos e seus retornos.. Pegado da internet.. Autor desconhecido
  229. #----------------------------------------------------------------------------
  230. TYPES = {
  231. struct: "p",
  232. int: "i",
  233. long: "l",
  234. INTERNET_PORT: "l",
  235. SOCKET: "p",
  236. C: "p", #– 8-bit unsigned character (byte)
  237. c: "p", # 8-bit character (byte)
  238. # "i"8 – 8-bit signed integer
  239. # "i"8 – 8-bit unsigned integer
  240. S: "N", # – 16-bit unsigned integer (Win32/API: S used for string params)
  241. s: "n", # – 16-bit signed integer
  242. # "i"16 – 16-bit unsigned integer
  243. # "i"16 – 16-bit signed integer
  244. I: "I", # 32-bit unsigned integer
  245. i: "i", # 32-bit signed integer
  246. # "i"32 – 32-bit unsigned integer
  247. # "i"32 – 32-bit signed integer
  248. L: "L", # unsigned long int – platform-specific size
  249. l: "l", # long int – platform-specific size. For discussion of platforms, see:
  250. # (http://groups.google.com/group/ruby-ffi/browse_thread/thread/4762fc77130339b1)
  251. # "i"64 – 64-bit signed integer
  252. # "i"64 – 64-bit unsigned integer
  253. # "l"_long – 64-bit signed integer
  254. # "l"_long – 64-bit unsigned integer
  255. F: "L", # 32-bit floating point
  256. D: "L", # 64-bit floating point (double-precision)
  257. P: "P", # pointer – platform-specific size
  258. p: "p", # C-style (NULL-terminated) character string (Win32API: S)
  259. B: "i", # (?? 1 byte in C++)
  260. V: "V", # For functions that return nothing (return type void).
  261. v: "v", # For functions that return nothing (return type void).
  262. # For function argument type only:
  263. # :buffer_in – Similar to "l", but optimized for Buffers that the function can only read (not write).
  264. # :buffer_out – Similar to "l", but optimized for Buffers that the function can only write (not read).
  265. # :buffer_inout – Similar to "l", but may be optimized for Buffers.
  266. # :varargs – Variable arguments
  267. # :enum - Enumerable type (should be defined)
  268. # "p"_array - ??
  269.  
  270. # Windows-specific type defs (ms-help://MS.MSDNQTR.v90.en/winprog/winprog/windows_data_types.htm):
  271. ATOM: "I", # Atom ~= Symbol: Atom table stores strings and corresponding identifiers. Application
  272. # places a string in an atom table and receives a 16-bit integer, called an atom, that
  273. # can be used to access the string. Placed string is called an atom name.
  274. # See: http://msdn.microsoft.com/en-us/library/ms648708%28VS.85%29.aspx
  275. BOOL: "i",
  276. BOOLEAN: "i",
  277. BYTE: "p", # Byte (8 bits). Declared as unsigned char
  278. #CALLBACK: K, # Win32.API gem-specific ?? MSDN: #define CALLBACK __stdcall
  279. CHAR: "p", # 8-bit Windows (ANSI) character. See http://msdn.microsoft.com/en-us/library/dd183415%28VS.85%29.aspx
  280. COLORREF: "i", # Red, green, blue (RGB) color value (32 bits). See COLORREF for more info.
  281. DWORD: "i", # 32-bit unsigned integer. The range is 0 through 4,294,967,295 decimal.
  282. DWORDLONG: "i", # 64-bit unsigned integer. The range is 0 through 18,446,744,073,709,551,615 decimal.
  283. DWORD_PTR: "l", # Unsigned long type for pointer precision. Use when casting a pointer to a long type
  284. # to perform pointer arithmetic. (Also commonly used for general 32-bit parameters that have
  285. # been extended to 64 bits in 64-bit Windows.) BaseTsd.h: #typedef ULONG_PTR DWORD_PTR;
  286. DWORD32: "I",
  287. DWORD64: "I",
  288. HALF_PTR: "i", # Half the size of a pointer. Use within a structure that contains a pointer and two small fields.
  289. # BaseTsd.h: #ifdef (_WIN64) typedef int HALF_PTR; #else typedef short HALF_PTR;
  290. HACCEL: "i", # (L) Handle to an accelerator table. WinDef.h: #typedef HANDLE HACCEL;
  291. # See http://msdn.microsoft.com/en-us/library/ms645526%28VS.85%29.aspx
  292. HANDLE: "l", # (L) Handle to an object. WinNT.h: #typedef PVOID HANDLE;
  293. # todo: Platform-dependent! Need to change to "i"64 for Win64
  294. HBITMAP: "l", # (L) Handle to a bitmap: http://msdn.microsoft.com/en-us/library/dd183377%28VS.85%29.aspx
  295. HBRUSH: "l", # (L) Handle to a brush. http://msdn.microsoft.com/en-us/library/dd183394%28VS.85%29.aspx
  296. HCOLORSPACE: "l", # (L) Handle to a color space. http://msdn.microsoft.com/en-us/library/ms536546%28VS.85%29.aspx
  297. HCURSOR: "l", # (L) Handle to a cursor. http://msdn.microsoft.com/en-us/library/ms646970%28VS.85%29.aspx
  298. HCONV: "l", # (L) Handle to a dynamic data exchange (DDE) conversation.
  299. HCONVLIST: "l", # (L) Handle to a DDE conversation list. HANDLE - L ?
  300. HDDEDATA: "l", # (L) Handle to DDE data (structure?)
  301. HDC: "l", # (L) Handle to a device context (DC). http://msdn.microsoft.com/en-us/library/dd183560%28VS.85%29.aspx
  302. HDESK: "l", # (L) Handle to a desktop. http://msdn.microsoft.com/en-us/library/ms682573%28VS.85%29.aspx
  303. HDROP: "l", # (L) Handle to an internal drop structure.
  304. HDWP: "l", # (L) Handle to a deferred window position structure.
  305. HENHMETAFILE: "l", #(L) Handle to an enhanced metafile. http://msdn.microsoft.com/en-us/library/dd145051%28VS.85%29.aspx
  306. HFILE: "i", # (I) Special file handle to a file opened by OpenFile, not CreateFile.
  307. # WinDef.h: #typedef int HFILE;
  308. HFONT: "l", # (L) Handle to a font. http://msdn.microsoft.com/en-us/library/dd162470%28VS.85%29.aspx
  309. HGDIOBJ: "l", # (L) Handle to a GDI object.
  310. HGLOBAL: "l", # (L) Handle to a global memory block.
  311. HHOOK: "l", # (L) Handle to a hook. http://msdn.microsoft.com/en-us/library/ms632589%28VS.85%29.aspx
  312. HICON: "l", # (L) Handle to an icon. http://msdn.microsoft.com/en-us/library/ms646973%28VS.85%29.aspx
  313. HINSTANCE: "l", # (L) Handle to an instance. This is the base address of the module in memory.
  314. # HMODULE and HINSTANCE are the same today, but were different in 16-bit Windows.
  315. HKEY: "l", # (L) Handle to a registry key.
  316. HKL: "l", # (L) Input locale identifier.
  317. HLOCAL: "l", # (L) Handle to a local memory block.
  318. HMENU: "l", # (L) Handle to a menu. http://msdn.microsoft.com/en-us/library/ms646977%28VS.85%29.aspx
  319. HMETAFILE: "l", # (L) Handle to a metafile. http://msdn.microsoft.com/en-us/library/dd145051%28VS.85%29.aspx
  320. HMODULE: "l", # (L) Handle to an instance. Same as HINSTANCE today, but was different in 16-bit Windows.
  321. HMONITOR: "l", # (L) ?andle to a display monitor. WinDef.h: if(WINVER >= 0x0500) typedef HANDLE HMONITOR;
  322. HPALETTE: "l", # (L) Handle to a palette.
  323. HPEN: "l", # (L) Handle to a pen. http://msdn.microsoft.com/en-us/library/dd162786%28VS.85%29.aspx
  324. HRESULT: "l", # Return code used by COM interfaces. For more info, Structure of the COM Error Codes.
  325. # To test an HRESULT value, use the FAILED and SUCCEEDED macros.
  326. HRGN: "l", # (L) Handle to a region. http://msdn.microsoft.com/en-us/library/dd162913%28VS.85%29.aspx
  327. HRSRC: "l", # (L) Handle to a resource.
  328. HSZ: "l", # (L) Handle to a DDE string.
  329. HWINSTA: "l", # (L) Handle to a window station. http://msdn.microsoft.com/en-us/library/ms687096%28VS.85%29.aspx
  330. HWND: "l", # (L) Handle to a window. http://msdn.microsoft.com/en-us/library/ms632595%28VS.85%29.aspx
  331. INT: "i", # 32-bit signed integer. The range is -2147483648 through 2147483647 decimal.
  332. INT_PTR: "i", # Signed integer type for pointer precision. Use when casting a pointer to an integer
  333. # to perform pointer arithmetic. BaseTsd.h:
  334. #if defined(_WIN64) typedef __int64 INT_PTR; #else typedef int INT_PTR;
  335. INT32: "i", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
  336. INT64: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
  337. LANGID: "n", # Language identifier. For more information, see Locales. WinNT.h: #typedef WORD LANGID;
  338. # See http://msdn.microsoft.com/en-us/library/dd318716%28VS.85%29.aspx
  339. LCID: "i", # Locale identifier. For more information, see Locales.
  340. LCTYPE: "i", # Locale information type. For a list, see Locale Information Constants.
  341. LGRPID: "i", # Language group identifier. For a list, see EnumLanguageGroupLocales.
  342. LONG: "l", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
  343. LONG32: "i", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
  344. LONG64: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
  345. LONGLONG: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
  346. LONG_PTR: "l", # Signed long type for pointer precision. Use when casting a pointer to a long to
  347. # perform pointer arithmetic. BaseTsd.h:
  348. #if defined(_WIN64) typedef __int64 LONG_PTR; #else typedef long LONG_PTR;
  349. LPARAM: "l", # Message parameter. WinDef.h as follows: #typedef LONG_PTR LPARAM;
  350. LPBOOL: "i", # Pointer to a BOOL. WinDef.h as follows: #typedef BOOL far *LPBOOL;
  351. LPBYTE: "i", # Pointer to a BYTE. WinDef.h as follows: #typedef BYTE far *LPBYTE;
  352. LPCSTR: "p", # Pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters.
  353. # See Character Sets Used By Fonts. http://msdn.microsoft.com/en-us/library/dd183415%28VS.85%29.aspx
  354. LPCTSTR: "p", # An LPCWSTR if UNICODE is defined, an LPCSTR otherwise.
  355. LPCVOID: "v", # Pointer to a constant of any type. WinDef.h as follows: typedef CONST void *LPCVOID;
  356. LPCWSTR: "P", # Pointer to a constant null-terminated string of 16-bit Unicode characters.
  357. LPDWORD: "p", # Pointer to a DWORD. WinDef.h as follows: typedef DWORD *LPDWORD;
  358. LPHANDLE: "l", # Pointer to a HANDLE. WinDef.h as follows: typedef HANDLE *LPHANDLE;
  359. LPINT: "I", # Pointer to an INT.
  360. LPLONG: "L", # Pointer to an LONG.
  361. LPSTR: "p", # Pointer to a null-terminated string of 8-bit Windows (ANSI) characters.
  362. LPTSTR: "p", # An LPWSTR if UNICODE is defined, an LPSTR otherwise.
  363. LPVOID: "v", # Pointer to any type.
  364. LPWORD: "p", # Pointer to a WORD.
  365. LPWSTR: "p", # Pointer to a null-terminated string of 16-bit Unicode characters.
  366. LRESULT: "l", # Signed result of message processing. WinDef.h: typedef LONG_PTR LRESULT;
  367. PBOOL: "i", # Pointer to a BOOL.
  368. PBOOLEAN: "i", # Pointer to a BOOL.
  369. PBYTE: "i", # Pointer to a BYTE.
  370. PCHAR: "p", # Pointer to a CHAR.
  371. PCSTR: "p", # Pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters.
  372. PCTSTR: "p", # A PCWSTR if UNICODE is defined, a PCSTR otherwise.
  373. PCWSTR: "p", # Pointer to a constant null-terminated string of 16-bit Unicode characters.
  374. PDWORD: "p", # Pointer to a DWORD.
  375. PDWORDLONG: "L", # Pointer to a DWORDLONG.
  376. PDWORD_PTR: "L", # Pointer to a DWORD_PTR.
  377. PDWORD32: "L", # Pointer to a DWORD32.
  378. PDWORD64: "L", # Pointer to a DWORD64.
  379. PFLOAT: "L", # Pointer to a FLOAT.
  380. PHALF_PTR: "L", # Pointer to a HALF_PTR.
  381. PHANDLE: "L", # Pointer to a HANDLE.
  382. PHKEY: "L", # Pointer to an HKEY.
  383. PINT: "i", # Pointer to an INT.
  384. PINT_PTR: "i", # Pointer to an INT_PTR.
  385. PINT32: "i", # Pointer to an INT32.
  386. PINT64: "i", # Pointer to an INT64.
  387. PLCID: "l", # Pointer to an LCID.
  388. PLONG: "l", # Pointer to a LONG.
  389. PLONGLONG: "l", # Pointer to a LONGLONG.
  390. PLONG_PTR: "l", # Pointer to a LONG_PTR.
  391. PLONG32: "l", # Pointer to a LONG32.
  392. PLONG64: "l", # Pointer to a LONG64.
  393. 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.
  394. 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.
  395. POINTER_SIGNED: "l", # A signed pointer.
  396. HPSS: "l",
  397. POINTER_UNSIGNED: "l", # An unsigned pointer.
  398. PSHORT: "l", # Pointer to a SHORT.
  399. PSIZE_T: "l", # Pointer to a SIZE_T.
  400. PSSIZE_T: "l", # Pointer to a SSIZE_T.
  401. PSS_CAPTURE_FLAGS: "l",
  402. PSTR: "p", # Pointer to a null-terminated string of 8-bit Windows (ANSI) characters. For more information, see Character Sets Used By Fonts.
  403. PTBYTE: "p", # Pointer to a TBYTE.
  404. PTCHAR: "p", # Pointer to a TCHAR.
  405. PTSTR: "p", # A PWSTR if UNICODE is defined, a PSTR otherwise.
  406. PUCHAR: "p", # Pointer to a UCHAR.
  407. PUINT: "i", # Pointer to a UINT.
  408. PUINT_PTR: "i", # Pointer to a UINT_PTR.
  409. PUINT32: "i", # Pointer to a UINT32.
  410. PUINT64: "i", # Pointer to a UINT64.
  411. PULONG: "l", # Pointer to a ULONG.
  412. PULONGLONG: "l", # Pointer to a ULONGLONG.
  413. PULONG_PTR: "l", # Pointer to a ULONG_PTR.
  414. PULONG32: "l", # Pointer to a ULONG32.
  415. PULONG64: "l", # Pointer to a ULONG64.
  416. PUSHORT: "l", # Pointer to a USHORT.
  417. PVOID: "v", # Pointer to any type.
  418. PWCHAR: "p", # Pointer to a WCHAR.
  419. PWORD: "p", # Pointer to a WORD.
  420. PWSTR: "p", # Pointer to a null- terminated string of 16-bit Unicode characters.
  421. # For more information, see Character Sets Used By Fonts.
  422. SC_HANDLE: "l", # (L) Handle to a service control manager database.
  423. SERVICE_STATUS_HANDLE: "l", # (L) Handle to a service status value. See SCM Handles.
  424. SHORT: "i", # A 16-bit integer. The range is –32768 through 32767 decimal.
  425. 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.
  426. SSIZE_T: "l", # Signed SIZE_T.
  427. TBYTE: "p", # A WCHAR if UNICODE is defined, a CHAR otherwise.TCHAR:
  428. # http://msdn.microsoft.com/en-us/library/c426s321%28VS.80%29.aspx
  429. TCHAR: "p", # A WCHAR if UNICODE is defined, a CHAR otherwise.TCHAR:
  430. UCHAR: "p", # Unsigned CHAR (8 bit)
  431. UHALF_PTR: "i", # Unsigned HALF_PTR. Use within a structure that contains a pointer and two small fields.
  432. UINT: "i", # Unsigned INT. The range is 0 through 4294967295 decimal.
  433. UINT_PTR: "i", # Unsigned INT_PTR.
  434. UINT32: "i", # Unsigned INT32. The range is 0 through 4294967295 decimal.
  435. UINT64: "i", # Unsigned INT64. The range is 0 through 18446744073709551615 decimal.
  436. ULONG: "l", # Unsigned LONG. The range is 0 through 4294967295 decimal.
  437. ULONGLONG: "l", # 64-bit unsigned integer. The range is 0 through 18446744073709551615 decimal.
  438. ULONG_PTR: "l", # Unsigned LONG_PTR.
  439. ULONG32: "i", # Unsigned INT32. The range is 0 through 4294967295 decimal.
  440. ULONG64: "i", # Unsigned LONG64. The range is 0 through 18446744073709551615 decimal.
  441. UNICODE_STRING: "P", # Pointer to some string structure??
  442. USHORT: "i", # Unsigned SHORT. The range is 0 through 65535 decimal.
  443. USN: "l", # Update sequence number (USN).
  444. WCHAR: "i", # 16-bit Unicode character. For more information, see Character Sets Used By Fonts.
  445. # In WinNT.h: typedef wchar_t WCHAR;
  446. #WINAPI: K, # Calling convention for system functions. WinDef.h: define WINAPI __stdcall
  447. WORD: "i", # 16-bit unsigned integer. The range is 0 through 65535 decimal.
  448. WPARAM: "i", # Message parameter. WinDef.h as follows: typedef UINT_PTR WPARAM;
  449. VOID: "v", # Any type ? Only use it to indicate no arguments or no return value
  450. vKey: "i",
  451. LPRECT: "p",
  452. }
  453. #----------------------------------------------------------------------------
  454. # • [Array] : Pega os valores especificados no método.. depois verifica
  455. # cada um se é String ou Symbol. Se for Symbol retorna ao valor especificado
  456. # na Constante TYPES.
  457. # Exemplo: types([:BOOL, :WCHAR]) # ["i", "i"]
  458. #----------------------------------------------------------------------------
  459. def types(import)
  460. import2 = []
  461. import.each { |i|
  462. next if i.is_a?(NilClass) or i.is_a?(String)
  463. import2 << TYPES[i]
  464. }
  465. return import2
  466. end
  467. #----------------------------------------------------------------------------
  468. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  469. # Por padrão a DLL é a "user32". O valor de exportação será "i"
  470. #----------------------------------------------------------------------------
  471. def int(function, import, dll="user32")
  472. Win32API.new(dll, function, types(import), "i") rescue nil
  473. end
  474. #----------------------------------------------------------------------------
  475. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  476. # Por padrão a DLL é a "user32". O valor de exportação será "l"
  477. #----------------------------------------------------------------------------
  478. def long(function, import, dll="user32")
  479. Win32API.new(dll, function.to_s, types(import), "l") rescue nil
  480. end
  481. #----------------------------------------------------------------------------
  482. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  483. # Por padrão a DLL é a "user32". O valor de exportação será "v"
  484. #----------------------------------------------------------------------------
  485. def void(function, import, dll="user32")
  486. Win32API.new(dll, function.to_s, types(import), "v") rescue nil
  487. end
  488. #----------------------------------------------------------------------------
  489. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  490. # Por padrão a DLL é a "user32". O valor de exportação será "p"
  491. #----------------------------------------------------------------------------
  492. def char(function, import, dll="user32")
  493. Win32API.new(dll, function.to_s, types(import), "p") rescue nil
  494. end
  495. #----------------------------------------------------------------------------
  496. # • [Dll]// : Com esse método você pode especificar uma função de uma Dll.
  497. # function(export, function, import, dll)
  498. # export : Valor da exportação. Formato [Symbol]
  499. # function : Função da Dll.
  500. # import : Valor da importação.
  501. # dll : Dll. Por padrão é a User32
  502. # Esconder o Mouse.
  503. # Exemplo: function(:int, "ShowCursor", [:BOOL]).call(0)
  504. #----------------------------------------------------------------------------
  505. def function(export, function, import, dll="user32")
  506. eval("#{export}(function, import, dll)")
  507. end
  508. #----------------------------------------------------------------------------
  509. # • Especificando o método protegido.
  510. #----------------------------------------------------------------------------
  511. # Métodos privados.
  512. private :long, :int, :char, :void, :types
  513. #----------------------------------------------------------------------------
  514. # • [CopyFile]/Dll : Função da DLL Kernel32 que permite copiar arquivos.
  515. # CopyFile.call(filename_to_copy, filename_copied, replace)
  516. # filename_to_copy : Formato [String]
  517. # filename_copied : Formato [String]
  518. # replace : Formato [Integer] 0 - false 1 - true
  519. # Exemplo: CopyFile.call("System/RGSS300.dll", "./RGSS300.dll", 1)
  520. #----------------------------------------------------------------------------
  521. CopyFile = Win32API.new('kernel32', 'CopyFile', 'ppl', 'l')
  522. #----------------------------------------------------------------------------
  523. # • [Beep]/Dll : Emitir uma frequência de um som do sistema com duração.
  524. # Beep.call(freq, duration)
  525. # freq : Formato [Integer\Hexadécimal]
  526. # duration : Formato [Integer\Hexadécimal]
  527. # Exemplo: Beep.call(2145, 51)
  528. #----------------------------------------------------------------------------
  529. Beep = Win32API.new('kernel32', 'Beep', 'LL', 'L')
  530. #----------------------------------------------------------------------------
  531. # • [keybd_event]/Dll : Ela é usada para sintentizar uma combinação de teclas.
  532. # KEYBD_EVENT.call(vk, scan, fdwFlags, dwExtraInfo)
  533. # vk : Formato [Integer/Hexadécimal].
  534. # scan : Formato [Integer]
  535. # fdwFlags : Formato [Integer]
  536. # dwExtraInfo : Formato [Integer]
  537. # Exemplo: KEYBD_EVENT.call(0x01, 0, 0, 0)
  538. #----------------------------------------------------------------------------
  539. KEYBD_EVENT = Win32API.new('user32', 'keybd_event', 'LLLL', '')
  540. #----------------------------------------------------------------------------
  541. # • [GetKeyState]/Dll : Pega o status da chave.
  542. # GetKeyState.call(vk)
  543. # vk : Formato [Integer/Hexadécimal].
  544. # Exemplo: GetKeyState.call(0x01)
  545. #----------------------------------------------------------------------------
  546. GetKeyState = Win32API.new('user32', 'GetAsyncKeyState', 'i', 'i')
  547. #----------------------------------------------------------------------------
  548. # • [MouseShowCursor]/Dll : Mostrar ou desativar o cusor do Mouse.
  549. # MouseShowCursor.call(value)
  550. # value : Formato [Integer] 0 - false 1 - true
  551. # Exemplo: MouseShowCursor.call(0)
  552. #----------------------------------------------------------------------------
  553. MouseShowCursor = Win32API.new("user32", "ShowCursor", "i", "i")
  554. #----------------------------------------------------------------------------
  555. # • [CursorPosition]/Dll : Obtem a posição do cursor do Mouse na tela.
  556. # CursorPosition.call(lpPoint)
  557. # lpPoint : Formato [Array]
  558. # Ex: CursorPosition.call([0, 0].pack('ll'))
  559. #----------------------------------------------------------------------------
  560. CursorPosition = Win32API.new('user32', 'GetCursorPos', 'p', 'i')
  561. #----------------------------------------------------------------------------
  562. # • [ScreenToClient]/Dll : Converte as coordenadas da tela para um ponto
  563. # em especifico da área da tela do cliente.
  564. # ScreenToClient.call(hWnd, lpPoint)
  565. #----------------------------------------------------------------------------
  566. ScreenToClient = Win32API.new('user32', 'ScreenToClient', 'lp', 'i')
  567. #----------------------------------------------------------------------------
  568. # • [ReadIni]/Dll : */Ainda não explicado./*
  569. #----------------------------------------------------------------------------
  570. ReadIni = Win32API.new('kernel32', 'GetPrivateProfileStringA', %w(p p p p l p), 'l')
  571. #----------------------------------------------------------------------------
  572. # • [FindWindow]/Dll : Recupera o identificador da janela superior. Cujo
  573. # o nome da janela é o nome da classe da janela se combina com as cadeias
  574. # especificas.
  575. # FindWindow.call(lpClassName, lpWindowName)
  576. # lpClassName : Formato [String]
  577. # lpWindowName : Formato [String]
  578. #----------------------------------------------------------------------------
  579. FindWindow = Win32API.new('user32', 'FindWindowA', %w(p p), 'l')
  580. #----------------------------------------------------------------------------
  581. # • [Handle]/Dll : Retorna ao Handle da janela.
  582. #----------------------------------------------------------------------------
  583. def hWND
  584. return API::FindWindow.call('RGSS Player', load_data("./Data/System.rvdata2").game_title.to_s)
  585. end
  586. #----------------------------------------------------------------------------
  587. # • [Handle]/Dll : Retorna ao Handle da janela. Método protegido.
  588. #----------------------------------------------------------------------------
  589. def hwnd
  590. hWND
  591. end
  592. #----------------------------------------------------------------------------
  593. # • [GetPrivateProfileString]/Dll : */Ainda não explicado./*
  594. #----------------------------------------------------------------------------
  595. GetPrivateProfileString = Win32API.new('kernel32', 'GetPrivateProfileStringA',%w(p p p p l p),'l')
  596. #----------------------------------------------------------------------------
  597. # • [SetWindowPos]/Dll : Modifica os elementos da janela como, posição, tamanho.
  598. #----------------------------------------------------------------------------
  599. SetWindowPos = Win32API.new("user32", "SetWindowPos", "lliiiii", "i")
  600. #----------------------------------------------------------------------------
  601. # • [GetWindowRect]/Dll : Obtem as dimensões do retângulo da janela.
  602. # GetWindowRect.call(hWnd, lpRect)
  603. #----------------------------------------------------------------------------
  604. GetWindowRect = Win32API.new('user32','GetWindowRect',%w(l p),'i')
  605. #----------------------------------------------------------------------------
  606. # • [StateKey]/Dll : Retorna ao status específico da chave.
  607. # StateKey.call(VK)
  608. # VK : Formato [Integer/Hexadécimal].
  609. #----------------------------------------------------------------------------
  610. StateKey = Win32API.new("user32", "GetKeyState", ["i"], "i")
  611. #----------------------------------------------------------------------------
  612. # • [SetCursorPos]/Dll : Move o cursor do Mouse para um ponto específico
  613. # da tela.
  614. # SetCursorPos.call(x, y)
  615. # x, y : Formato [Integer/Float]
  616. #----------------------------------------------------------------------------
  617. SetCursorPos = Win32API.new("user32", "SetCursorPos", "ll", "i")
  618. #----------------------------------------------------------------------------
  619. # • [GetKeyboardState]/Dll : Cópia o status das 256 chaves para um
  620. # buffer especificado.
  621. #----------------------------------------------------------------------------
  622. GetKeyboardState = Win32API.new('user32', 'GetKeyboardState', ['P'], 'V')
  623. #----------------------------------------------------------------------------
  624. # • [GetAsyncKeyState]/Dll : Determina o estado da chave no momento em que a
  625. # função é chamada.
  626. # GetAsyncKeyState.call(Vk)
  627. # VK : Formato [Integer/Hexadécimal].
  628. #----------------------------------------------------------------------------
  629. GetAsyncKeyState = Win32API.new('user32', 'GetAsyncKeyState', 'i', 'i')
  630. #----------------------------------------------------------------------------
  631. # • [WideCharToMultiByte] : [MultiByteToWideChar] // Comentários
  632. # não adicionados.
  633. #----------------------------------------------------------------------------
  634. WideCharToMultiByte = Win32API.new('kernel32', 'WideCharToMultiByte', 'ilpipipp', 'i')
  635. MultiByteToWideChar = Win32API.new('kernel32', 'MultiByteToWideChar', 'ilpipi', 'i')
  636. #----------------------------------------------------------------------------
  637. # • [ZeroMemoy]/Dll : Enche um bloco da memória com zeros.
  638. #----------------------------------------------------------------------------
  639. ZeroMemory = Win32API.new("kernel32", "RtlZeroMemory", "pl", "")
  640. #----------------------------------------------------------------------------
  641. # • [AdjustWindowRect] : Calcula o tamanho requerido do retângulo da Janela.
  642. #----------------------------------------------------------------------------
  643. AdjustWindowRect = int("AdjustWindowRect", [:LPRECT, :DWORD, :BOOL])
  644. #----------------------------------------------------------------------------
  645. # • Constantes [SetWindowPos]
  646. #----------------------------------------------------------------------------
  647. SWP_ASYNCWINDOWPOS = 0x4000
  648. # Desenha os frames (definidos na classe da janela descrita) em torno na janela.
  649. SWP_DRAWFRAME = 0x0020
  650. # Esconde a janela.
  651. SWP_HIDEWINDOW = 0x0080
  652. # Não pode ser ativada nem movida
  653. SWP_NOACTIVATE = 0x0010
  654. # Não permite mover
  655. SWP_NOMOVE = 0x0002
  656. # Não permite redimensionar
  657. SWP_NOSIZE = 0x0001
  658. # Mostra a Janela
  659. SWP_SHOWWINDOW = 0x0040
  660. # Coloca a janela na parte inferior na ordem de Z. Se identificar uma janela
  661. # superior ela perde os seus status.
  662. HWND_BOTTOM = 1
  663. # Coloca a janela acima de todas as janelas que não estão em primeiro plano.
  664. HWND_NOTOPMOST = -2
  665. # Poem a janela no Topo na ordem de Z.
  666. HWND_TOP = 0
  667. # Poem a janela acima de todas que não estão em primeiro plano. Mantendo a
  668. # posição.
  669. HWND_TOPMOST = -1
  670. #----------------------------------------------------------------------------
  671. # • [SetActiveWindow]/ Dll : Ativa a Window.
  672. #----------------------------------------------------------------------------
  673. SetActiveWindow = long("SetActiveWindow", [:HWND])
  674. #----------------------------------------------------------------------------
  675. # • WindowFromPoint : Retorna ao handle da janela, que contém um ponto
  676. # específico.
  677. #----------------------------------------------------------------------------
  678. WindowFromPoint = long("WindowFromPoint", [:HWND])
  679. #----------------------------------------------------------------------------
  680. # • ShowWindow : Mostra a janela em um estado específico.
  681. #----------------------------------------------------------------------------
  682. ShowWindow = long("ShowWindow", [:HWND, :LONG])
  683. # Força a janela a minimizar
  684. SW_FORCEMINIMIZE = 11
  685. # Esconde a janela, ativa outra.
  686. SW_HIDE = 0
  687. # Maximiza a janela.
  688. SW_MAXIMIZE = 3
  689. # Minimiza a janela
  690. SW_MINIMIZE = 6
  691. # Restaura o estado da janela.
  692. SW_RESTORE = 9
  693. # Ativa a janela a mostrando na posição original.
  694. SW_SHOW = 5
  695. #----------------------------------------------------------------------------
  696. # • [SetWindowText] : Permite modificar o título da janela.
  697. #----------------------------------------------------------------------------
  698. SetWindowText = int("SetWindowText", [:HWND, :LPCTSTR])
  699. #----------------------------------------------------------------------------
  700. # • [GetDesktopWindow] : Retorna ao handle da janela em relação ao Desktop.
  701. #----------------------------------------------------------------------------
  702. GetDesktopWindow = long("GetDesktopWindow", [:HWND])
  703. #----------------------------------------------------------------------------
  704. # • [GetSystemMetric] : Obtem um sistema métrico específico ou a configuração
  705. # do sistema. As dimensões retornadas são em pixel.
  706. #----------------------------------------------------------------------------
  707. GetSystemMetric = int("GetSystemMetric", [:int])
  708. #----------------------------------------------------------------------------
  709. # • [GetSystemMetric]/Constantes:
  710. #----------------------------------------------------------------------------
  711. # Obtem a flag que especifica como o sistema está organizando as janelas
  712. # minimizadas.
  713. SM_ARRANGE = 56
  714. # Obtem o tamanho da borda da Janela em pixel.
  715. SM_CXBORDER = 5
  716. # Valor do tamanho da área do cliente pra uma Janela em modo de tela-chéia.
  717. # em pixel.
  718. SM_CXFULLSCREEN = 16
  719. # Para mais informações dos valores, visite :
  720. # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx
  721. #----------------------------------------------------------------------------
  722. # • [GetClientRect] : Retorna ao rect da área da Janela.
  723. # Uses :
  724. # lpRect = [0,0,0,0].pack("L*")
  725. # GetClientRect.(hwnd, lpRect)
  726. # lpRect = lpRect.unpack("L*")
  727. #----------------------------------------------------------------------------
  728. GetClientRect = int("GetClientRect", [:HWND, :LPRECT])
  729. #----------------------------------------------------------------------------
  730. # • [GetModuleHandle] : Retorna ao Handle do módulo, do módulo específicado.
  731. # Pode ser aquivo '.dll' ou '.exe'. Exemplo:
  732. # GetModuleHandle.call('System/RGSS300.dll')
  733. #----------------------------------------------------------------------------
  734. GetModuleHandle = long("GetModuleHandle", [:LPCTSTR], "kerne32")
  735. #----------------------------------------------------------------------------
  736. # • [FreeLibrary] : Libera o módulo que está carregado na DLL específica.
  737. #----------------------------------------------------------------------------
  738. FreeLibrary = long("FreeLibrary", [:HMODULE], "kernel32")
  739. #----------------------------------------------------------------------------
  740. # • [LoadLibrary] : Carrega um endereço de um módulo em específico.
  741. # LoadLibrary.call(Nome da Libraria(dll/exe))
  742. # [Handle] : Retorna ao valor do Handle do módulo caso der certo.
  743. #----------------------------------------------------------------------------
  744. LoadLibrary = long("LoadLibrary", [:LPCTSTR], "kernel32")
  745. #----------------------------------------------------------------------------
  746. # • [GetProcAddress] : Retorna ao endereço da função exportada ou a variável
  747. # de uma DLL específica.
  748. # GetProcAddress.call(hModule, lpProcName)
  749. # hModule : É o valor do handle. Você pode pega-lo usando o LoadLibrary
  750. # lpProcName : A função ou o nome da variável.
  751. #----------------------------------------------------------------------------
  752. GetProcAddress = long("GetProcAddress", [:HMODULE, :LPCSTR], "kernel32")
  753. #----------------------------------------------------------------------------
  754. # • [GetSystemMetrics] : Retorna á uma configuração específica do sistema
  755. # métrico.
  756. #----------------------------------------------------------------------------
  757. GetSystemMetrics = int("GetSystemMetrics", [:int])
  758. #----------------------------------------------------------------------------
  759. # • [GetSystemMetrics]::Constantes. #Para mais visite:
  760. # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx
  761. #----------------------------------------------------------------------------
  762. SM_CXSCREEN = 0 # O tamanho(width/largura) da janela em pixel.
  763. SM_CYSCREEN = 1 # O tamanho(height/comprimento) da janela em pixel.
  764. SM_CXFULLSCREEN = 16 # O tamanho da largura da tela chéia da janela.
  765. SM_CYFULLSCREEN = 17 # O tamanho do comprimento da tela chéia da janela.
  766. #----------------------------------------------------------------------------
  767. # • [Método protegido] : Método usado para chamar a função LoadLibrary.
  768. #----------------------------------------------------------------------------
  769. def dlopen(name, fA=nil)
  770. l = LoadLibrary.(String(name))
  771. return l if fA.nil?
  772. return GetProcAddress.(l, String(fA))
  773. end
  774. #----------------------------------------------------------------------------
  775. # • Converte um texto para o formato UTF-8
  776. # textUTF(text)
  777. # * text : Texto.
  778. #----------------------------------------------------------------------------
  779. def textUTF(text)
  780. wC = API::MultiByteToWideChar.call(65001, 0, text, -1, "", 0)
  781. API::MultiByteToWideChar.call(65001, 0, text, -1, text = "\0\0" * wC, wC)
  782. return text
  783. end
  784. #----------------------------------------------------------------------------
  785. # • [TrueClass/FalseClass] : Retorna verdadeiro caso o Caps Lock esteja
  786. # ativo e retorna Falso caso não esteja ativo.
  787. #----------------------------------------------------------------------------
  788. def get_caps_lock
  789. return int("GetKeyState", [:vKey]).call(20) == 1
  790. end
  791. #----------------------------------------------------------------------------
  792. # • Abre a URL de um site o direcionado para o navegador padrão do usuário.
  793. #----------------------------------------------------------------------------
  794. def open_site(url)
  795. c = Win32API.new("Shell32", "ShellExecute", "pppppl", "l")
  796. c.call(nil, "open", url, nil, nil, 0)
  797. end
  798. #==============================================================================
  799. # • Clipboard
  800. #==============================================================================
  801. module Clipboard
  802. extend self
  803. #----------------------------------------------------------------------------
  804. # • Constantes do módulo:
  805. #----------------------------------------------------------------------------
  806. Close = Win32API.new("user32", "CloseClipboard", "v", "l")
  807. GetData = Win32API.new("user32", "GetClipboardData", "n", "l")
  808. Open = Win32API.new('user32', 'OpenClipboard', "N", "L")
  809. FormatAvailable = Win32API.new('user32', 'IsClipboardFormatAvailable', "i", "i")
  810. GlobalAlloc = Win32API.new('kernel32', 'GlobalAlloc', 'll', 'l')
  811. GlobalLock = Win32API.new('kernel32', 'GlobalLock', 'l', 'l')
  812. GlobalSize = Win32API.new('kernel32', 'GlobalSize', 'l', 'l')
  813. GlobalUnlock = Win32API.new('kernel32', 'GlobalUnlock', 'l', '')
  814. MemCpy = Win32API.new('ntdll', 'memcpy', 'ppl', 'l')
  815. FORMATS = {text: 1, dib: 2, bitmap: 8}
  816. #----------------------------------------------------------------------------
  817. # • Data. Retorna a Data do clipboard. Especificar o formato para receber
  818. # o retorno do formato especifico. Formato padrão é o texto.
  819. #----------------------------------------------------------------------------
  820. def data(format=FORMATS[:text])
  821. begin
  822. self.open
  823. if FormatAvailable.call(format)
  824. handle = GetData.call(format)
  825. case format
  826. when 1
  827. clip_data = 0.chr * GlobalSize.call(handle)
  828. MemCpy.call(clip_data, handle, clip_data.size)
  829. clip_data = clip_data[ /^[^\0]*/ ]
  830. when 2, 8 then clip_data = get_image_data(handle)
  831. else
  832. raise Error, 'format not supported'
  833. end
  834. else
  835. clip_data = ''
  836. end
  837. ensure
  838. self.close
  839. end
  840. clip_data
  841. end
  842. #----------------------------------------------------------------------------
  843. # • Singleton Class
  844. #----------------------------------------------------------------------------
  845. class << self
  846. alias :get_data :data
  847. end
  848. #----------------------------------------------------------------------------
  849. # • Formato aceito.
  850. #----------------------------------------------------------------------------
  851. def formatAvailable?(format)
  852. FormatAvailable.call(format).boolean
  853. end
  854. private
  855. #----------------------------------------------------------------------------
  856. # • Abrir clipboard
  857. #----------------------------------------------------------------------------
  858. def open
  859. Open.call(0)
  860. end
  861. #----------------------------------------------------------------------------
  862. # • Fechar
  863. #----------------------------------------------------------------------------
  864. def close
  865. Close.call
  866. end
  867. #----------------------------------------------------------------------------
  868. # • Obter a data de uma imagem, bitmap.
  869. #----------------------------------------------------------------------------
  870. def get_image_data(handle)
  871. buf = nil
  872. bmi = 0.chr * 44 # BITMAPINFO
  873. begin
  874. address = GlobalLock.call(handle)
  875. buf_size = GlobalSize.call(handle)
  876. MemCpy.call(bmi, address, bmi.length)
  877. bit_count = bmi[14,2].unpack('S').first # biBitCount
  878. compression = bmi[16,4].unpack('L').first # biCompression
  879. size_image = bmi[20,4].unpack('L').first # biSizeImage
  880. clr_used = bmi[32,4].unpack('L').first # biClrUsed
  881. size_image = buf_size + 16 if size_image == 0
  882. # Calculate the header size
  883. case bit_count
  884. when 1 then table_size = 2
  885. when 4 then table_size = 16
  886. when 8 then table_size = 256
  887. when 16, 32
  888. if compression == 0
  889. table_size = clr_used
  890. elsif compression == 3
  891. table_size = 3
  892. else
  893. msgbox "ERROR: invalid bit/compression combination"
  894. end
  895. when 24 then table_size = crl_used
  896. else
  897. msgbox "ERROR: invalid bit count"
  898. end
  899. offset = 0x36 + (table_size * 4)
  900. buf = 0.chr * buf_size
  901. MemCpy.call(buf, address, buf.size)
  902. buf = "\x42\x4D" + [size_image].pack('L') + 0.chr * 4 + [offset].pack('L') + buf
  903. ensure
  904. GlobalUnlock.call(handle)
  905. end
  906. buf
  907. end
  908. end
  909. #============================================================================
  910. # • MessageBox
  911. #============================================================================
  912. module MessageBox
  913. extend self
  914. # handle, string, title, format.
  915. FunctionMessageBox = Win32API.new("user32", "MessageBoxW", "lppl", "l")
  916. #--------------------------------------------------------------------------
  917. # • [Constantes] Botões:
  918. #--------------------------------------------------------------------------
  919. # Adiciona três botões a mensagem: Anular, Repetir e Ignorar.
  920. ABORTRETRYIGNORE = 0x00000002
  921. # Adiciona três botões a mensagem: Cancelar, Tentar e Continuar.
  922. CANCELTRYCONTINUE = 0x00000006
  923. # Adiciona o botão de ajuda.
  924. HELP = 0x00004000
  925. # Adiciona o botão Ok.
  926. OK = 0x00000000
  927. # Adiciona o botão OK e Cancelar.
  928. OKCANCEL = 0x00000001
  929. # Adiciona os botões: Repetir e Cancelar.
  930. RETRYCANCEL = 0x00000005
  931. # Adiciona os botões: Sim e Não
  932. YESNO = 0x00000004
  933. # Adiciona os botões: Sim, Não e Cancelar
  934. YESNOCANCEL = 0x00000003
  935. #--------------------------------------------------------------------------
  936. # • [Constantes] Ícones:
  937. #--------------------------------------------------------------------------
  938. # Adiciona um ícone de exclamação
  939. ICONEXCLAMATION = 0x00000030
  940. # Adiciona um ícone de informação.
  941. ICONINFORMATION = 0x00000040
  942. # Adiciona um ícone de um círculo com um ponto de interrogação.
  943. ICONQUESTION = 0x00000020
  944. # Adiciona um íconde parar na mensagem.
  945. ICONSTOP = 0x00000010
  946. #--------------------------------------------------------------------------
  947. # • [Constantes] Valores de retorno dos botões:
  948. #--------------------------------------------------------------------------
  949. ABORT = 3 # Retorno do valor do botão de Anular
  950. CANCEL = 2 # Retorno do valor do botão de Cancelar.
  951. CONTINUE = 11 # Retorno do valor do botão de Continuar.
  952. IGNORE = 5 # Retorno do valor de ignonar.
  953. NO = 7 # Retorno do valor do botão de Não.
  954. OK = 1 # Retorno do valor do botão de Ok.
  955. RETRY = 4 # Retorno do valor de repetir.
  956. TRYAGAIN = 10 # Retorno do valor de Repetir.
  957. YES = 6 # Retorno do valor do botão de Sim.
  958. #--------------------------------------------------------------------------
  959. # • [Constantes] Valores adicionais.
  960. #--------------------------------------------------------------------------
  961. RIGHT = 0x00080000 # Os textos ficarão justificados a direita.
  962. TOPMOST = 0x00040000 # O estilo da mensagem é criado como WB_EX_TOPMOST
  963. #--------------------------------------------------------------------------
  964. # • [call] : Retorna aos valores dos botões. Para serem usados
  965. # como condição, de que se ao clicar.
  966. # API::MessageBox.call(title, string, format)
  967. # title -> Título da caixa.
  968. # string -> Conteúdo da caixa.
  969. # format -> Formato, no caso seria os botões e ícones.
  970. #--------------------------------------------------------------------------
  971. def call(title, string, format)
  972. return FunctionMessageBox.call(API.hWND, API.textUTF(string), API.textUTF(title), format)
  973. end
  974. #--------------------------------------------------------------------------
  975. # • [messageBox] : Mesma função do Call a diferença é que e protegido.
  976. #--------------------------------------------------------------------------
  977. def messageBox(*args)
  978. self.call(*args)
  979. end
  980. protected :messageBox
  981. end
  982. protected :hwnd, :open, :function
  983. end
  984. #==============================================================================
  985. # * String
  986. #==============================================================================
  987. Dax.register(:string)
  988. class String
  989. #--------------------------------------------------------------------------
  990. # • [String] : converter à String em UTF8
  991. #--------------------------------------------------------------------------
  992. def to_utf8
  993. API.textUTF(self)
  994. end
  995. #--------------------------------------------------------------------------
  996. # • [Array] : Extrai somente os números da String, e retorna a uma Array.
  997. # Exemplo: "João89".numbers # [8, 9]
  998. #--------------------------------------------------------------------------
  999. def numbers
  1000. self.scan(/-*\d+/).collect{|n|n.to_i}
  1001. end
  1002. #----------------------------------------------------------------------------
  1003. # • [String] : Aplicando Case Sensitive
  1004. # "Exemplo 2" => "Exemplo_2"
  1005. #----------------------------------------------------------------------------
  1006. def case_sensitive
  1007. return self.gsub(" ", "_")
  1008. end
  1009. #----------------------------------------------------------------------------
  1010. # • [String] : Transormar em símbolo.
  1011. #----------------------------------------------------------------------------
  1012. def symbol
  1013. return self.case_sensitive.downcase.to_sym
  1014. end
  1015. #----------------------------------------------------------------------------
  1016. # • [String] : Remove o último caractere da String.
  1017. #----------------------------------------------------------------------------
  1018. def backslash
  1019. return String(self[0, self.split(//).size-1])
  1020. end
  1021. end
  1022. #==============================================================================
  1023. # * Integer
  1024. #==============================================================================
  1025. Dax.register(:integer)
  1026. class Integer
  1027. #----------------------------------------------------------------------------
  1028. # • [TrueClass/FalseClass] : Verifica-se e par.
  1029. #----------------------------------------------------------------------------
  1030. def is_evan?
  1031. return (self & 1) == 0
  1032. end
  1033. #----------------------------------------------------------------------------
  1034. # • [TrueClass/FalseClass] : Verifica-se e impar.
  1035. #----------------------------------------------------------------------------
  1036. def is_odd?
  1037. return (self & 1) == 1
  1038. end
  1039. #----------------------------------------------------------------------------
  1040. # • [Integer] : Aumenta o valor até chegar ao máximo(definido), quando
  1041. # chegar ao máximo(definido) retorna a zero.
  1042. #----------------------------------------------------------------------------
  1043. def up(max)
  1044. n = self
  1045. n = n > max ? 0 : n.next
  1046. return n
  1047. end
  1048. #----------------------------------------------------------------------------
  1049. # • [Integer] : Diminui o valor até chegar a zero, quando chegar a zero
  1050. # retorna ao valor máximo(defindo).
  1051. #----------------------------------------------------------------------------
  1052. def down(max)
  1053. n = self
  1054. n = n < 0 ? max : n - 1
  1055. return n
  1056. end
  1057. end
  1058. #==============================================================================
  1059. # • Numeric
  1060. #==============================================================================
  1061. Dax.register(:numeric)
  1062. class Numeric
  1063. #----------------------------------------------------------------------------
  1064. # * [Numeric] : Transformar em porcentagem
  1065. # a : Valor atual.
  1066. # b : Valor máximo.
  1067. #----------------------------------------------------------------------------
  1068. def to_p(a, b)
  1069. self * a / b
  1070. end
  1071. end
  1072. #==============================================================================
  1073. # * Color
  1074. #==============================================================================
  1075. Dax.register(:color)
  1076. class Color
  1077. #----------------------------------------------------------------------------
  1078. # • [Color] : Permite você modificar a opacidade da cor.
  1079. # Color.new(r, g, b).opacity([alpha])
  1080. # O valor padrão do alpha e 128.. não é preciso espeficar.
  1081. #----------------------------------------------------------------------------
  1082. def opacity(alpha=nil)
  1083. self.set(self.red, self.green, self.blue, alpha || 128)
  1084. end
  1085. #----------------------------------------------------------------------------
  1086. # • [Color] : Inverte as cores.
  1087. # Color.new(r, g, b[, a).invert!
  1088. #----------------------------------------------------------------------------
  1089. def invert!
  1090. self.set(255-self.red, 255-self.green, 255-self.blue, self.alpha)
  1091. end
  1092. #----------------------------------------------------------------------------
  1093. # • [Color] : Reverte as cores.
  1094. # Color.new(r, g, b[, a).revert
  1095. #----------------------------------------------------------------------------
  1096. def revert
  1097. self.set(*[self.red, self.green, self.blue, self.alpha].reverse!)
  1098. end
  1099. #----------------------------------------------------------------------------
  1100. # • [String] : Converte para string as informações dos valores das cores.
  1101. # Color.new(0, 0, 0).to_s
  1102. # red: 0
  1103. # blue: 0
  1104. # green: 0
  1105. # alpha: 255
  1106. #----------------------------------------------------------------------------
  1107. def to_s
  1108. "red: #{self.red}\nblue: #{self.blue}\ngreen: #{self.green}\nalpha: #{self.alpha}"
  1109. end
  1110. #----------------------------------------------------------------------------
  1111. # • [TrueClass/FalseClass] : Comparar cores, retorna a [true] se for igual..
  1112. # retorna a [false] se não for igual.
  1113. #----------------------------------------------------------------------------
  1114. def ==(color)
  1115. return (self.red == color.red and self.green == color.green and self.blue == color.blue and
  1116. self.alpha == color.alpha) ? true : false
  1117. end
  1118. #----------------------------------------------------------------------------
  1119. # • [Hash] : Retorna aos valores das cores em formato de Hash.
  1120. # Color.new(0, 0, 0).to_h
  1121. # {:red => 0, :green => 0, :blue => 0, :alpha => 255}
  1122. #----------------------------------------------------------------------------
  1123. def to_h
  1124. return {
  1125. red: self.red, green: self.green, blue: self.blue, alpha: self.alpha,
  1126. }
  1127. end
  1128. #----------------------------------------------------------------------------
  1129. # • [Array] : Retorna aos valores das cores em formato de Array.
  1130. # Color.new(0, 0, 0).to_a
  1131. # [0, 0, 0, 255]
  1132. #----------------------------------------------------------------------------
  1133. def to_a
  1134. return [self.red, self.green, self.blue, self.alpha]
  1135. end
  1136. #----------------------------------------------------------------------------
  1137. # • [Color] Soma os valores das cores com os valores de outras cores.
  1138. # Ex: color + Color.new(21,54,255)
  1139. #----------------------------------------------------------------------------
  1140. def +(color)
  1141. return unless color.is_a?(Color)
  1142. red = self.red + color.red
  1143. green = self.green + color.green
  1144. blue = self.blue + color.blue
  1145. self.set(red, green, blue)
  1146. end
  1147. #----------------------------------------------------------------------------
  1148. # • [Color] Subtrai os valores das cores com os valores de outras cores.
  1149. # Ex: color - Color.new(21,54,255)
  1150. #----------------------------------------------------------------------------
  1151. def -(color)
  1152. return unless color.is_a?(Color)
  1153. red = self.red - color.red
  1154. green = self.green - color.green
  1155. blue = self.blue - color.blue
  1156. self.set(red, green, blue)
  1157. end
  1158. #----------------------------------------------------------------------------
  1159. # • [Color] Multiplica os valores das cores com os valores de outras cores.
  1160. # Ex: color * Color.new(21,54,255)
  1161. #----------------------------------------------------------------------------
  1162. def *(color)
  1163. return unless color.is_a?(Color)
  1164. red = (self.red * color.red) / 255.0
  1165. green = (self.green * color.green) / 255.0
  1166. blue = (self.blue * color.blue) / 255.0
  1167. self.set(red, green, blue)
  1168. end
  1169. #----------------------------------------------------------------------------
  1170. # • [Numeric] : Retorna ao valor mais alto que tiver, dentre os valores
  1171. # especificados das cores.
  1172. #----------------------------------------------------------------------------
  1173. def max
  1174. [red, green, blue].max
  1175. end
  1176. #----------------------------------------------------------------------------
  1177. # • [Numeric] : Retorna ao valor menor que tiver, dentre os valores
  1178. # especificados das cores.
  1179. #----------------------------------------------------------------------------
  1180. def min
  1181. [red, green, blue].min
  1182. end
  1183. #----------------------------------------------------------------------------
  1184. # • [Color] : Define uma cor aleatória:
  1185. # Exemplo: Color.new.random
  1186. #----------------------------------------------------------------------------
  1187. def random
  1188. self.set(rand(256), rand(256), rand(256))
  1189. end
  1190. #----------------------------------------------------------------------------
  1191. # • [Color] : Define uma cor em hexadécimal.
  1192. # Exemplo : Color.new.hex("ffffff")
  1193. #----------------------------------------------------------------------------
  1194. def hex(string)
  1195. self.set(*string.scan(/../).map { |color| color.to_i(16)})
  1196. end
  1197. #----------------------------------------------------------------------------
  1198. # • [Color] : Retorna a cor padrão.
  1199. # Exemplo : Color.new.default
  1200. #----------------------------------------------------------------------------
  1201. def default
  1202. self.hex("ffffff")
  1203. end
  1204. end
  1205. #==============================================================================
  1206. # • Rect
  1207. #==============================================================================
  1208. Dax.register(:rect)
  1209. class Rect
  1210. #----------------------------------------------------------------------------
  1211. # • [TrueClass/FalseClass] : Verificar se algo está na área.
  1212. #----------------------------------------------------------------------------
  1213. def in?(x, y)
  1214. x.between?(self.x, self.x + self.width) &&
  1215. y.between?(self.y, self.y + self.height)
  1216. end
  1217. #----------------------------------------------------------------------------
  1218. # • [NilClass] : Cada elemento em um bloco.
  1219. # rect.each { |x, y, w, h| }
  1220. #----------------------------------------------------------------------------
  1221. def each
  1222. yield(self.x, self.y, self.width, self.height)
  1223. return nil
  1224. end
  1225. end
  1226. #==============================================================================
  1227. # • DMath
  1228. #==============================================================================
  1229. Dax.register(:dmath, 'Dax', 1.5, '04/05/13')
  1230. module DMath
  1231. extend self
  1232. #----------------------------------------------------------------------------
  1233. # • [Numeric] : Clamp | Delimitar o inteiro
  1234. # num : Número.
  1235. # low : Número minímo. Sê o 'num' for menor que min retorna a low.
  1236. # high : Número máximo. Sê o 'num' for maior que hight retorna a high, caso
  1237. # não retorna ao próprio número(num).
  1238. #----------------------------------------------------------------------------
  1239. def clamp(num, low, high)
  1240. num, low, high = num.to_i, low.to_i, high.to_i
  1241. num = num < low ? low : num > high ? high : num
  1242. num
  1243. end
  1244. #----------------------------------------------------------------------------
  1245. # • [Array] : Centralizar um objeto n'outro.
  1246. # object : Objeto, tem que ser do tipo [Sprite] ou [Window_Base]
  1247. # object_for_centralize : Objeto que irá se centralizar no 'object', tem
  1248. # que ser do tipo [Sprite] ou [Window_Base]
  1249. # * Retorna a uma Array contendo as informações das novas posições em X e Y.
  1250. #----------------------------------------------------------------------------
  1251. def centralize_object(object, object_for_centralize)
  1252. x = object.x + (object.width - object_for_centralize.width) / 2
  1253. y = object.y + (object.height - object_for_centralize.height) / 2
  1254. return x, y
  1255. end
  1256. #----------------------------------------------------------------------------
  1257. # • [Numeric] : Centralizar um objeto n'outro, obtendo somente a posição X.
  1258. # objectx : Valor da posição X do objeto número 1.
  1259. # objectwidth : Valor da largura do objeto número 1.
  1260. # object_for_centralizewidth : Valor da largura do objeto que irá se
  1261. # centralizar no objeto número 1.
  1262. # * Retorna ao valor da posição X.
  1263. #----------------------------------------------------------------------------
  1264. def centralize_x(objectx, objectwidth, object_for_centralizewidth)
  1265. return objectx + (objectwidth - object_for_centralizewidth) / 2
  1266. end
  1267. #----------------------------------------------------------------------------
  1268. # • [Numeric] : Centralizar um objeto n'outro, obtendo somente a posição Y.
  1269. # objecty : Valor da posição Y do objeto número 1.
  1270. # objectheight : Valor da altura do objeto número 1.
  1271. # object_for_centralizeheight : Valor da altura do objeto que irá se
  1272. # centralizar no objeto número 1.
  1273. # * Retorna ao valor da posição Y.
  1274. #----------------------------------------------------------------------------
  1275. def centralize_y(objecty, objectheight, object_for_centralizeheight)
  1276. return objecty + (objectheight - object_for_centralizeheight) / 2
  1277. end
  1278. #----------------------------------------------------------------------------
  1279. # • [Numeric] : Obter a posição X do centro da tela referente a largura do objeto X.
  1280. # Exemplo: get_x_center_screen(sprite.width) : Irá retornar ao valor da posição
  1281. # X para que o objeto fique no centro da tela.
  1282. # Exemplo: sprite.x = get_x_center_screen(sprite.width)
  1283. #----------------------------------------------------------------------------
  1284. def get_x_center_screen(width)
  1285. return (Graphics.width - width) / 2
  1286. end
  1287. #----------------------------------------------------------------------------
  1288. # • [Numeric] : Obter a posição Y do centro da tela referente a altura do objeto X.
  1289. # Exemplo: get_y_center_screen(sprite.height) : Irá retornar ao valor da posição
  1290. # Y para que o objeto fique no centro da tela.
  1291. # Exemplo: sprite.y = get_y_center_screen(sprite.height)
  1292. #----------------------------------------------------------------------------
  1293. def get_y_center_screen(height)
  1294. return (Graphics.height - height) / 2
  1295. end
  1296. #--------------------------------------------------------------------------
  1297. # • [TrueClass/FalseClass] : Verifica se um objeto está na área de um círculo.
  1298. # object : Objeto do tipo da classe [Sprite].
  1299. # object2 : Objeto do tipo da classe [Sprite].
  1300. # size : Tamanho geral do círculo.
  1301. #--------------------------------------------------------------------------
  1302. def circle(object, object2, size)
  1303. ( (object.x - object2.x) ** 2) + ( (object.y - object2.y) ** 2) <= (size ** 2)
  1304. end
  1305. #----------------------------------------------------------------------------
  1306. # • [Numeric] : Converter o valor em graus.
  1307. #----------------------------------------------------------------------------
  1308. def graus
  1309. 360 / (2 * Math::PI)
  1310. end
  1311. #----------------------------------------------------------------------------
  1312. # • [Numeric] : Converte o valor em radiano.
  1313. #----------------------------------------------------------------------------
  1314. def radian(degree)
  1315. return (degree.to_f/180) * Math::PI
  1316. end
  1317. #----------------------------------------------------------------------------
  1318. # • [Numeric] : Converte o valor em grau.
  1319. #----------------------------------------------------------------------------
  1320. def degree(radian)
  1321. return (radian.to_f/Math::PI) * 180
  1322. end
  1323. #----------------------------------------------------------------------------
  1324. # • [Numeric] : Retorna pra base de 4 decimais.
  1325. #----------------------------------------------------------------------------
  1326. def to_4_dec(n)
  1327. ((n * 1000).ceil) / 1000
  1328. end
  1329. #----------------------------------------------------------------------------
  1330. # • [TrueClass/FalseClass] : Verifica se está na área de um triângulo.
  1331. #----------------------------------------------------------------------------
  1332. def triangle_area(*args)
  1333. x, y, x2, y2, x3, y3 = *args
  1334. return (x2 - x) * (y3 - y) - (x3 - x) * (y2 - y)
  1335. end
  1336. #----------------------------------------------------------------------------
  1337. # • [Numeric] : Método para calcular a distância de um objeto para com outro.
  1338. #----------------------------------------------------------------------------
  1339. def distance_sensor(target, target2)
  1340. return (target.x - target2.x).abs + (target.y - target2.y).abs
  1341. end
  1342. #----------------------------------------------------------------------------
  1343. # • [Numeric] : Dentro do círculo.
  1344. #----------------------------------------------------------------------------
  1345. def circle_in(t, b, c, d)
  1346. return -c * (Math.sqrt(1 - (t /= d.to_f) * t) - 1) + b
  1347. end
  1348. #----------------------------------------------------------------------------
  1349. # • [Numeric] : Fora do círculo
  1350. #----------------------------------------------------------------------------
  1351. def circle_out(t, b, c, d)
  1352. return c * Math.sqrt(1 - (t=t/d.to_f-1)*t) + b
  1353. end
  1354. #----------------------------------------------------------------------------
  1355. # • [Numeric] : Retorna ao valor minímo, do valor máximo de min & v, com o
  1356. # valor de max.
  1357. #----------------------------------------------------------------------------
  1358. def force_range(v, min, max)
  1359. [[min, v].max, max].min
  1360. end
  1361. end
  1362. #==============================================================================
  1363. # • Keyboard | Método para usar todas as teclas do teclado.
  1364. #==============================================================================
  1365. Dax.register(:key, "Dax", 1.0)
  1366. module Key
  1367. extend self
  1368. #--------------------------------------------------------------------------
  1369. # * Chaves diversos.
  1370. #--------------------------------------------------------------------------
  1371. CANCEL = 0x03 # Control-Break Processing
  1372. BACKSPACE = 0x08 # Backspace Key
  1373. TAB = 0x09 # Tab Key
  1374. CLEAR = 0x0C # Clear Key
  1375. ENTER = 0x0D # Enter Key
  1376. SHIFT = 0x10 # Shift Key
  1377. CONTROL = 0x11 # Ctrl Key
  1378. MENU = 0x12 # Alt Key
  1379. PAUSE = 0x13 # Pause Key
  1380. ESC = 0x1B # Esc Key
  1381. CONVERT = 0x1C # IME Convert Key
  1382. NONCONVERT = 0x1D # IME Nonconvert Key
  1383. ACCEPT = 0x1E # IME Accept Key
  1384. SPACE = 0x20 # Space Bar Key (Space, usually blank)
  1385. PRIOR = 0x21 # Page Up Key
  1386. NEXT = 0x22 # Page Down Key
  1387. ENDS = 0x23 # End Key
  1388. HOME = 0x24 # Home Key
  1389. LEFT = 0x25 # Left Arrow Key
  1390. UP = 0x26 # Up Arrow Key
  1391. RIGHT = 0x27 # Right Arrow Key
  1392. DOWN = 0x28 # Down Arrow Key
  1393. SELECT = 0x29 # Select Key
  1394. PRINT = 0x2A # Print Key
  1395. EXECUTE = 0x2B # Execute Key
  1396. SNAPSHOT = 0x2C # Print Screen Key
  1397. DELETE = 0x2E # Delete Key
  1398. HELP = 0x2F # Help Key
  1399. LSHIFT = 0xA0 # Left Shift Key
  1400. RSHIFT = 0xA1 # Right Shift Key
  1401. LCONTROL = 0xA2 # Left Control Key (Ctrl)
  1402. RCONTROL = 0xA3 # Right Control Key (Ctrl)
  1403. LMENU = 0xA4 # Left Menu Key (Alt)
  1404. RMENU = 0xA5 # Right Menu Key (Alt)
  1405. PACKET = 0xE7 # Used to Pass Unicode Characters as Keystrokes
  1406. MOUSE_RIGHT = 0x01 # Button Mouse Right
  1407. MOUSE_LEFT = 0x02 # Button Mouse Left
  1408. MOUSE_MIDDLE = 0x04 # Button Mouse Middle
  1409. #--------------------------------------------------------------------------
  1410. # * Chaves de números.
  1411. #--------------------------------------------------------------------------
  1412. N0 = 0x30 # 0 Key
  1413. N1 = 0x31 # 1 Key
  1414. N2 = 0x32 # 2 Key
  1415. N3 = 0x33 # 3 Key
  1416. N4 = 0x34 # 4 Key
  1417. N5 = 0x35 # 5 Key
  1418. N6 = 0x36 # 6 Key
  1419. N7 = 0x37 # 7 Key
  1420. N8 = 0x38 # 8 Key
  1421. N9 = 0x39 # 9 Key
  1422. #--------------------------------------------------------------------------
  1423. # * Chaves de letras
  1424. #--------------------------------------------------------------------------
  1425. A = 0x41 # A Key
  1426. B = 0x42 # B Key
  1427. C = 0x43 # C Key
  1428. D = 0x44 # D Key
  1429. E = 0x45 # E Key
  1430. F = 0x46 # F Key
  1431. G = 0x47 # G Key
  1432. H = 0x48 # H Key
  1433. I = 0x49 # I Key
  1434. J = 0x4A # J Key
  1435. K = 0x4B # K Key
  1436. L = 0x4C # L Key
  1437. M = 0x4D # M Key
  1438. N = 0x4E # N Key
  1439. O = 0x4F # O Key
  1440. P = 0x50 # P Key
  1441. Q = 0x51 # Q Key
  1442. R = 0x52 # R Key
  1443. S = 0x53 # S Key
  1444. T = 0x54 # T Key
  1445. U = 0x55 # U Key
  1446. V = 0x56 # V Key
  1447. W = 0x57 # W Key
  1448. X = 0x58 # X Key
  1449. Y = 0x59 # Y Key
  1450. Z = 0x5A # Z Key
  1451. #--------------------------------------------------------------------------
  1452. # * Chaves de windows
  1453. #--------------------------------------------------------------------------
  1454. LWIN = 0x5B # Left Windows Key (Natural keyboard)
  1455. RWIN = 0x5C # Right Windows Key (Natural Keyboard)
  1456. APPS = 0x5D # Applications Key (Natural keyboard)
  1457. SLEEP = 0x5F # Computer Sleep Key
  1458. BROWSER_BACK = 0xA6 # Browser Back Key
  1459. BROWSER_FORWARD = 0xA7 # Browser Forward Key
  1460. BROWSER_REFRESH = 0xA8 # Browser Refresh Key
  1461. BROWSER_STOP = 0xA9 # Browser Stop Key
  1462. BROWSER_SEARCH = 0xAA # Browser Search Key
  1463. BROWSER_FAVORITES = 0xAB # Browser Favorites Key
  1464. BROWSER_HOME = 0xAC # Browser Start and Home Key
  1465. VOLUME_MUTE = 0xAD # Volume Mute Key
  1466. VOLUME_DOWN = 0xAE # Volume Down Key
  1467. VOLUME_UP = 0xAF # Volume Up Key
  1468. MEDIA_NEXT_TRACK = 0xB0 # Next Track Key
  1469. MEDIA_PREV_TRACK = 0xB1 # Previous Track Key
  1470. MEDIA_STOP = 0xB2 # Stop Media Key
  1471. MEDIA_PLAY_PAUSE = 0xB3 # Play/Pause Media Key
  1472. LAUNCH_MAIL = 0xB4 # Start Mail Key
  1473. LAUNCH_MEDIA_SELECT = 0xB5 # Select Media Key
  1474. LAUNCH_APP1 = 0xB6 # Start Application 1 Key
  1475. LAUNCH_APP2 = 0xB7 # Start Application 2 Key
  1476. PROCESSKEY = 0xE5 # IME Process Key
  1477. ATTN = 0xF6 # Attn Key
  1478. CRSEL = 0xF7 # CrSel Key
  1479. EXSEL = 0xF8 # ExSel Key
  1480. EREOF = 0xF9 # Erase EOF Key
  1481. PLAY = 0xFA # Play Key
  1482. ZOOM = 0xFB # Zoom Key
  1483. PA1 = 0xFD # PA1 Key
  1484. #--------------------------------------------------------------------------
  1485. # * Chaves do Numpad
  1486. #--------------------------------------------------------------------------
  1487. NUMPAD0 = 0x60 # Numeric Keypad 0 Key
  1488. NUMPAD1 = 0x61 # Numeric Keypad 1 Key
  1489. NUMPAD2 = 0x62 # Numeric Keypad 2 Key
  1490. NUMPAD3 = 0x63 # Numeric Keypad 3 Key
  1491. NUMPAD4 = 0x64 # Numeric Keypad 4 Key
  1492. NUMPAD5 = 0x65 # Numeric Keypad 5 Key
  1493. NUMPAD6 = 0x66 # Numeric Keypad 6 Key
  1494. NUMPAD7 = 0x67 # Numeric Keypad 7 Key
  1495. NUMPAD8 = 0x68 # Numeric Keypad 8 Key
  1496. NUMPAD9 = 0x69 # Numeric Keypad 9 Key
  1497. MULTIPLY = 0x6A # Multiply Key (*)
  1498. ADD = 0x6B # Add Key (+)
  1499. SEPARATOR = 0x6C # Separator Key
  1500. SUBTRACT = 0x6D # Subtract Key (-)
  1501. DECIMAL = 0x6E # Decimal Key (.)
  1502. DIVIDE = 0x6F # Divide Key (/)
  1503. #--------------------------------------------------------------------------
  1504. # * Chaves de funções
  1505. #--------------------------------------------------------------------------
  1506. F1 = 0x70 # F1 Key
  1507. F2 = 0x71 # F2 Key
  1508. F3 = 0x72 # F3 Key
  1509. F4 = 0x73 # F4 Key
  1510. F5 = 0x74 # F5 Key
  1511. F6 = 0x75 # F6 Key
  1512. F7 = 0x76 # F7 Key
  1513. F8 = 0x77 # F8 Key
  1514. F9 = 0x78 # F9 Key
  1515. F10 = 0x79 # F10 Key
  1516. F11 = 0x7A # F11 Key
  1517. F12 = 0x7B # F12 Key
  1518. F13 = 0x7C # F13 Key
  1519. F14 = 0x7D # F14 Key
  1520. F15 = 0x7E # F15 Key
  1521. F16 = 0x7F # F16 Key
  1522. F17 = 0x80 # F17 Key
  1523. F18 = 0x81 # F18 Key
  1524. F19 = 0x82 # F19 Key
  1525. F20 = 0x83 # F20 Key
  1526. F21 = 0x84 # F21 Key
  1527. F22 = 0x85 # F22 Key
  1528. F23 = 0x86 # F23 Key
  1529. F24 = 0x87 # F24 Key
  1530. #--------------------------------------------------------------------------
  1531. # * Chaves alternativas
  1532. #--------------------------------------------------------------------------
  1533. CAPITAL = 0x14 # Caps Lock Key
  1534. KANA = 0x15 # IME Kana Mode Key
  1535. HANGUL = 0x15 # IME Hangul Mode Key
  1536. JUNJA = 0x17 # IME Junja Mode Key
  1537. FINAL = 0x18 # IME Final Mode Key
  1538. HANJA = 0x19 # IME Hanja Mode Key
  1539. KANJI = 0x19 # IME Kanji Mode Key
  1540. MODECHANGE = 0x1F # IME Mode Change Request Key
  1541. INSERT = 0x2D # Insert Key
  1542. NUMLOCK = 0x90 # Num Lock Key
  1543. SCROLL = 0x91 # Scroll Lock Key
  1544. #--------------------------------------------------------------------------
  1545. # * Chaves OEM, variadas
  1546. #--------------------------------------------------------------------------
  1547. OEM_1 = 0xBA # Misc Characters (; : in USA 101/102 Keyboards)
  1548. OEM_PLUS = 0xBB # + = Key
  1549. OEM_COMMA = 0xBC # , < Key
  1550. OEM_MINUS = 0xBD # - _ Key
  1551. OEM_PERIOD = 0xBE # . > Key
  1552. OEM_2 = 0xBF # Misc Characters (/ ? in USA 101/102 Keyboards)
  1553. OEM_3 = 0xC0 # Misc Characters (` ~ in USA 101/102 Keyboards)
  1554. OEM_4 = 0xDB # Misc Characters ([ { in USA 101/102 Keyboards)
  1555. OEM_5 = 0xDC # Misc Characters (\ | in USA 101/102 Keyboards)
  1556. OEM_6 = 0xDD # Misc Characters (] } in USA 101/102 Keyboards)
  1557. OEM_7 = 0xDE # Misc Characters (' " in USA 101/102 Keyboards)
  1558. OEM_8 = 0xDF # Misc Characters (Varies by Keyboard)
  1559. OEM_9 = 0xE1 # OEM Specific
  1560. OEM_10 = 0x92 # OEM Specific
  1561. OEM_11 = 0x93 # OEM Specific
  1562. OEM_12 = 0x94 # OEM Specific
  1563. OEM_13 = 0x95 # OEM Specific
  1564. OEM_14 = 0x96 # OEM Specific
  1565. OEM_15 = 0xE3 # OEM Specific
  1566. OEM_16 = 0xE4 # OEM Specific
  1567. OEM_17 = 0xE6 # OEM Specific
  1568. OEM_18 = 0xE9 # OEM Specific
  1569. OEM_19 = 0xEA # OEM Specific
  1570. OEM_20 = 0xEB # OEM Specific
  1571. OEM_21 = 0xEC # OEM Specific
  1572. OEM_22 = 0xED # OEM Specific
  1573. OEM_23 = 0xEE # OEM Specific
  1574. OEM_24 = 0xEF # OEM Specific
  1575. OEM_25 = 0xF1 # OEM Specific
  1576. OEM_26 = 0xF2 # OEM Specific
  1577. OEM_27 = 0xF3 # OEM Specific
  1578. OEM_28 = 0xF4 # OEM Specific
  1579. OEM_29 = 0xF5 # OEM Specific
  1580. OEM_102 = 0xE2 # Angle Bracket or Backslash on RT-102 Keyboards
  1581. OEM_CLEAR = 0xFE # Clear Key
  1582. #--------------------------------------------------------------------------
  1583. # * Variáveis do módulo.
  1584. #--------------------------------------------------------------------------
  1585. @unpack_string = 'b'*256
  1586. @last_array = '0'*256
  1587. @press = Array.new(256, false)
  1588. @trigger = Array.new(256, false)
  1589. @repeat = Array.new(256, false)
  1590. @release = Array.new(256, false)
  1591. @repeat_counter = Array.new(256, 0)
  1592. @getKeyboardState = API::GetKeyboardState
  1593. @getAsyncKeyState = API::GetAsyncKeyState
  1594. @getKeyboardState.call(@last_array)
  1595. @last_array = @last_array.unpack(@unpack_string)
  1596. for i in 0...@last_array.size
  1597. @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
  1598. end
  1599. #--------------------------------------------------------------------------
  1600. # * Atualização dos objetos do módulo.
  1601. #--------------------------------------------------------------------------
  1602. def update
  1603. @trigger = Array.new(256, false)
  1604. @repeat = Array.new(256, false)
  1605. @release = Array.new(256, false)
  1606. array = '0'*256
  1607. @getKeyboardState.call(array)
  1608. array = array.unpack(@unpack_string)
  1609. for i in 0...array.size
  1610. if array[i] != @last_array[i]
  1611. @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
  1612. if @repeat_counter[i] <= 0 && @press[i]
  1613. @repeat[i] = true
  1614. @repeat_counter[i] = 15
  1615. end
  1616. if !@press[i]
  1617. @release[i] = true
  1618. else
  1619. @trigger[i] = true
  1620. end
  1621. else
  1622. if @press[i] == true
  1623. @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
  1624. @release[i] = true if !@press[i]
  1625. end
  1626. if @repeat_counter[i] > 0 && @press[i] == true
  1627. @repeat_counter[i] -= 1
  1628. elsif @repeat_counter[i] <= 0 && @press[i] == true
  1629. @repeat[i] = true
  1630. @repeat_counter[i] = 3
  1631. elsif @repeat_counter[i] != 0
  1632. @repeat_counter[i] = 0
  1633. end
  1634. end
  1635. end
  1636. @last_array = array
  1637. end
  1638. #--------------------------------------------------------------------------
  1639. # * [TrueClass/FalseClass] Obter o estado quando a chave for pressionada.
  1640. # key : key index
  1641. #--------------------------------------------------------------------------
  1642. def press?(key)
  1643. return @press[key]
  1644. end
  1645. #--------------------------------------------------------------------------
  1646. # * [TrueClass/FalseClass] Obter o estado quando a chave for teclada.
  1647. # key : key index
  1648. #--------------------------------------------------------------------------
  1649. def trigger?(key)
  1650. return @trigger[key]
  1651. end
  1652. #--------------------------------------------------------------------------
  1653. # * [TrueClass/FalseClass] Obter o estado quando a chave for teclada repetidamente.
  1654. # key : key index
  1655. #--------------------------------------------------------------------------
  1656. def repeat?(key)
  1657. return @repeat[key]
  1658. end
  1659. #--------------------------------------------------------------------------
  1660. # * [TrueClass/FalseClass] Obter o estado quando a chave for "lançada"
  1661. # key : key index
  1662. #--------------------------------------------------------------------------
  1663. def release?(key)
  1664. return @release[key]
  1665. end
  1666. #----------------------------------------------------------------------------
  1667. # • CONSTANTES.
  1668. #----------------------------------------------------------------------------
  1669. AZ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(//)
  1670. Az = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".downcase!.split(//)
  1671. NUM = "0123456789".split(//)
  1672. #----------------------------------------------------------------------------
  1673. # • [String] : Retornar a String correspondente a tecla pressionada dos números.
  1674. #----------------------------------------------------------------------------
  1675. def stringNUM(input='trigger?')
  1676. n = "N0,N1,N2,N3,N4,N5,N6,N7,N8,N9".split(',')
  1677. numpad = "NUMPAD0,NUMPAD1,NUMPAD2,NUMPAD3,NUMPAD4,NUMPAD5,NUMPAD6,NUMPAD7,NUMPAD8,NUMPAD9".split(',')
  1678. n.each_with_index { |v,i| eval("return NUM[i] if #{input}(#{v})") }
  1679. numpad.each_with_index { |v,i| eval("return NUM[i] if #{input}(#{v})") }
  1680. return ""
  1681. end
  1682. #----------------------------------------------------------------------------
  1683. # • [String] : Retorar a String correspondente a tecla pressionada dos alfabeto
  1684. #----------------------------------------------------------------------------
  1685. def stringAZ(input='trigger?')
  1686. if API.get_caps_lock
  1687. AZ.each_with_index { |v,i| eval("return AZ[i] if #{input}(#{v})") }
  1688. else
  1689. AZ.each_with_index { |v,i| eval("return Az[i] if #{input}(#{v})") }
  1690. end
  1691. return ""
  1692. end
  1693. end
  1694. #==============================================================================
  1695. # • Sprite
  1696. #==============================================================================
  1697. Dax.register(:sprite)
  1698. class Sprite
  1699. #----------------------------------------------------------------------------
  1700. # • Variáveis públicas da instância.
  1701. #----------------------------------------------------------------------------
  1702. attr_accessor :clone_sprite
  1703. attr_accessor :outline_fill_rect
  1704. #----------------------------------------------------------------------------
  1705. # • Novo método. Modos de usos abaixo:
  1706. # * [normal] : É o método normal, na qual você não define nada. Sprite.new
  1707. # * [viewport] : É o método na qual você define um viewport.
  1708. # Sprite.new(Viewport)
  1709. # * [system] : É o método na qual você já define um bitmap que irá carregar
  1710. # uma imagem já direto da pasta System, através do Cache.
  1711. # Sprite.new("S: Nome do Arquivo")
  1712. # * [picture] : É o método na qual você já define um bitmap que irá carregar
  1713. # uma imagem já direito da pasta Pictures, através do Cache.
  1714. # Sprite.new("P: Nome do Arquivo")
  1715. # * [graphics] : É o método na qual você já define um bitmap com uma imagem
  1716. # que está dentro da pasta Graphics, através do Cache.
  1717. # Sprite.new("G: Nome do Arquivo.")
  1718. # * [width, height] : É o método na qual você já define a largura e altura
  1719. # do bitmap. Sprite.new([width, height])
  1720. # * [elements] : É o método na qual você já define a largura, altura,
  1721. # posição X, posição Y e Prioridade do bitmap.
  1722. # Sprite.new([width, height, x, y, z])
  1723. #----------------------------------------------------------------------------
  1724. alias new_initialize initialize
  1725. def initialize(viewport=nil)
  1726. @clone_sprite = []
  1727. @outline_fill_rect = nil
  1728. if viewport.is_a?(String)
  1729. new_initialize(nil)
  1730. if viewport.match(/S: ([^>]*)/)
  1731. self.bitmap = Cache.system($1.to_s)
  1732. elsif viewport.match(/P: ([^>]*)/)
  1733. self.bitmap = Cache.picture($1.to_s)
  1734. elsif viewport.match(/G: ([^>]*)/)
  1735. self.bitmap = Cache.load_bitmap("Graphics/", $1.to_s)
  1736. else
  1737. self.bitmap = Bitmap.new(viewport)
  1738. end
  1739. elsif viewport.is_a?(Array)
  1740. if viewport.size == 2
  1741. new_initialize(nil)
  1742. self.bitmap = Bitmap.new(viewport[0], viewport[1])
  1743. elsif viewport.size == 5
  1744. new_initialize(nil)
  1745. self.bitmap = Bitmap.new(viewport[0], viewport[1])
  1746. self.x, self.y, self.z = viewport[2], viewport[3], viewport[4]
  1747. end
  1748. elsif viewport.is_a?(Viewport) or viewport.nil?
  1749. new_initialize(viewport)
  1750. end
  1751. end
  1752. #----------------------------------------------------------------------------
  1753. # • Renovação do Sprite.
  1754. #----------------------------------------------------------------------------
  1755. alias :dax_core_dispose :dispose
  1756. def dispose
  1757. dax_core_dispose
  1758. @outline_fill_rect.dispose unless @outline_fill_rect.nil?
  1759. end
  1760. #----------------------------------------------------------------------------
  1761. # • Definir um contorno no Sprite em forma de retângulo.
  1762. # color : Cor do contorno.
  1763. # size : Tamanho da linha do contorno.
  1764. # vis : Visibilidade. true - visível | false - invisível.
  1765. #----------------------------------------------------------------------------
  1766. def set_outline(color=Color.new.default, size=2, vis=true)
  1767. @outline_fill_rect = Sprite.new([self.width, self.height, self.x, self.y, self.z+2])
  1768. @outline_fill_rect.bitmap.fill_rect(0, 0, self.width, size, color)
  1769. @outline_fill_rect.bitmap.fill_rect(0, self.height-size, self.width, size, color)
  1770. @outline_fill_rect.bitmap.fill_rect(0, 0, size, self.height, color)
  1771. @outline_fill_rect.bitmap.fill_rect(self.width-size, 0, size, self.height, color)
  1772. @outline_fill_rect.visible = vis
  1773. end
  1774. #----------------------------------------------------------------------------
  1775. # • Atualização do contorno.
  1776. # vis : Visibilidade. true - visível | false - invisível.
  1777. #----------------------------------------------------------------------------
  1778. def update_outline(vis=true)
  1779. @outline_fill_rect.visible = vis
  1780. @outline_fill_rect.x, @outline_fill_rect.y = self.x, self.y
  1781. end
  1782. #----------------------------------------------------------------------------
  1783. # • Slide pela direita.
  1784. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  1785. #----------------------------------------------------------------------------
  1786. def slide_right(speed, point)
  1787. self.x += speed unless self.x >= point
  1788. end
  1789. #----------------------------------------------------------------------------
  1790. # • Slide pela esquerda.
  1791. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  1792. #----------------------------------------------------------------------------
  1793. def slide_left(speed, point)
  1794. self.x -= speed unless self.x <= point
  1795. end
  1796. #----------------------------------------------------------------------------
  1797. # • Slide por cima.
  1798. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  1799. #----------------------------------------------------------------------------
  1800. def slide_up(speed, point)
  1801. self.y -= speed unless self.y <= point
  1802. end
  1803. #----------------------------------------------------------------------------
  1804. # • Slide por baixo.
  1805. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  1806. #----------------------------------------------------------------------------
  1807. def slide_down(speed, point)
  1808. self.y += speed unless self.y >= point
  1809. end
  1810. #----------------------------------------------------------------------------
  1811. # • Define aqui uma posição fixa para um objeto.
  1812. # command : Retorna a uma base padrão.
  1813. #----------------------------------------------------------------------------
  1814. def position(command=0)
  1815. return if command.nil?
  1816. case command
  1817. # Imagem ficará no canto esquerdo superior. Posição X
  1818. when 0 then self.x = 0
  1819. # A posição X ficará no centro da tela.
  1820. when 1 then self.x = DMath.get_x_center_screen(self.width)
  1821. # A posição X ficará no canto direito superior.
  1822. when 2 then self.x = Graphics.width - self.width
  1823. # A posição Y ficará no canto esquerdo inferior.
  1824. when 3 then self.y = 0
  1825. # Posicionar o Y para ficar no centro.
  1826. when 4 then self.y = DMath.get_y_center_screen(self.height)
  1827. # Posicionar o Y para ficar no fundo da tela.
  1828. when 5 then self.y = Graphics.height - self.height
  1829. # Posicionar a imagem no centro da tela.
  1830. when :center
  1831. self.x = (Graphics.width - self.width) / 2
  1832. self.y = Graphics.height / 2 - self.height / 2
  1833. # Posicionar no centro esquerdo da tela.
  1834. when :center_left
  1835. self.x = 0
  1836. self.y = (Graphics.height - self.height) / 2
  1837. # Posicionar no centro direito da tela.
  1838. when :center_right
  1839. self.x = Graphics.width - self.height
  1840. self.y = (Graphics.height - self.height) / 2
  1841. end
  1842. end
  1843. #----------------------------------------------------------------------------
  1844. # • [Numeric] : Tamanho geral
  1845. #----------------------------------------------------------------------------
  1846. def size
  1847. return self.width + self.height
  1848. end
  1849. #----------------------------------------------------------------------------
  1850. # • [Rect] : Retorna ao Rect do Bitmap.
  1851. #----------------------------------------------------------------------------
  1852. def rect
  1853. return self.bitmap.rect
  1854. end
  1855. #----------------------------------------------------------------------------
  1856. # • Base para clonar um Sprite.
  1857. # * depht : Prioridade no mapa.
  1858. # * clone_bitmap : Se irá clonar o bitmap.
  1859. # Exemplo: sprite = sprite2.clone
  1860. #----------------------------------------------------------------------------
  1861. def clone(depht=0, clone_bitmap=false)
  1862. @clone_sprite.delete_if { |bitmap| bitmap.disposed? }
  1863. cloned = Sprite.new(self.viewport)
  1864. cloned.x, cloned.y = self.x, self.y
  1865. cloned.bitmap = self.bitmap
  1866. cloned.bitmap = self.bitmap.clone if clone_bitmap
  1867. unless depht == 0
  1868. cloned.z = self.z + depht
  1869. else
  1870. @clone_sprite.each { |sprite| sprite.z -= 1 }
  1871. cloned.z = self.z - 1
  1872. end
  1873. cloned.src_rect.set(self.src_rect)
  1874. ["zoom_x", "zoom_y", "angle", "mirror", "opacity", "blend_type", "visible",
  1875. "ox", "oy"].each { |meth|
  1876. eval("cloned.#{meth} = self.#{meth}")
  1877. }
  1878. cloned.color.set(color)
  1879. cloned.tone.set(tone)
  1880. after_clone(cloned)
  1881. @clone_sprite.push(cloned)
  1882. return cloned
  1883. end
  1884. #----------------------------------------------------------------------------
  1885. # • Efeito após ter clonado o Sprite.
  1886. #----------------------------------------------------------------------------
  1887. def after_clone(clone)
  1888. end
  1889. #----------------------------------------------------------------------------
  1890. # • O que irá acontecer sê o mouse estiver em cima do sprite?
  1891. #----------------------------------------------------------------------------
  1892. def mouse_over
  1893. end
  1894. #----------------------------------------------------------------------------
  1895. # • O que irá acontecer sê o mouse não estiver em cima do sprite?
  1896. #----------------------------------------------------------------------------
  1897. def mouse_no_over
  1898. end
  1899. #----------------------------------------------------------------------------
  1900. # • O que irá acontecer sê o mouse clicar no objeto
  1901. #----------------------------------------------------------------------------
  1902. def mouse_click
  1903. end
  1904. #----------------------------------------------------------------------------
  1905. # • Atualização dos sprites.
  1906. #----------------------------------------------------------------------------
  1907. alias :dax_update :update
  1908. def update(*args, &block)
  1909. dax_update(*args, &block)
  1910. unless Mouse.cursor.nil?
  1911. self.if_mouse_over { |over| over ? mouse_over : mouse_no_over }
  1912. self.if_mouse_click { mouse_click }
  1913. end
  1914. end
  1915. #----------------------------------------------------------------------------
  1916. # • Inverter o lado do sprite.
  1917. #----------------------------------------------------------------------------
  1918. def invert!
  1919. self.mirror = !self.mirror
  1920. end
  1921. end
  1922. #==============================================================================
  1923. # • Bitmap
  1924. #==============================================================================
  1925. Dax.register(:bitmap)
  1926. class Bitmap
  1927. #----------------------------------------------------------------------------
  1928. # • Criar uma barra.
  1929. # color : Objeto de Cor [Color]
  1930. # actual : Valor atual da barra.
  1931. # max : Valor máximo da barra.
  1932. # borda : Tamanho da borda da barra.
  1933. #----------------------------------------------------------------------------
  1934. def bar(color, actual, max, borda=1)
  1935. rate = self.width.to_p(actual, max)
  1936. self.fill_rect(borda, borda, rate-(borda*2), self.height-(borda*2),
  1937. color)
  1938. end
  1939. #----------------------------------------------------------------------------
  1940. # • Barra em forma de gradient.
  1941. # color : Objeto de Cor, em forma de [Array] para conter 2 [Color]
  1942. # exemplo -> [Color.new(x), Color.new(y)]
  1943. # actual : Valor atual da barra.
  1944. # max : Valor máximo da barra.
  1945. # borda : Tamanho da borda da barra.
  1946. #----------------------------------------------------------------------------
  1947. def gradient_bar(color, actual, max, borda=1)
  1948. rate = self.width.to_p(actual, max)
  1949. self.gradient_fill_rect(borda, borda, rate-(borda*2), self.height-(borda*2),
  1950. color[0], color[1], 2)
  1951. end
  1952. #----------------------------------------------------------------------------
  1953. # • Limpar uma área num formato de um círculo.
  1954. #----------------------------------------------------------------------------
  1955. def clear_rect_circle(x, y, r)
  1956. rr = r*r
  1957. for i in 0...r
  1958. adj = Math.sqrt(rr - (i*i)).ceil
  1959. xd = x - adj
  1960. wd = 2 * adj
  1961. self.clear_rect(xd, y-i, wd, 1)
  1962. self.clear_rect(xd, y+i, wd, 1)
  1963. end
  1964. end
  1965. #----------------------------------------------------------------------------
  1966. # • Novo modo de desenhar textos. Configurações já especificadas.
  1967. #----------------------------------------------------------------------------
  1968. def draw_text_rect(*args)
  1969. self.draw_text(self.rect, *args)
  1970. end
  1971. #----------------------------------------------------------------------------
  1972. # • Salvar em png.
  1973. # --- Autor : Gab! ---
  1974. #----------------------------------------------------------------------------
  1975. def save(file_name)
  1976. def chunk(type, data)
  1977. [data.size, type, data, Zlib.crc32(type + data)].pack("NA4A*N")
  1978. end
  1979. img_data = ""
  1980. width, height = self.width, self.height
  1981. for j in 0...(height)
  1982. img_data << "\0"
  1983. for i in 0...(width)
  1984. pos_c = self.get_pixel(i, j)
  1985. img_data << [pos_c.red, pos_c.green, pos_c.blue, pos_c.alpha].pack("C*")
  1986. end
  1987. end
  1988. c = [
  1989. "\x89PNG\r\n\x1a\n",
  1990. chunk("IHDR", [width, height, 8, 6, 0, 0, 0].pack("N2C5")),
  1991. chunk("IDAT", Zlib::Deflate.deflate(img_data)),
  1992. chunk("IEND", "")
  1993. ]
  1994. File.open(file_name << ".png", "wb"){|file| c.each{|chunk| file.write(chunk) }}
  1995. end
  1996. #----------------------------------------------------------------------------
  1997. # • Modificar as cores do [Bitmap] para ficarem Negativas.
  1998. #----------------------------------------------------------------------------
  1999. def negative
  2000. for i in 0...(self.width)
  2001. for j in 0...(self.height)
  2002. pix = self.get_pixel(i, j)
  2003. pix.red = (pix.red - 255) * -1
  2004. pix.blue = (pix.blue - 255) * -1
  2005. pix.green = (pix.green - 255) * -1
  2006. self.set_pixel(i, j, pix)
  2007. end
  2008. end
  2009. end
  2010. #----------------------------------------------------------------------------
  2011. # • Grayscale : Modificar as cores do [Bitmap] para cor cinza. Efeito cinza.
  2012. #----------------------------------------------------------------------------
  2013. def grayscale(rect = Rect.new(0, 0, self.width, self.height))
  2014. for i in rect.x...rect.x + rect.width
  2015. for j in rect.y...rect.y + rect.height
  2016. colour = self.get_pixel(i,j)
  2017. grey_pixel = (colour.red*0.3 + colour.green*0.59 + colour.blue*0.11)
  2018. colour.red = colour.green = colour.blue = grey_pixel
  2019. self.set_pixel(i,j,colour)
  2020. end
  2021. end
  2022. end
  2023. #----------------------------------------------------------------------------
  2024. # • Novo fornecedor de pixel.
  2025. #----------------------------------------------------------------------------
  2026. def set_pixel_s(x, y, color, size)
  2027. for i in 0...size
  2028. self.set_pixel(x+i, y, color)
  2029. self.set_pixel(x-i, y, color)
  2030. self.set_pixel(x, y+i, color)
  2031. self.set_pixel(x, y-i, color)
  2032. self.set_pixel(x+i, y+i, color)
  2033. self.set_pixel(x-i, y-i, color)
  2034. self.set_pixel(x+i, y-i, color)
  2035. self.set_pixel(x-i, y+i, color)
  2036. end
  2037. end
  2038. #----------------------------------------------------------------------------
  2039. # • Desenhar uma linha.
  2040. # start_x : Início da linha em X.
  2041. # start_y : Início da linha em Y.
  2042. # end_x : Finalização da linha em X.
  2043. # end_y : Finalização da linha em Y.
  2044. #----------------------------------------------------------------------------
  2045. def draw_line(start_x, start_y, end_x, end_y, color, size=1)
  2046. set_pixel_s(start_x, start_y, color, size)
  2047. distance = (start_x - end_x).abs + (start_y - end_y).abs
  2048. for i in 1..distance
  2049. x = (start_x + 1.0 * (end_x - start_x) * i / distance).to_i
  2050. y = (start_y + 1.0 * (end_y - start_y) * i / distance).to_i
  2051. set_pixel_s(x, y, color, size)
  2052. end
  2053. set_pixel_s(end_x, end_y, color, size)
  2054. end
  2055. #----------------------------------------------------------------------------
  2056. # • draw_bar_gauge(x, y, current, current_max, border, colors)
  2057. # x : Coordenadas X.
  2058. # y : Coordenadas Y.
  2059. # current : Valor atual da barra.
  2060. # current_max : Valor maxímo da barra.
  2061. # border : Expressura da borda.
  2062. # colors : Cores. [0, 1, 2]
  2063. #----------------------------------------------------------------------------
  2064. # Permite adicionar uma barra.
  2065. #----------------------------------------------------------------------------
  2066. def draw_bar_gauge(x, y, current, current_max, colors=[])
  2067. cw = self.width.to_p(current, current_max)
  2068. ch = self.height
  2069. self.gradient_fill_rect(x, y, self.width, self.height, colors[0], colors[1])
  2070. src_rect = Rect.new(0, 0, cw, ch)
  2071. self.blt(x, y, self, src_rect)
  2072. end
  2073. #----------------------------------------------------------------------------
  2074. # • draw_icon(icon_index, x, y, enabled)
  2075. # icon_index : ID do ícone.
  2076. # x : Coordenadas X.
  2077. # y : Coordenadas Y.
  2078. # enabled : Habilitar flag, translucido quando false
  2079. # filename : Podes definir uma imagem: Basta
  2080. # por o nome da imagem, ela deve estar na pasta System.
  2081. #----------------------------------------------------------------------------
  2082. def draw_icon(icon_index, x, y, enabled = true, filename="IconSet")
  2083. icon_index = icon_index.nil? ? 0 : icon_index
  2084. bitmap = Cache.system(filename)
  2085. rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)
  2086. self.blt(x, y, bitmap, rect, enabled ? 255 : 128)
  2087. end
  2088. #----------------------------------------------------------------------------
  2089. # • draw_gradation_gauge(x, y, width, height, current, current_max, border, colors, align)
  2090. # x : Coordenadas X.
  2091. # y : Coordenadas Y.
  2092. # width : Largura da barra.
  2093. # height : Altura da barra.
  2094. # current : Valor atual da barra.
  2095. # current_max : Valor maxímo da barra.
  2096. # border : Expressura da borda.
  2097. # colors : Cores. [0, 1, 2]
  2098. # align : Alinhamento.
  2099. #----------------------------------------------------------------------------
  2100. # Permite adicionar uma barra.
  2101. #----------------------------------------------------------------------------
  2102. def draw_gradation_gauge(x, y, current, current_max, border, colors=[])
  2103. cw = self.width.to_p(current, current_max)
  2104. ch = self.height
  2105. self.fill_rect(x, y, self.width, self.height, colors[0])
  2106. self.gradient_fill_rect(x+border, y+border, self.width-(border/2), self.height-(border/2), colors[1], colors[2])
  2107. src_rect = Rect.new(0, 0, cw, ch)
  2108. self.blt(x, y, self, src_rect)
  2109. end
  2110. #----------------------------------------------------------------------------
  2111. # • Desenhar um círuclo preenchido.
  2112. #----------------------------------------------------------------------------
  2113. def fill_circle(x, y, r, c)
  2114. rr = r*r
  2115. for i in 0...r
  2116. adj = Math.sqrt(rr - (i*i)).ceil
  2117. xd = x - adj
  2118. wd = 2 * adj
  2119. self.fill_rect(xd, y-i, wd, 1, c)
  2120. self.fill_rect(xd, y+i, wd, 1, c)
  2121. end
  2122. end
  2123. end
  2124. #==============================================================================
  2125. # • Mouse
  2126. #==============================================================================
  2127. Dax.register(:mouse)
  2128. module Mouse
  2129. extend self
  2130. #--------------------------------------------------------------------------
  2131. # • Inicialização dos objetos.
  2132. #--------------------------------------------------------------------------
  2133. def start
  2134. @cursor = Sprite_Mouse.new(Dax::Mouse_Name, 0, 0, 100000)
  2135. x = Dax::Mouse_Name == "" ? 1 : 0
  2136. API::MouseShowCursor.call(x)
  2137. @dgraphic = Dax::Mouse_Name
  2138. @old_graphic = @dgraphic
  2139. update
  2140. end
  2141. #----------------------------------------------------------------------------
  2142. # • visible = (boolean)
  2143. # * boolean : true ou false
  2144. # Tornar vísivel ou não o cursor do Mouse.
  2145. #----------------------------------------------------------------------------
  2146. def visible=(boolean)
  2147. API::MouseShowCursor.call(boolean.boolean)
  2148. end
  2149. #--------------------------------------------------------------------------
  2150. # • graphic(graphic_set)
  2151. # graphic_set : Se for número é um ícone; Se for string é uma imagem.
  2152. #--------------------------------------------------------------------------
  2153. def graphic(graphic_set)
  2154. @cursor.set_graphic = graphic_set
  2155. @dgraphic = graphic_set
  2156. end
  2157. #--------------------------------------------------------------------------
  2158. # • show(visible)
  2159. # visible : True - para mostrar o mouse | False - para esconder o mouse.
  2160. #--------------------------------------------------------------------------
  2161. def show(visible=true)
  2162. @cursor.visible = visible
  2163. end
  2164. #--------------------------------------------------------------------------
  2165. # • update (Atualização das coordenadas)
  2166. #--------------------------------------------------------------------------
  2167. def update
  2168. return if @cursor.nil?
  2169. @cursor.x, @cursor.y = position
  2170. end
  2171. #--------------------------------------------------------------------------
  2172. # • Retorna a variável '@cursor' que tem como valor a classe [Sprite].
  2173. #--------------------------------------------------------------------------
  2174. def cursor
  2175. @cursor
  2176. end
  2177. #--------------------------------------------------------------------------
  2178. # • x (Coordenada X do Mouse)
  2179. #--------------------------------------------------------------------------
  2180. def x
  2181. @cursor.x
  2182. end
  2183. #--------------------------------------------------------------------------
  2184. # • y (Coordenada Y do Mouse)
  2185. #--------------------------------------------------------------------------
  2186. def y
  2187. @cursor.y
  2188. end
  2189. #----------------------------------------------------------------------------
  2190. # • Elementos das coordenadas do mouse.
  2191. #----------------------------------------------------------------------------
  2192. def eachPos
  2193. yield(x, y, @cursor.z)
  2194. return nil
  2195. end
  2196. #--------------------------------------------------------------------------
  2197. # • position (Posição do Mouse!)
  2198. #--------------------------------------------------------------------------
  2199. def position
  2200. x, y = get_client_position
  2201. return x, y
  2202. end
  2203. #--------------------------------------------------------------------------
  2204. # • get_client_position (Posição original do Mouse!)
  2205. #--------------------------------------------------------------------------
  2206. def get_client_position
  2207. pos = [0, 0].pack('ll')
  2208. API::CursorPosition.call(pos)
  2209. API::ScreenToClient.call(WINDOW, pos)
  2210. return pos.unpack('ll')
  2211. end
  2212. #--------------------------------------------------------------------------
  2213. # • find_window (Tamanho da window)
  2214. #--------------------------------------------------------------------------
  2215. def find_window
  2216. game_name = '\0' * 256
  2217. API::ReadIni.call('Game', 'Title', '', game_name, 255, '.\\Game.ini')
  2218. game_name.delete!('\0') ensure game_name
  2219. return API::FindWindow.call('RGSS Player', game_name)
  2220. end
  2221. #--------------------------------------------------------------------------
  2222. # • Verificação se o mouse está na área de um determinado objeto.
  2223. #--------------------------------------------------------------------------
  2224. def in_area?(object_sprite)
  2225. return @cursor.x.between?(object_sprite.x, object_sprite.x + object_sprite.width) &&
  2226. @cursor.y.between?(object_sprite.y, object_sprite.y + object_sprite.height)
  2227. end
  2228. #----------------------------------------------------------------------------
  2229. # • Verificar se o mouse está em determinada área
  2230. #----------------------------------------------------------------------------
  2231. def area?(x, y, width, height)
  2232. return @cursor.x.between?(x, x + width) &&
  2233. @cursor.y.between?(y, y + height)
  2234. end
  2235. #----------------------------------------------------------------------------
  2236. # • Mudar posição do cursor.
  2237. #----------------------------------------------------------------------------
  2238. def set_mouse(pos)
  2239. SetCursorPos.call(pos.x, pos.y)
  2240. update
  2241. @cursor.x = @pos.x
  2242. @cursor.y = @pos.y
  2243. end
  2244. WINDOW = find_window
  2245. end
  2246. #==============================================================================
  2247. # • Sprite_Mouse
  2248. #==============================================================================
  2249. Dax.register(:sprite_mouse)
  2250. class Sprite_Mouse < Sprite
  2251. #----------------------------------------------------------------------------
  2252. # • Variáveis públicas da instância.
  2253. #----------------------------------------------------------------------------
  2254. attr_accessor :set_graphic # definir o gráfico.
  2255. #----------------------------------------------------------------------------
  2256. # • Inicialização dos objetos.
  2257. #----------------------------------------------------------------------------
  2258. def initialize(graphic, x, y, z)
  2259. super(nil)
  2260. @set_graphic = graphic
  2261. if @set_graphic.is_a?(Fixnum)
  2262. self.bitmap = Bitmap.new(24, 24)
  2263. self.bitmap.draw_icon(@set_graphic, 0, 0)
  2264. elsif @set_graphic.is_a?(NilClass) or @set_graphic == ""
  2265. self.bitmap = Bitmap.new(1, 1)
  2266. elsif @set_graphic.is_a?(String)
  2267. self.bitmap = Cache.system(@set_graphic)
  2268. end
  2269. self.x, self.y, self.z = x, y, z
  2270. @older = @set_graphic
  2271. end
  2272. #----------------------------------------------------------------------------
  2273. # • Renovação dos objetos.
  2274. #----------------------------------------------------------------------------
  2275. def dispose
  2276. self.bitmap.dispose
  2277. super
  2278. end
  2279. #----------------------------------------------------------------------------
  2280. # • Atualização dos objetos.
  2281. #----------------------------------------------------------------------------
  2282. def update
  2283. super
  2284. unless @older == @set_graphic
  2285. if @set_graphic.is_a?(Fixnum)
  2286. self.bitmap = Bitmap.new(24, 24)
  2287. self.bitmap.draw_icon(@set_graphic, 0, 0)
  2288. elsif @set_graphic.is_a?(NilClass) or @set_graphic == ""
  2289. self.bitmap = Bitmap.new(1, 1)
  2290. elsif @set_graphic.is_a?(String)
  2291. self.bitmap = Cache.system(@set_graphic)
  2292. end
  2293. @older = @set_graphic
  2294. end
  2295. end
  2296. end
  2297. #==============================================================================
  2298. # • Object
  2299. #==============================================================================
  2300. Dax.register(:object)
  2301. class Object
  2302. #----------------------------------------------------------------------------
  2303. # • O que irá ocorrer caso o mouse esteja sobre uma sprite.
  2304. # Tem que ser um objeto Sprite.
  2305. #----------------------------------------------------------------------------
  2306. def if_mouse_over(&block)
  2307. return if Mouse.cursor.nil?
  2308. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  2309. over ||= false
  2310. if Mouse.in_area?(self)
  2311. block.call
  2312. over = true
  2313. else
  2314. over = false
  2315. end
  2316. yield over
  2317. end
  2318. #----------------------------------------------------------------------------
  2319. # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao clicar.
  2320. # Tem que ser um objeto Sprite.
  2321. # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
  2322. # EXPLICAÇÕES NO FINAL DO SCRIPT.
  2323. #----------------------------------------------------------------------------
  2324. def if_mouse_click(button=:left, &block)
  2325. return if Mouse.cursor.nil?
  2326. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  2327. button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
  2328. block.call if Mouse.in_area?(self) and trigger?(button)
  2329. end
  2330. #----------------------------------------------------------------------------
  2331. # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao pressionar.
  2332. # Tem que ser um objeto Sprite.
  2333. # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
  2334. #----------------------------------------------------------------------------
  2335. def if_mouse_press(button=:left, &block)
  2336. return if Mouse.cursor.nil?
  2337. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  2338. button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
  2339. block.call if Mouse.in_area?(self) and press?(button)
  2340. end
  2341. #----------------------------------------------------------------------------
  2342. # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao ficar clicando.
  2343. # Tem que ser um objeto Sprite.
  2344. # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
  2345. #----------------------------------------------------------------------------
  2346. def if_mouse_repeat(button=:left, &block)
  2347. return if Mouse.cursor.nil?
  2348. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  2349. button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
  2350. block.call if Mouse.in_area?(self) and repeat?(button)
  2351. end
  2352. #----------------------------------------------------------------------------
  2353. # • Trigger
  2354. # * key : Chave.
  2355. # Você também pode usá-lo como condição para executar tal bloco;
  2356. #----------------------------------------------------------------------------
  2357. # trigger?(key) { bloco que irá executar }
  2358. #----------------------------------------------------------------------------
  2359. def trigger?(key, &block)
  2360. ckey = key.is_a?(Symbol) ? Input.trigger?(key) : Key.trigger?(key)
  2361. return ckey unless block_given?
  2362. block.call if ckey
  2363. end
  2364. #----------------------------------------------------------------------------
  2365. # • Press
  2366. # * key : Chave.
  2367. # Você também pode usá-lo como condição para executar tal bloco;
  2368. #----------------------------------------------------------------------------
  2369. # press?(key) { bloco que irá executar. }
  2370. #----------------------------------------------------------------------------
  2371. def press?(key, &block)
  2372. ckey = key.is_a?(Symbol) ? Input.press?(key) : Key.press?(key)
  2373. return ckey unless block_given?
  2374. block.call if ckey
  2375. end
  2376. #----------------------------------------------------------------------------
  2377. # • Repeat
  2378. # * key : Chave.
  2379. # Você também pode usá-lo como condição para executar tal bloco;
  2380. #----------------------------------------------------------------------------
  2381. # repeat?(key) { bloco que irá executar. }
  2382. #----------------------------------------------------------------------------
  2383. def repeat?(key)
  2384. ckey = key.is_a?(Symbol) ? Input.repeat?(key) : Key.repeat?(key)
  2385. return ckey unless block_given?
  2386. block.call if ckey
  2387. end
  2388. #----------------------------------------------------------------------------
  2389. # • Retorna em forma de número os valores true ou false. E caso seja
  2390. # 0 ou 1.. retorna a true ou false.
  2391. # Se for true, retorna a 1.
  2392. # Se for false, retorna a 0.
  2393. # Se for 1, retorna a true.
  2394. # Se for 0, retorna a false.
  2395. #----------------------------------------------------------------------------
  2396. def boolean
  2397. return self.is_a?(Integer) ? self == 0 ? false : 1 : self ? 1 : 0
  2398. end
  2399. #----------------------------------------------------------------------------
  2400. # • Converte para a classe Position.
  2401. #----------------------------------------------------------------------------
  2402. def position
  2403. return Position.new(self, self) if self.is_a?(Numeric)
  2404. return Position.new(self.x, self.y) if self.is_a?(Sprite) or self.is_a?(Window_Base)
  2405. return Position.new(self[0], self[1]) if self.is_a?(Array)
  2406. return Position.new(0, 0)
  2407. end
  2408. #----------------------------------------------------------------------------
  2409. # • Transforma em cor.
  2410. # Se for uma Array. Exemplo: [128, 174, 111].color =># Color.new(128, 174, 111)
  2411. # Se for uma String. Exemplo: "ffffff".color =># Color.new(255,255,255)
  2412. #----------------------------------------------------------------------------
  2413. def color
  2414. return Color.new(*self) if self.is_a?(Array)
  2415. return Color.new.hex(self) if self.is_a?(String)
  2416. end
  2417. end
  2418. #==============================================================================
  2419. # • Entries
  2420. #==============================================================================
  2421. Dax.register(:entries)
  2422. class Entries
  2423. #----------------------------------------------------------------------------
  2424. # • Variável pública da instância.
  2425. #----------------------------------------------------------------------------
  2426. attr_accessor :file
  2427. attr_reader :get_number
  2428. attr_reader :get_file
  2429. attr_reader :get_array
  2430. attr_reader :name
  2431. #----------------------------------------------------------------------------
  2432. # • Inicialização dos objetos.
  2433. #----------------------------------------------------------------------------
  2434. def initialize(directory, typefile)
  2435. return unless FileTest.directory?(directory)
  2436. @file = Dir.glob(directory + "/*.{" + typefile + "}")
  2437. @file.each_index { |i| @get_number = i.to_i }
  2438. @file.each { |i| @get_file = i.to_s }
  2439. @file.each_with_index { |i| @get_array = i }
  2440. @name = split @file[0]
  2441. end
  2442. #----------------------------------------------------------------------------
  2443. # • Split
  2444. #----------------------------------------------------------------------------
  2445. def split(file)
  2446. file.to_s.split('/').last
  2447. end
  2448. #----------------------------------------------------------------------------
  2449. # • Obter nome.
  2450. #----------------------------------------------------------------------------
  2451. def name(id)
  2452. return if @file.nil?
  2453. return split(@file[id])
  2454. end
  2455. end
  2456. #==============================================================================
  2457. # • DRGSS | Comandos do RGSS...
  2458. #==============================================================================
  2459. Dax.register(:drgss)
  2460. module DRGSS
  2461. extend self
  2462. #----------------------------------------------------------------------------
  2463. # • **** Método ainda não explicado ****
  2464. #----------------------------------------------------------------------------
  2465. def recursive_delete(dir)
  2466. files = []
  2467. Dir.foreach(dir) do |fname|
  2468. next if fname == '.' || fname == '..'
  2469. path = dir + '/' + fname
  2470. if File.directory?(path)
  2471. puts "dir #{path}"
  2472. recursive_delete(path)
  2473. else
  2474. puts "file #{path}"
  2475. files << path
  2476. end
  2477. end
  2478. files.each do |path|
  2479. msgbox "delete file #{path}"
  2480. end
  2481. msgbox "delete dir #{dir}"
  2482. Dir.rmdir(dir)
  2483. end
  2484. #----------------------------------------------------------------------------
  2485. # • **** Método ainda não explicado ****
  2486. #----------------------------------------------------------------------------
  2487. def delete(directory)
  2488. if File.directory?(directory)
  2489. Dir.foreach(directory) do |file_or_directory|
  2490. File.delete(directory+"/"+file_or_directory) if file_or_directory != "." and file_or_directory != ".."
  2491. end
  2492. else
  2493. begin
  2494. File.delete(directory) if File.new(directory).stat.size == 0
  2495. rescue
  2496. msgbox "#{$!} Erro ao excluir um arquivo de tamanho zero."
  2497. end
  2498. end
  2499. end
  2500. #----------------------------------------------------------------------------
  2501. # • Extrair scripts do Database para um arquivo de extensão de texto.
  2502. # options : Caso você deixe assim: {folder: "NM"}
  2503. # NM => Nome da pasta na qual os arquivos irão.
  2504. #----------------------------------------------------------------------------
  2505. def extract_scripts(type=".txt",options={})
  2506. except = options[:except] || []
  2507. folder = options[:folder] || ""
  2508. id = 0 #
  2509. $RGSS_SCRIPTS.each do |script|
  2510. name = script[1]
  2511. data = script[3]
  2512. next if except.include? name or name.empty? or data.empty?
  2513. filename = sprintf("%03d", id) + "_" + name
  2514. p "Writing: #{filename}"
  2515. File.open(folder+filename+"#{type}", "wb") do |file|
  2516. file.write data
  2517. end
  2518. id += 1
  2519. end
  2520. end
  2521. #----------------------------------------------------------------------------
  2522. # • Guarda todos os scripts do Database num arquivo;
  2523. #----------------------------------------------------------------------------
  2524. def keep_scripts_in_file(filename="RGSS.rvdata2")
  2525. unless FileTest.exist?(filename)
  2526. self.extract_scripts(".txt")
  2527. file = File.open(filename, "wb")
  2528. Dir.glob("./*.{txt}").each_with_index { |v,i|
  2529. next unless v.match(/(\d+){3}_(\w*)/)
  2530. file.write(IO.readlines(v).to_s)
  2531. File.delete(v)
  2532. }
  2533. file.close
  2534. end
  2535. end
  2536. #----------------------------------------------------------------------------
  2537. # • **** Método ainda não explicado ****
  2538. #----------------------------------------------------------------------------
  2539. def load_scripts(type=".txt",options={})
  2540. skip = options[:skip] || []
  2541. folder = options[:folder] || ""
  2542. begin
  2543. Dir.foreach(folder) do |file|
  2544. file_id = file[0,3].to_i
  2545. break if file_id == options[:limit]
  2546. next if file == "." or file == ".." or File.extname(file) != "#{type}" or skip.include?(file_id)
  2547. r = load(folder+"#{file}")
  2548. p "Loaded: #{r}"
  2549. end
  2550. end
  2551. end
  2552. end
  2553. #==============================================================================
  2554. # • Backup Complete
  2555. #==============================================================================
  2556. Dax.register(:backup)
  2557. module Backup
  2558. extend self
  2559. #----------------------------------------------------------------------------
  2560. # • Criar as pastas.
  2561. #----------------------------------------------------------------------------
  2562. def make_past
  2563. Dir.mkdir("Backup") unless File.directory?("Backup")
  2564. ["Data", "System", "Movies", "Graphics", "Audio", "Audio/BGM", "Audio/BGS", "Audio/ME", "Audio/SE"].each { |i|
  2565. Dir.mkdir("Backup/#{i}") unless File.directory?("Backup/#{i}")
  2566. }
  2567. end
  2568. #----------------------------------------------------------------------------
  2569. # • Copiar a pasta system.
  2570. #----------------------------------------------------------------------------
  2571. def system
  2572. list = Dir.glob('System/*')
  2573. list.size.times { |i|API::CopyFile.call(list[i], "Backup/" + list[i], true.boolean)}
  2574. end
  2575. #----------------------------------------------------------------------------
  2576. # • Copiar a pasta movie.
  2577. #----------------------------------------------------------------------------
  2578. def movies
  2579. movies = Dir.glob("Movies/*")
  2580. movies.size.times { |i| API::CopyFile.call(movies[i], "Backup/" + movies[i], true.boolean)}
  2581. end
  2582. #----------------------------------------------------------------------------
  2583. # • Copiar a pasta audio
  2584. #----------------------------------------------------------------------------
  2585. def audio
  2586. bgm = Dir.glob('Audio/BGM/*')
  2587. bgs = Dir.glob('Audio/BGS/*')
  2588. me = Dir.glob('Audio/ME/*')
  2589. se = Dir.glob('Audio/SE/*')
  2590. bgm.size.times { |i| API::CopyFile.call(bgm[i], "Backup/" + bgm[i], true.boolean)}
  2591. bgs.size.times { |i| API::CopyFile.call(bgs[i], "Backup/" + bgs[i], true.boolean) }
  2592. me.size.times { |i| API::CopyFile.call(me[i], "Backup/" + me[i], true.boolean) }
  2593. se.size.times { |i| API::CopyFile.call(se[i], "Backup/" + se[i], true.boolean) }
  2594. end
  2595. #----------------------------------------------------------------------------
  2596. # • Copiar a pasta Data.
  2597. #----------------------------------------------------------------------------
  2598. def data
  2599. data = Dir.glob('Data/*')
  2600. data.size.times { |i| API::CopyFile.call(data[i], "Backup/" + data[i], true.boolean) }
  2601. end
  2602. #----------------------------------------------------------------------------
  2603. # • Copiar a pasta Graphic.
  2604. #----------------------------------------------------------------------------
  2605. def graphics
  2606. ["Animations", "Battlebacks1", "Battlebacks2", "Battlers", "Characters",
  2607. "Faces", "Parallaxes", "Pictures", "System", "Titles1", "Titles2",
  2608. "Tilesets"].each { |dirs|
  2609. Dir.mkdir("Backup/Graphics/#{dirs}") unless File.directory?("Backup/Graphics/#{dirs}")
  2610. d = Dir.glob("Graphics/#{dirs}/*")
  2611. d.size.times { |v| API::CopyFile.call(d[v], "Backup/" + d[v], true.boolean) }
  2612. }
  2613. end
  2614. #----------------------------------------------------------------------------
  2615. # • Executar
  2616. #----------------------------------------------------------------------------
  2617. def run(audios=false, graphic=false)
  2618. unless $TEST
  2619. DRGSS.delete("Backup")
  2620. else
  2621. make_past
  2622. movies
  2623. data
  2624. system
  2625. audio if audios
  2626. graphics if graphic
  2627. end
  2628. end
  2629. end
  2630. #==============================================================================
  2631. # * SceneManager
  2632. #==============================================================================
  2633. Dax.register :scenemanager
  2634. if defined?("SceneManager")
  2635. class << SceneManager
  2636. #--------------------------------------------------------------------------
  2637. # • **** Método ainda não explicado ****
  2638. #--------------------------------------------------------------------------
  2639. def symbol(scene_symbol)
  2640. eval("self.call(#{scene_symbol.to_s})")
  2641. end
  2642. end
  2643. end
  2644. #==============================================================================
  2645. # • Sprite_Text
  2646. #==============================================================================
  2647. Dax.register(:sprite_text)
  2648. class Sprite_Text < Sprite
  2649. #----------------------------------------------------------------------------
  2650. # • Variáveis públicas da instância.
  2651. #----------------------------------------------------------------------------
  2652. attr_accessor :text # Mudar de texto...
  2653. attr_accessor :align
  2654. #----------------------------------------------------------------------------
  2655. # • Inicialização dos objetos.
  2656. #----------------------------------------------------------------------------
  2657. def initialize(x, y, width, height, text, align=0)
  2658. super([width, height])
  2659. self.x, self.y = x, y
  2660. @text = text
  2661. @align = align
  2662. self.bitmap.draw_text_rect(@text, align)
  2663. end
  2664. #----------------------------------------------------------------------------
  2665. # • Renovação dos objetos.
  2666. #----------------------------------------------------------------------------
  2667. def dispose
  2668. self.bitmap.dispose
  2669. super
  2670. end
  2671. #----------------------------------------------------------------------------
  2672. # • Atualização dos objetos.
  2673. #----------------------------------------------------------------------------
  2674. def update
  2675. self.bitmap.clear
  2676. super
  2677. self.bitmap.draw_text_rect(@text, @align)
  2678. end
  2679. def name=(value=nil)
  2680. self.bitmap.font.name = name || Font.default_name.to_s
  2681. end
  2682. #----------------------------------------------------------------------------
  2683. # • Negrito na fonte?
  2684. #----------------------------------------------------------------------------
  2685. def bold=(value=nil)
  2686. self.bitmap.font.bold = value || true
  2687. end
  2688. #----------------------------------------------------------------------------
  2689. # • Itálico na fonte?
  2690. #----------------------------------------------------------------------------
  2691. def italic=(value=nil)
  2692. self.bitmap.font.italic = value || true
  2693. end
  2694. #----------------------------------------------------------------------------
  2695. # • Sombra na fonte?
  2696. #----------------------------------------------------------------------------
  2697. def shadow=(value=nil)
  2698. self.bitmap.font.shadow = value || true
  2699. end
  2700. #----------------------------------------------------------------------------
  2701. # • Borda na fonte?
  2702. #----------------------------------------------------------------------------
  2703. def outline=(value=nil)
  2704. self.bitmap.font.outline = value || true
  2705. end
  2706. #----------------------------------------------------------------------------
  2707. # • Mudar a cor da fonte:
  2708. #----------------------------------------------------------------------------
  2709. def color=(color=nil)
  2710. self.bitmap.font.color = color || -1.color
  2711. end
  2712. #----------------------------------------------------------------------------
  2713. # • Mudar a cor da borda da fonte.
  2714. #----------------------------------------------------------------------------
  2715. def out_color=(out_color=nil)
  2716. self.bitmap.font.out_color = out_color || 7.color
  2717. end
  2718. end
  2719. #==============================================================================
  2720. # • Sprite_Icon
  2721. #==============================================================================
  2722. Dax.register(:sprite_icon)
  2723. class Sprite_Icon < Sprite
  2724. #----------------------------------------------------------------------------
  2725. # • Variáveis públicas da instância.
  2726. #----------------------------------------------------------------------------
  2727. attr_accessor :icon_index # Mudar de ícone.
  2728. attr_accessor :enabled # Tornar opaco ou não.
  2729. attr_accessor :filename # Nome do arquivo.
  2730. #----------------------------------------------------------------------------
  2731. # • Inicialização dos objetos.
  2732. #----------------------------------------------------------------------------
  2733. def initialize(icon_index, x, y, enabled=true)
  2734. super([24, 24])
  2735. self.x, self.y = x, y
  2736. @icon_index = icon_index.to_i
  2737. @enabled = enabled
  2738. self.bitmap.draw_icon(@icon_index, 0, 0, @enabled)
  2739. end
  2740. #----------------------------------------------------------------------------
  2741. # • Renovação dos objetos.
  2742. #----------------------------------------------------------------------------
  2743. def dispose
  2744. self.bitmap.dispose
  2745. super
  2746. end
  2747. #----------------------------------------------------------------------------
  2748. # • Atualização dos objetos.
  2749. #----------------------------------------------------------------------------
  2750. def update
  2751. self.bitmap.clear
  2752. super
  2753. self.bitmap.draw_icon(@icon_index, 0, 0, @enabled, @filename)
  2754. end
  2755. end
  2756. #==============================================================================
  2757. # • Opacity
  2758. #==============================================================================
  2759. Dax.register(:opacity)
  2760. module Opacity
  2761. extend self
  2762. @key ||= {}
  2763. #----------------------------------------------------------------------------
  2764. # • Efeito de opacidade que vai aumentando e diminuindo.
  2765. # sprite : Objeto na qual sofrerá o efeito. [Sprite]
  2766. # speed : Velocidade na qual o efeito irá acontencer.
  2767. # max : Valor máximo na qual irá ser atingido.
  2768. # min : Valor minímo na qual irá ser atingido.
  2769. #----------------------------------------------------------------------------
  2770. def sprite_opacity(sprite, speed, max, min, hash=nil)
  2771. @key[hash.nil? ? hash.__id__ : hash] || false
  2772. unless @key[hash]
  2773. sprite.opacity += speed unless sprite.opacity >= max
  2774. @key[hash] = sprite.opacity >= max
  2775. else
  2776. sprite.opacity -= speed unless sprite.opacity <= min
  2777. @key[hash] = false if sprite.opacity <= min
  2778. end
  2779. end
  2780. #----------------------------------------------------------------------------
  2781. # • Efeito de opacidade por fora.
  2782. # sprite : Objeto na qual sofrerá o efeito. [Sprite]
  2783. # speed : Velocidade na qual o efeito irá acontencer.
  2784. # max : Valor máximo na qual irá ser atingido.
  2785. #----------------------------------------------------------------------------
  2786. def sprite_opacity_out(sprite, speed, max)
  2787. sprite.opacity += speed unless sprite.opacity >= max
  2788. end
  2789. #----------------------------------------------------------------------------
  2790. # • Efeito de opacidade por dentro.
  2791. # sprite : Objeto na qual sofrerá o efeito. [Sprite]
  2792. # speed : Velocidade na qual o efeito irá acontencer.
  2793. # min : Valor minímo na qual irá ser atingido.
  2794. #----------------------------------------------------------------------------
  2795. def sprite_opacity_in(sprite, speed, min)
  2796. sprite.opacity -= speed unless sprite.opacity <= min
  2797. end
  2798. #----------------------------------------------------------------------------
  2799. # • Limpar variável.
  2800. #----------------------------------------------------------------------------
  2801. def clear
  2802. @key.clear
  2803. end
  2804. end
  2805. #==============================================================================
  2806. # • Read
  2807. #==============================================================================
  2808. Dax.register(:read, "Dax")
  2809. module Read
  2810. extend self
  2811. #----------------------------------------------------------------------------
  2812. # • Verificar valor numérico após uma palavra em um arquivo.
  2813. #----------------------------------------------------------------------------
  2814. def numeric(file, tag)
  2815. IO.readlines(file).each do |line|
  2816. return $1.to_i if line.match(/#{tag} (\d+)/)
  2817. end
  2818. end
  2819. #----------------------------------------------------------------------------
  2820. # • Verificar valor de uma palavra(string única) após uma palavra em um arquivo
  2821. #----------------------------------------------------------------------------
  2822. def string(file, tag)
  2823. IO.readlines(file).each do |line|
  2824. return $1.to_s if line.match(/#{tag} (\w+)/)
  2825. end
  2826. end
  2827. #----------------------------------------------------------------------------
  2828. # • Verificar um conteúdo após uma palavra de um arquivo.
  2829. #----------------------------------------------------------------------------
  2830. def content(file, tag)
  2831. IO.readlines(file).each do |line|
  2832. return $1 if line.match(/#{tag} ([^>]*)/)
  2833. end
  2834. end
  2835. #----------------------------------------------------------------------------
  2836. # • Multiplo número..
  2837. #----------------------------------------------------------------------------
  2838. def multiple_numeric(file, tag)
  2839. IO.readlines(file).each do |line|
  2840. return [$1.to_i, $2.to_i] if line.match(/#{tag} (\d+), (\d+)/)
  2841. end
  2842. end
  2843. #----------------------------------------------------------------------------
  2844. # • Multiplo string..
  2845. #----------------------------------------------------------------------------
  2846. def multiple_string(file, tag)
  2847. IO.readlines(file).each do |line|
  2848. return [$1.to_s, $2.to_s] if line.match(/#{tag} (\w+), (\w+)/)
  2849. end
  2850. end
  2851. #----------------------------------------------------------------------------
  2852. # • Triplo número.
  2853. #----------------------------------------------------------------------------
  2854. def triple_numeric(file, tag)
  2855. IO.readlines(file).each do |line|
  2856. return [$1.to_i, $2.to_i, $3.to_i] if line.match(/#{tag} (\d+), (\d+), (\d+)/)
  2857. end
  2858. end
  2859. #----------------------------------------------------------------------------
  2860. # • Triplo string.
  2861. #----------------------------------------------------------------------------
  2862. def triple_string(file, tag)
  2863. IO.readlines(file).each do |line|
  2864. return [$1.to_s, $2.to_s, $3.to_s] if line.match(/#{tag} (\w+), (\w+), (\w+)/)
  2865. end
  2866. end
  2867. #----------------------------------------------------------------------------
  2868. # • Se é verdairo ou falo.
  2869. #----------------------------------------------------------------------------
  2870. def of(file, tag)
  2871. IO.readlines(file).each do |line|
  2872. return $1.to_s == "true" ? true : false if line.match(/#{tag} ([^>]*)/)
  2873. end
  2874. end
  2875. end
  2876. #==============================================================================
  2877. # • Background
  2878. #==============================================================================
  2879. Dax.register :background
  2880. module Background
  2881. extend self
  2882. @background ||= {}
  2883. #----------------------------------------------------------------------------
  2884. # • Plano de fundo padrão...
  2885. #----------------------------------------------------------------------------
  2886. def default(alpha=128, key=nil)
  2887. @background[key.__id__] = Sprite.new
  2888. @background[key.__id__].bitmap = SceneManager.background_bitmap
  2889. @background[key.__id__].color.set(16, 16, 16, alpha)
  2890. end
  2891. #----------------------------------------------------------------------------
  2892. # • Plano de fundo padrão renovado.
  2893. #----------------------------------------------------------------------------
  2894. def default_dispose
  2895. return if @background.nil?
  2896. @background.each_value(&:dispose)
  2897. end
  2898. # Definir um sprite de fundo
  2899. def define_back(color="ffffff".color, key=nil)
  2900. @background[key.__id__] = Sprite.new([Graphics.width, Graphics.height])
  2901. @background[key.__id__].bitmap.fill_rect(@background[key.__id__].rect, color)
  2902. end
  2903. end
  2904. #==============================================================================
  2905. # * Window_Base
  2906. #==============================================================================
  2907. Dax.register(:window_base)
  2908. Dax.if_defined?("Window_Base") {
  2909. class Window_Base < Window
  2910. #----------------------------------------------------------------------------
  2911. # • Slide pela direita.
  2912. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  2913. #----------------------------------------------------------------------------
  2914. def slide_right(speed, point)
  2915. self.x += speed unless self.x >= point
  2916. end
  2917. #----------------------------------------------------------------------------
  2918. # • Slide pela esquerda.
  2919. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  2920. #----------------------------------------------------------------------------
  2921. def slide_left(speed, point)
  2922. self.x -= speed unless self.x <= point
  2923. end
  2924. #----------------------------------------------------------------------------
  2925. # • Slide por cima.
  2926. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  2927. #----------------------------------------------------------------------------
  2928. def slide_up(speed, point)
  2929. self.y -= speed unless self.y <= point
  2930. end
  2931. #----------------------------------------------------------------------------
  2932. # • Slide por baixo.
  2933. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  2934. #----------------------------------------------------------------------------
  2935. def slide_down(speed, point)
  2936. self.y += speed unless self.y >= point
  2937. end
  2938. #----------------------------------------------------------------------------
  2939. # • Define aqui uma posição fixa para um objeto.
  2940. # command : Retorna a uma base padrão.
  2941. #----------------------------------------------------------------------------
  2942. def position(command=0)
  2943. return if command.nil?
  2944. case command
  2945. # Imagem ficará no canto esquerdo superior. Posição X
  2946. when 0 then self.x = 0
  2947. # A posição X ficará no centro da tela.
  2948. when 1 then self.x = DMath.get_x_center_screen(self.width)
  2949. # A posição X ficará no canto direito superior.
  2950. when 2 then self.x = Graphics.width - self.width
  2951. # A posição Y ficará no canto esquerdo inferior.
  2952. when 3 then self.y = 0
  2953. # Posicionar o Y para ficar no centro.
  2954. when 4 then self.y = DMath.get_y_center_screen(self.height)
  2955. # Posicionar o Y para ficar no fundo da tela.
  2956. when 5 then self.y = Graphics.height - self.height
  2957. # Posicionar a imagem no centro da tela.
  2958. when :center
  2959. self.x = (Graphics.width - self.width) / 2
  2960. self.y = Graphics.height / 2 - self.height / 2
  2961. # Posicionar no centro esquerdo da tela.
  2962. when :center_left
  2963. self.x = 0
  2964. self.y = (Graphics.height - self.height) / 2
  2965. # Posicionar no centro direito da tela.
  2966. when :center_right
  2967. self.x = Graphics.width - self.height
  2968. self.y = (Graphics.height - self.height) / 2
  2969. end
  2970. end
  2971. end
  2972. }
  2973. #==============================================================================
  2974. # • Sound Base
  2975. #==============================================================================
  2976. Dax.register(:sound_base)
  2977. module Sound_Base
  2978. #----------------------------------------------------------------------------
  2979. # • Função do módulo.
  2980. #----------------------------------------------------------------------------
  2981. module_function
  2982. #----------------------------------------------------------------------------
  2983. # • Executar um som.
  2984. #----------------------------------------------------------------------------
  2985. def play(name, volume, pitch, type = :se)
  2986. case type
  2987. when :se ; RPG::SE.new(name, volume, pitch).play rescue valid?(name)
  2988. when :me ; RPG::ME.new(name, volume, pitch).play rescue valid?(name)
  2989. when :bgm ; RPG::BGM.new(name, volume, pitch).play rescue valid?(name)
  2990. when :bgs ; RPG::BGS.new(name, volume, pitch).play rescue valid?(name)
  2991. end
  2992. end
  2993. #----------------------------------------------------------------------------
  2994. # • Validar som.
  2995. #----------------------------------------------------------------------------
  2996. def valid?(name)
  2997. raise("Arquivo de som não encontrado: #{name}")
  2998. exit
  2999. end
  3000. end
  3001. #==============================================================================
  3002. # • Position.
  3003. #==============================================================================
  3004. Dax.register :position
  3005. class Position
  3006. #----------------------------------------------------------------------------
  3007. # • Variáveis públicas da instância.
  3008. #----------------------------------------------------------------------------
  3009. attr_accessor :x # Variável que retorna ao valor que indica a posição X.
  3010. attr_accessor :y # Variável que retorna ao valor que indica a posição Y.
  3011. #----------------------------------------------------------------------------
  3012. # • Inicialização dos objetos.
  3013. #----------------------------------------------------------------------------
  3014. def initialize(x, y)
  3015. @x = x || 0
  3016. @y = y || 0
  3017. end
  3018. #----------------------------------------------------------------------------
  3019. # • Somar com outra posição.
  3020. #----------------------------------------------------------------------------
  3021. def +(position)
  3022. position = position.position unless position.is_a?(Position)
  3023. Position.new(self.x + position.x, self.y + position.y)
  3024. end
  3025. #----------------------------------------------------------------------------
  3026. # • Subtrair com outra posição.
  3027. #----------------------------------------------------------------------------
  3028. def -(position)
  3029. position = position.position unless position.is_a?(Position)
  3030. Position.new(self.x - position.x, self.y - position.y)
  3031. end
  3032. #----------------------------------------------------------------------------
  3033. # • Multiplicar com outra posição.
  3034. #----------------------------------------------------------------------------
  3035. def *(position)
  3036. position = position.position unless position.is_a?(Position)
  3037. Position.new(self.x * position.x, self.y * position.y)
  3038. end
  3039. #----------------------------------------------------------------------------
  3040. # • Dividir com outra posição.
  3041. #----------------------------------------------------------------------------
  3042. def /(position)
  3043. position = position.position unless position.is_a?(Position)
  3044. return if (self.x or position.x or self.y or position.y) <= 0
  3045. Position.new(self.x / position.x, self.y / position.y)
  3046. end
  3047. #----------------------------------------------------------------------------
  3048. # • Comparar com outra posição.
  3049. #----------------------------------------------------------------------------
  3050. def ==(position)
  3051. position = position.position unless position.is_a?(Position)
  3052. return self.x == position.x && self.y == position.y
  3053. end
  3054. #----------------------------------------------------------------------------
  3055. # • Converter em string.
  3056. #----------------------------------------------------------------------------
  3057. def to_s
  3058. return "position x: #{self.x}\nposition y: #{self.y}"
  3059. end
  3060. end
  3061. #==============================================================================
  3062. # • Animation
  3063. #==============================================================================
  3064. Dax.register :animation
  3065. class Animation
  3066. attr_reader :size, :frame_size, :index, :max_width, :max_height
  3067. #----------------------------------------------------------------------------
  3068. # • Inicialização.
  3069. #----------------------------------------------------------------------------
  3070. def initialize(size, frame_size, wait=1)
  3071. @size = size
  3072. @frame_size = frame_size
  3073. @index = 0
  3074. @max_width = @size[0] / @frame_size[0]
  3075. @max_height = @size[1] / @frame_size[1]
  3076. @wait = wait
  3077. @time = 0
  3078. end
  3079. #----------------------------------------------------------------------------
  3080. # • Animação na horizontal.
  3081. #----------------------------------------------------------------------------
  3082. def horz
  3083. @time += 1 unless @time >= @wait
  3084. if @time >= @wait
  3085. @index = Rpg::Menu.cursor_up(@index, @max_width)
  3086. @time = 0
  3087. end
  3088. end
  3089. #----------------------------------------------------------------------------
  3090. # • Animação na vertical.
  3091. #----------------------------------------------------------------------------
  3092. def vert
  3093. @time += 1 unless @time >= @wait
  3094. if @time >= @wait
  3095. @index = Rpg::Menu.cursor_up(@index, @max_height)
  3096. @time = 0
  3097. end
  3098. end
  3099. end
  3100. #==============================================================================
  3101. # • Sprite_Anime_Horz
  3102. #==============================================================================
  3103. Dax.register :sprite_anime_horz
  3104. class Sprite_Anime_Horz < Sprite
  3105. #----------------------------------------------------------------------------
  3106. # • Inicialização dos objetos
  3107. # filename : Nome do arquivo.
  3108. # frame_size : Tamanho de cada frame.
  3109. # wait : Tempo de espera para mudar de um frame para outro.
  3110. #----------------------------------------------------------------------------
  3111. def initialize(filename, frame_size, wait=1)
  3112. @bitmap = Bitmap.new(filename)
  3113. super(frame_size)
  3114. @animation = Animation.new([@bitmap.width, @bitmap.height],
  3115. frame_size, wait)
  3116. end
  3117. #----------------------------------------------------------------------------
  3118. # • Renovação dos objetos.
  3119. #----------------------------------------------------------------------------
  3120. def dispose
  3121. self.bitmap.dispose
  3122. super
  3123. end
  3124. #----------------------------------------------------------------------------
  3125. # • Atualização dos objetos.
  3126. #----------------------------------------------------------------------------
  3127. def update
  3128. self.bitmap.clear
  3129. super
  3130. @animation.horz
  3131. rect = Rect.new(@animation.index % @animation.max_width * @animation.frame_size[0],
  3132. 0, *@animation.frame_size)
  3133. self.bitmap.blt(0, 0, @bitmap, rect)
  3134. end
  3135. end
  3136. #==============================================================================
  3137. # • Sprite_Anime_Vert
  3138. #==============================================================================
  3139. Dax.register :sprite_anime_vert
  3140. class Sprite_Anime_Vert < Sprite
  3141. #----------------------------------------------------------------------------
  3142. # • Inicialização dos objetos
  3143. # filename : Nome do arquivo.
  3144. # frame_size : Tamanho de cada frame.
  3145. # wait : Tempo de espera para mudar de um frame para outro.
  3146. #----------------------------------------------------------------------------
  3147. def initialize(filename, frame_size, wait=1)
  3148. @bitmap = Bitmap.new(filename)
  3149. super(frame_size)
  3150. @animation = Animation.new([@bitmap.width, @bitmap.height],
  3151. frame_size, wait)
  3152. end
  3153. #----------------------------------------------------------------------------
  3154. # • Renovação dos objetos.
  3155. #----------------------------------------------------------------------------
  3156. def dispose
  3157. self.bitmap.dispose
  3158. super
  3159. end
  3160. #----------------------------------------------------------------------------
  3161. # • Atualização dos objetos.
  3162. #----------------------------------------------------------------------------
  3163. def update
  3164. self.bitmap.clear
  3165. super
  3166. @animation.vert
  3167. rect = Rect.new(0,
  3168. @animation.index % @animation.max_height * @animation.frame_size[1], *@animation.frame_size)
  3169. self.bitmap.blt(0, 0, @bitmap, rect)
  3170. end
  3171. end
  3172. #==============================================================================
  3173. # • Desativar scripts : Para fazer, basta por no nome do script da lista,
  3174. # [D].
  3175. # • Salvar script em arquivo de texto : Para fazer, basta por no nome do script da lista,
  3176. # [S].
  3177. #==============================================================================
  3178. Dax.register(:disable_script)
  3179. $RGSS_SCRIPTS.each_with_index { |data, index|
  3180. if data.at(1).include?("[S]")
  3181. File.open("#{rgss.at(1)}.txt", "wb") { |file|
  3182. file.write(String($RGSS_SCRIPTS.at(index)[3]))
  3183. file.close
  3184. }
  3185. end
  3186. $RGSS_SCRIPTS.at(index)[2] = $RGSS_SCRIPTS.at(index)[3] = "" if data.at(1).include?("[D]")
  3187. }
  3188. #==============================================================================
  3189. # * DataManager
  3190. #==============================================================================
  3191. unless defined?(DataManager)
  3192. Mouse.start
  3193. Rpg.data_manager
  3194. else
  3195. class << DataManager
  3196. alias :new_init :init
  3197. def init
  3198. Mouse.start
  3199. new_init
  3200. end
  3201. end
  3202. end
  3203. #==============================================================================
  3204. # * Input
  3205. #==============================================================================
  3206. class << Input
  3207. alias :upft :update
  3208. def update
  3209. upft
  3210. Key.update
  3211. end
  3212. end
  3213. #==============================================================================
  3214. # • Graphics
  3215. #==============================================================================
  3216. class << Graphics
  3217. alias :uptf :update
  3218. def update
  3219. uptf
  3220. Mouse.update
  3221. end
  3222. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement