$imported = {} if $imported == nil
$imported["H87_UniversalModule"] = true
#==============================================================================
# ? Modulo di utility universale di Holy87
# versione 1.1
# Difficoltā utente: ???
#==============================================================================
# Questo č un modulo che serve principalmente a far funzionare alcuni script
# miei, ma puō essere utile anche come base per sviluppare in modo pių facile
# script di terzi. Tutte le funzioni dello script sono scritte in basso.
#==============================================================================
# ? Installazione
# Installare questo script sotto Materials e prima del Main.
#==============================================================================
# ? Istruzioni
# Usare da script o da chiama evento le seguenti chiamate: quando vedi delle
# parentesi quadre [] a dei valori significa che č facoltativo.
#
#
# ? Valori universali di gioco
# L'oggetto $game_settings č una classe universale che salva e conserva un
# valore indipendentemente dal salvataggio. Puō essere usato per memorizzare
# impostazioni nella schermata del titolo, sbloccare gli extra o gestire gli
# obiettivi, o qualsiasi cosa ti venga in mente.
#
# ? $game_settings[quellochevuoi] = ilvalorechevuoi
# memorizza il valore che vuoi, e viene automaticamente salvato nel file
# game_settings.rvdata, che si trova nella cartella del gioco. Il valore
# viene salvato anche se la partita non č stata salvata.
#
# ? $game_settings[quellochevuoi]
# restituisce il valore di quellochevuoi.
#
# ? Chiamate di sistema
#
# ? Win.version:
# restituisce un decimale con il numero di versione di Windows in uso.
# 5.0 -> Windows 2000
# 5.1 -> Windows Xp
# 5.2 -> Windows Xp (64 bit)
# 6.0 -> Windows Vista
# 6.1 -> Windows 7
# 6.2 -> Windows 8
#
# ? Win.username
# Restituisce una stringa con nome utente di Windows attualmente in uso
#
# ? Win.homepath
# Restituisce il percorso utente del computer. Esempio:
# C:/Users/nomeutente/ in Windows Vista, 7 e 8
# C:/Documents and Settings/nomeutente in Windows 2000 e Xp
#
# ? Win.shutdown[(mode)]
# Spegne il computer, a seconda di mode (se si omette č 0):
# 0: spegnimento normale
# 1: riavvio
# 2: ibernazione
#
# ? Win.open(filepath)
# Apre una cartella o un file sul PC. Specificare il percorso in filepath
# Esempi:
# Win.open(C:/Windows/system32/calc.exe) avvierā la calcolatrice
# Win.open(homepath+"/Desktop") aprirā la cartella del desktop
#
# ? Win.temp_flush(nomefile)
# elimina il file dai file temporanei di internet. Utilizzarlo prima di un
# download di un file che viene aggiornato molto spesso.
#
# ? Win.datenow[(partition)]
# Restituisce la data attuale in stringa in formato "gg/mm/aaaa". Se
# viene inserito partition come valore:
# 0: restituisce il numero del giorno in intero
# 1: restituisce il numero del mese attuale in intero
# 2: restituisce il numero dell'anno attuale in intero
#
# ? Win.timenow[(partition)]
# Restituisce l'ora attuale in formato "hh:mm" (h 0~24)
# partition: 0 -> restituisce le ore in intero
# partition: 1 -> restituisce il minuto attuale 0~59
# partition: 2 -> restituisce i secondi 0~59
#
# ? Win.screen_resolution
# restituisce un array di due interi contenenti la risoluzione in lunghezza
# e altezza dello schermo (es. [1024,730]). Ricordati che non restituisce
# la risoluzione completa, ma solo la parte di schermo utilizzabile (cioč
# quella non nascosta dalla barra delle applicazioni)
#
# ? Screen.resize(lunghezza, larghezza)
# ridimensiona la finestra di gioco. Ricordati che questa funzione non
# aumenta la risoluzione del gioco, ma stretcha limmagine.
#
# ? Internet e HTTP
#
# ? HTTP.domain
# restituisce il dominio principale del tuo server (configura in basso).
# usalo nelle locazioni internet in modo da cambiare velocemente dominio
#
# ? HTTP.download(percorsofile[,destinazione[,bassa prioritā]])
# Scarica il file dal percorso. Se il percorso di destinazione č omesso,
# verrā scaricato nella cartella del gioco (cioč "./") Esempio:
# HTTP.download("http://www.miosito.it/immagine.png","./Graphics/Pictures")
# scaricherā immagine.png nella cartella Graphics/Pictures del gioco.
# HTTP.download("http://www.miosito.it/immagine.png")
# scaricherā immagine.png nella cartella del gioco.
# HTTP.download("http://www.miosito.it/immagine.png",Win.homepath+"/Desktop")
# scaricherā immagine.png sul desktop.
# Imposta true in bassa prioritā per velocizzare il gioco durante il download
# (il download sarā pių lento)
#
# ? HTTP.downloaded?(nomefile)
# Restituisce true se il file che si sta scaricando č stato scaricato
# completamente. Restituisce false se non č stato neanche iniziato.
#
# ? HTTP.progress(nomefile)
# Restituisce la percentuale di scaricamento del file in un float compreso
# tra 0.0 e 100.0. Restituisce 0 se il download non č cominciato.
#
# ? HTTP.filesize(nomefile)
# restituisce la grandezza del file in bit: dividi per 8 per ottenere i byte.
#
# ? HTTP.sizeloaded(nomefile)
# restituisce il numero di bit scaricati del file: dividi per 8 per ottenere
# i byte.
#
# ? HTTP.time_passed(nomefile)
# restituisce il tempo in secondi del tempo che ha richiesto il download.
# Restituisce 0 se il download non č completato o non esiste.
#
# ? HTTP.downloads
# restituisce un hash contenente l'elenco dei download
#
# ? HTTP.completed
# restituisce il numero dei download completati
#
# ? HTTP.file_good?(nomefile)
# controlla se il file č stato scaricato correttamente
#
# ? Browser.open(url)
# apre il browser ad un sito scelto. Ricordati che se l'url č troppo grande,
# potrebbe non avviare il sito. In questo caso ti consiglio di usare tinyurl
# o goo.gl per rimpicciolire il link.
#
#==============================================================================
module H87_ModConfig
HTTPDOMAIN = "http://miosito.com/"
end
#==============================================================================
# ** Win
#------------------------------------------------------------------------------
# Questo modulo gestisce le chiamate di sistema e recupera informazioni sul
# computer
#==============================================================================
module Win
#-----------------------------------------------------------------------------
# *Nome Utente Windows
# Restituisce il nome utente di Windows
#-----------------------------------------------------------------------------
def self.username
name = " " * 128
size = "128"
Win32API.new('advapi32','GetUserName',['P','P'],'I').call(name,size)
username = name.unpack("A*")
return username[0]
end
# --------------------------------------------------------------------------
# * Restituisce la cartella utente di Windows
# --------------------------------------------------------------------------
def self.homepath
name = " " * 128
size = "128"
username = "\0" * 256 #userprofile
Win32API.new('kernel32', 'GetEnvironmentVariable', %w(p p l), 'l').call("userprofile", username, 256)
username.delete!("\0")
return username.gsub("\\","/")
end
# --------------------------------------------------------------------------
# * Restituisce la larghezza della cornice della finestra
# --------------------------------------------------------------------------
def self.window_frame_width
return Win32API.new("user32", "GetSystemMetrics", ['I'],'I').call(7)
end
# --------------------------------------------------------------------------
# * Restituisce l'altezza della barra del titolo
# --------------------------------------------------------------------------
def self.window_title_height
return Win32API.new("user32", "GetSystemMetrics", ['I'],'I').call(4)
end
#-----------------------------------------------------------------------------
# * Elimina il file temporaneo per aggiornarlo prima di un download.
# inserire il nome del file.
#-----------------------------------------------------------------------------
def self.temp_flush(nomefile)
if version < 6
path = homepath+"/Impostazioni locali/Temporary Internet Files"
unless File.directory?(path)
path = homepath+"/Local Settings/Temporary Internet Files"
return unless File.directory?(path)
end
fetch_folder_for_delete(path,nomefile)
else
path = homepath+"/AppData/Local/Microsoft/Windows/Temporary Internet Files/Content.IE5"
Dir.foreach(path) {|x| #per ogni file nel percorso
next if x == "." or x == ".." #passa al prossimo se č ind.
if File.directory?(path+"/"+x) #se il file č una cartella
folder = path+"/"+x #entra nella cartella
fetch_folder_for_delete(folder,nomefile)
end
}
end
end
# --------------------------------------------------------------------------
# * Cerca nella cartella il file da cancellare
# path: directory
# nomefile: file da cancellare
# --------------------------------------------------------------------------
def self.fetch_folder_for_delete(path,nomefile)
Dir.foreach(path) {|y| #per ogni file nella cartella
next if File.directory?(path+"/"+y) #passa al prossimo se č una c.
if no_ext(nomefile) == y[0..no_ext(nomefile).size-1]#se l'inizio del nome corrisp.
begin
File.delete(path+"/"+y) #eliminalo
rescue
next
end
end
}
end
# --------------------------------------------------------------------------
# * Restituisce la versione di Windows in uso
# --------------------------------------------------------------------------
def self.version
gvex = Win32API.new( 'kernel32', 'GetVersionEx', ['P'], 'I' )
s = [20+128, 0, 0, 0, 0, '' ].pack('LLLLLa128')
gvex.call( s );
a = s.unpack( 'LLLLLa128' )
indice = a[1].to_f;dec = a[2].to_f/10
return indice + dec
end
#-----------------------------------------------------------------------------
# * Restituisce il nome del file senza estensione.
#-----------------------------------------------------------------------------
def self.no_ext(nomefile)
nome = nomefile.split(".")
return nome[0]
end
#-----------------------------------------------------------------------------
# * Restituisce un array di larghezza e altezza della parte utilizzabile dello
# schermo: non conta lo spazio della barra delle applicazioni.
#-----------------------------------------------------------------------------
def self.screen_resolution
x = Win32API.new("user32", "GetSystemMetrics", ['I'],'I').call(16)
y = Win32API.new("user32", "GetSystemMetrics", ['I'],'I').call(17)
return [x,y]
end
#-----------------------------------------------------------------------------
# * Restituisce la data attuale
#-----------------------------------------------------------------------------
def self.datenow(partition = -1)
date = Time.new
case partition
when -1
return sprintf("%d/%d/%d",date.day,date.month,date.year)
when 0
return date.day
when 1
return date.month
when 2
return date.year
end
end
#-----------------------------------------------------------------------------
# * Restituisce l'ora attuale
#-----------------------------------------------------------------------------
def self.timenow(partition = -1)
date = Time.new
case partition
when -1
return sprintf("%d:%d",date.hour,date.min)
when 0
return date.hour
when 1
return date.min
when 2
return date.sec
end
end
#-----------------------------------------------------------------------------
# * arresta il computer in modalitā diverse.
#-----------------------------------------------------------------------------
def self.shutdown(mode = 0)
string = "system "
case mode
when 0
string += "-s"
when 1
string += "-r"
when 2
string += "-h"
end
system(string)
end
end #win
#==============================================================================
# ** Screen
#------------------------------------------------------------------------------
# Questo modulo gestisce il ridimensionamento della finestra di gioco
#==============================================================================
module Screen
#-----------------------------------------------------------------------------
# * ridimensiona la finestra e la centra
# width = nuova larghezza
# height = nuova altezza
#-----------------------------------------------------------------------------
def self.resize(width ,height)
#API
getSystemMetrics = Win32API.new("user32", "GetSystemMetrics", 'I', 'I')
moveWindow = Win32API.new("user32","MoveWindow",['l','i','i','i','i','l'],'l')
findWindowEx = Win32API.new("user32","FindWindowEx",['l','l','p','p'],'i')
this_window = findWindowEx.call(0,0,"RGSS Player",0)
res_x = Win.screen_resolution[0] #risoluzione x
res_y = Win.screen_resolution[1] #risoluzione y
width += Win.window_frame_width*2
height += Win.window_frame_width*2 + window_title_height
new_x = [(res_x-width)/2, 0].max #ottiene la nuova coordinata, ma non
new_y = [(res_y-height)/2, 0].max#fa passare oltre il bordo
moveWindow.call(this_window, new_x, new_y, width, height, 1)
end
end #screen
#==============================================================================
# ** HTTP
#------------------------------------------------------------------------------
# Questo modulo gestisce i download dei file.
#==============================================================================
module HTTP
SetPrClass = Win32API.new('kernel32','SetPriorityClass','pi','i').call(-1,128)
InternetOpenA = Win32API.new("wininet",'InternetOpenA','plppl','l').call('',0,'','',0)
InternetConnectA = Win32API.new("wininet",'InternetConnectA','lplpplll','l')
InternetOpenUrl = Win32API.new("wininet",'InternetOpenUrl','lppllp','l')
InternetReadFile = Win32API.new("wininet",'InternetReadFile','lpip','l')
InternetCloseHandle = Win32API.new("wininet",'InternetCloseHandle','l','l')
HttpQueryInfo = Win32API.new("wininet",'HttpQueryInfo','llppp','i')
#--------------------------------------------------------------------------
# * Scarica un file da internet in un thread separato
# url = indirizzo completo del nome del file
# folder = cartella dove depositare il file scaricato
#--------------------------------------------------------------------------
def self.download(url, folder = "./", low_priority = false)
#inizializzazione
@downloaded = 0 if @downloaded.nil?
@downloads = {} if @downloads.nil?
@counter = -1 if @counter.nil?
@size = {} if @size.nil?
@received = {} if @received.nil?
@timepassed = {} if @timepassed.nil?
#ottenimento dell'indirizzo
address = url.split('/')
server = address[2]
root = address[3..address.size].join('/')
filename = address[-1]
#crezione del thread
@downloads[filename] = Thread.start(url,folder){|url,folder|
txt = ""
t = Time.now
ErrConHttp if(e=InternetConnectA.call(InternetOpenA,server,80,'','',3,1,0))==0
file = InternetOpenUrl.call(InternetOpenA,url,nil,0,0,0)
HttpQueryInfo.call(file,5,k="\0"*1024,[k.size-1].pack('l'),nil)
@received[filename] = 0
@size[filename] = k.delete!("\0").to_i
loop do
buffer = " "*1024
n = 0
r = InternetReadFile.call(file,buffer,1024,o=[n].pack('i!'))
n = o.unpack('i!')[0]
break if r&&n==0
txt<<buffer[0,n]
@received[filename] = txt.size
sleep(0.001) if low_priority
end
#creazione del file nel percorso
obj = File.open(folder + filename,'wb')<<txt
obj.close #chiusura del file
@downloaded += @received[filename]
InternetCloseHandle.call(file)
sleep(0.01)
@timepassed[filename] = Time.now-t
}
end
#--------------------------------------------------------------------------
# * Restituisce true se il file č scaricato.
# filename: nome del file
#--------------------------------------------------------------------------
def self.downloaded?(filename)
return false if @received[filename].nil?
return true if progress(filename) > 96.0
return false
end
#--------------------------------------------------------------------------
# * Restituisce la grandezza del file da scaricare in byte
# filename: nome del file
#--------------------------------------------------------------------------
def self.filesize(filename)
return 0 if @size[filename].nil?
return @size[filename]
end
#--------------------------------------------------------------------------
# * Restituisce la quantitā di byte scaricati
# filename: nome del file
#--------------------------------------------------------------------------
def self.sizeloaded(filename)
return 0 if @received[filename].nil?
return @received[filename]
end
#--------------------------------------------------------------------------
# * Restituisce la percentuale di progresso del download
# filename: nome del file
#--------------------------------------------------------------------------
def self.progress(filename)
return 0 if @received[filename].nil?
return @received[filename].to_f/@size[filename]*100
end
#--------------------------------------------------------------------------
# * Restituisce l'hash dei download
#--------------------------------------------------------------------------
def downloads
return {} if @downloads.nil?
return @downloads
end
#--------------------------------------------------------------------------
# * Restituisce il numero di secondi che ci sono voluti per scaricare
#--------------------------------------------------------------------------
def self.time_passed(filename)
return 0 if @timepassed[filename] == nil
return @timepassed[filename]
end
#--------------------------------------------------------------------------
# * Restituisce il numero dei download completati
#--------------------------------------------------------------------------
def self.completed
return 0 if @downloaded.nil?
return @downloaded
end
#--------------------------------------------------------------------------
# * Restituisce il dominio principale
#--------------------------------------------------------------------------
def self.domain
H87_ModConfig::HTTPDOMAIN
end
#--------------------------------------------------------------------------
# * Controlla se il file scaricato č buono e restituisce true o false
#--------------------------------------------------------------------------
def self.file_good?(filename)
if File.exist? (filename) #apre il file in sola lett.
File.open(filename,"r") do |f|
f.lineno = 1 # imposta la riga n.1
txt = f.gets
return false if txt == "" or txt.nil?
@controllore = txt[0].chr
return false if @controllore == "" or @controllore == nil
end
else
return false
end
return false if @controllore == "<"
return true
end
end #http
#==============================================================================
# ** Modulo Browser per aprire il browser predefinito del PC
#==============================================================================
module Browser
#--------------------------------------------------------------------------
# * apre il browser
# url: url impostato
#--------------------------------------------------------------------------
def self.open(url)
#controlla che ci siano prefissi
if url[0..6] != "http://" and url[0..7] != "https://"
open_url = "explorer http://"+url
else
open_url = "explorer "+url
end
Thread.new{system(open_url)}
end
end #browser
#==============================================================================
# ** Classe Settings (per le impostazioni comuni ai salvataggi)
#==============================================================================
class H87_Settings
#--------------------------------------------------------------------------
# * restituisce l'elemento corrispondente al parametro
#--------------------------------------------------------------------------
def [](param)
@settings[param]
end
#--------------------------------------------------------------------------
# * inizializzazione
#--------------------------------------------------------------------------
def initialize
@settings = {}
end
#--------------------------------------------------------------------------
# * cambia o aggiunge un elemento dell'hash
#--------------------------------------------------------------------------
def []=(param_name,value)
@settings[param_name] = value
save_data($game_settings,"game_settings.rvdata")
end
end #settings
module DataManager
#--------------------------------------------------------------------------
# * alias
#--------------------------------------------------------------------------
class << self
alias h87set_load_n_db load_normal_database
alias h87set_load_b_db load_battle_test_database
end
# --------------------------------------------------------------------------
# * caricamento nd
# --------------------------------------------------------------------------
def self.load_normal_database
h87set_load_n_db
load_h87settings
end
# --------------------------------------------------------------------------
# * caricamento btd
# --------------------------------------------------------------------------
def self.load_battle_test_database
h87set_load_b_db
load_h87settings
end
#--------------------------------------------------------------------------
# * carica le impostazioni universali
#--------------------------------------------------------------------------
def self.load_h87settings
if File.exist?("game_settings.rvdata")
$game_settings = load_data("game_settings.rvdata")
else
$game_settings = H87_Settings.new
save_data($game_settings,"game_settings.rvdata")
end
end
end #datamanager