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