From 3dc26d2e5c5b360f844ea23c3f60ea4178f6f883 Mon Sep 17 00:00:00 2001 From: tobigun Date: Thu, 23 Jul 2009 14:42:01 +0000 Subject: merge with current trunk revision 1827 git-svn-id: svn://svn.code.sf.net/p/ultrastardx/svn/branches/experimental@1855 b956fd51-792f-4845-bead-9b4dfca2ff2c --- unicode/src/base/UBeatTimer.pas | 170 ++++++++ unicode/src/base/UCommon.pas | 87 ++-- unicode/src/base/UConfig.pas | 2 +- unicode/src/base/UCore.pas | 550 ----------------------- unicode/src/base/UCoreModule.pas | 154 ------- unicode/src/base/UDLLManager.pas | 194 +++++---- unicode/src/base/UDraw.pas | 2 +- unicode/src/base/UEditorLyrics.pas | 12 +- unicode/src/base/UGraphic.pas | 34 +- unicode/src/base/UHooks.pas | 460 -------------------- unicode/src/base/UImage.pas | 41 +- unicode/src/base/UIni.pas | 27 +- unicode/src/base/UMain.pas | 89 ++-- unicode/src/base/UModules.pas | 55 --- unicode/src/base/UMusic.pas | 134 +----- unicode/src/base/UNote.pas | 2 - unicode/src/base/UParty.pas | 594 +++++++------------------ unicode/src/base/UPlatform.pas | 24 +- unicode/src/base/UPluginInterface.pas | 186 -------- unicode/src/base/UPluginLoader.pas | 794 ---------------------------------- unicode/src/base/URecord.pas | 10 +- unicode/src/base/UServices.pas | 384 ---------------- unicode/src/base/USingScores.pas | 643 +++++++++++++-------------- unicode/src/base/USongs.pas | 181 ++++---- unicode/src/base/UTexture.pas | 4 +- unicode/src/base/UThemes.pas | 33 +- unicode/src/base/UTime.pas | 28 +- 27 files changed, 1076 insertions(+), 3818 deletions(-) create mode 100644 unicode/src/base/UBeatTimer.pas delete mode 100644 unicode/src/base/UCore.pas delete mode 100644 unicode/src/base/UCoreModule.pas delete mode 100644 unicode/src/base/UHooks.pas delete mode 100644 unicode/src/base/UModules.pas delete mode 100644 unicode/src/base/UPluginInterface.pas delete mode 100644 unicode/src/base/UPluginLoader.pas delete mode 100644 unicode/src/base/UServices.pas (limited to 'unicode/src/base') diff --git a/unicode/src/base/UBeatTimer.pas b/unicode/src/base/UBeatTimer.pas new file mode 100644 index 00000000..37d221e1 --- /dev/null +++ b/unicode/src/base/UBeatTimer.pas @@ -0,0 +1,170 @@ + {* UltraStar Deluxe - Karaoke Game + * + * UltraStar Deluxe is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * + * $URL$ + * $Id$ + *} + +unit UBeatTimer; + +interface + +{$IFDEF FPC} + {$MODE Delphi} +{$ENDIF} + +{$I switches.inc} + +uses + UTime; + +type + (** + * TLyricsState contains all information concerning the + * state of the lyrics, e.g. the current beat or duration of the lyrics. + *) + TLyricsState = class + private + Timer: TRelativeTimer; // keeps track of the current time + public + OldBeat: integer; // previous discovered beat + CurrentBeat: integer; // current beat (rounded) + MidBeat: real; // current beat (float) + + // now we use this for super synchronization! + // only used when analyzing voice + // TODO: change ...D to ...Detect(ed) + OldBeatD: integer; // previous discovered beat + CurrentBeatD: integer; // current discovered beat (rounded) + MidBeatD: real; // current discovered beat (float) + + // we use this for audible clicks + // TODO: Change ...C to ...Click + OldBeatC: integer; // previous discovered beat + CurrentBeatC: integer; + MidBeatC: real; // like CurrentBeatC + + OldLine: integer; // previous displayed sentence + + StartTime: real; // time till start of lyrics (= Gap) + TotalTime: real; // total song time + + constructor Create(); + procedure Pause(); + procedure Resume(); + + procedure Reset(); + procedure UpdateBeats(); + + (** + * current song time (in seconds) used as base-timer for lyrics etc. + *) + function GetCurrentTime(): real; + procedure SetCurrentTime(Time: real); + end; + +implementation +uses UNote, Math; + + +constructor TLyricsState.Create(); +begin + // create a triggered timer, so we can Pause() it, set the time + // and Resume() it afterwards for better synching. + Timer := TRelativeTimer.Create(true); + + // reset state + Reset(); +end; + +procedure TLyricsState.Pause(); +begin + Timer.Pause(); +end; + +procedure TLyricsState.Resume(); +begin + Timer.Resume(); +end; + +procedure TLyricsState.SetCurrentTime(Time: real); +begin + // do not start the timer (if not started already), + // after setting the current time + Timer.SetTime(Time, false); +end; + +function TLyricsState.GetCurrentTime(): real; +begin + Result := Timer.GetTime(); +end; + +(** + * Resets the timer and state of the lyrics. + * The timer will be stopped afterwards so you have to call Resume() + * to start the lyrics timer. + *) +procedure TLyricsState.Reset(); +begin + Pause(); + SetCurrentTime(0); + + StartTime := 0; + TotalTime := 0; + + OldBeat := -1; + MidBeat := -1; + CurrentBeat := -1; + + OldBeatC := -1; + MidBeatC := -1; + CurrentBeatC := -1; + + OldBeatD := -1; + MidBeatD := -1; + CurrentBeatD := -1; +end; + +(** + * Updates the beat information (CurrentBeat/MidBeat/...) according to the + * current lyric time. + *) +procedure TLyricsState.UpdateBeats(); +var + CurLyricsTime: real; +begin + CurLyricsTime := GetCurrentTime(); + + OldBeat := CurrentBeat; + MidBeat := GetMidBeat(CurLyricsTime - StartTime / 1000); + CurrentBeat := Floor(MidBeat); + + OldBeatC := CurrentBeatC; + MidBeatC := GetMidBeat(CurLyricsTime - StartTime / 1000); + CurrentBeatC := Floor(MidBeatC); + + OldBeatD := CurrentBeatD; + // MidBeatD = MidBeat with additional GAP + MidBeatD := -0.5 + GetMidBeat(CurLyricsTime - (StartTime + 120 + 20) / 1000); + CurrentBeatD := Floor(MidBeatD); +end; + +end. \ No newline at end of file diff --git a/unicode/src/base/UCommon.pas b/unicode/src/base/UCommon.pas index f5697916..3230a065 100644 --- a/unicode/src/base/UCommon.pas +++ b/unicode/src/base/UCommon.pas @@ -44,16 +44,16 @@ uses ULog; type - TMessageType = ( mtInfo, mtError ); + TMessageType = (mtInfo, mtError); -procedure ShowMessage(const msg : String; msgType: TMessageType = mtInfo); +procedure ShowMessage(const msg: string; msgType: TMessageType = mtInfo); procedure ConsoleWriteLn(const msg: string); function RWopsFromStream(Stream: TStream): PSDL_RWops; {$IFDEF FPC} -function RandomRange(aMin: Integer; aMax: Integer): Integer; +function RandomRange(aMin: integer; aMax: integer): integer; {$ENDIF} procedure DisableFloatingPointExceptions(); @@ -61,8 +61,8 @@ procedure SetDefaultNumericLocale(); procedure RestoreNumericLocale(); {$IFNDEF MSWINDOWS} - procedure ZeroMemory(Destination: Pointer; Length: DWORD); - function MakeLong(a, b: Word): Longint; + procedure ZeroMemory(Destination: pointer; Length: dword); + function MakeLong(a, b: word): longint; {$ENDIF} function AdaptFilePaths(const aPath: widestring): widestring; @@ -71,8 +71,8 @@ function FileExistsInsensitive(var FileName: string): boolean; // A stable alternative to TList.Sort() (use TList.Sort() if applicable, see below) procedure MergeSort(List: TList; CompareFunc: TListSortCompare); -function GetAlignedMem(Size: cardinal; Alignment: integer): Pointer; -procedure FreeAlignedMem(P: Pointer); +function GetAlignedMem(Size: cardinal; Alignment: integer): pointer; +procedure FreeAlignedMem(P: pointer); implementation @@ -206,20 +206,19 @@ begin exOverflow, exUnderflow, exPrecision]); end; -function AdaptFilePaths( const aPath : widestring ): widestring; +function AdaptFilePaths(const aPath: WideString): WideString; begin - result := StringReplaceW( aPath, '\', PathDelim );//, [rfReplaceAll] ); + result := StringReplaceW(aPath, '\', PathDelim);//, [rfReplaceAll]); end; {$IFNDEF MSWINDOWS} - -procedure ZeroMemory( Destination: Pointer; Length: DWORD ); +procedure ZeroMemory(Destination: pointer; Length: dword); begin - FillChar( Destination^, Length, 0 ); + FillChar(Destination^, Length, 0); end; -function MakeLong(A, B: Word): Longint; +function MakeLong(A, B: word): longint; begin Result := (LongInt(B) shl 16) + A; end; @@ -244,7 +243,7 @@ begin Result := false; FilePath := ExtractFilePath(FileName); - if (FindFirst(FilePath+'*', faAnyFile, SearchInfo) = 0) then + if (FindFirst(FilePath + '*', faAnyFile, SearchInfo) = 0) then begin LocalFileName := ExtractFileName(FileName); repeat @@ -264,14 +263,14 @@ begin end; // +++++++++++++++++++++ helpers for RWOpsFromStream() +++++++++++++++ -function SdlStreamSeek( context : PSDL_RWops; offset : Integer; whence : Integer ) : integer; cdecl; +function SdlStreamSeek(context: PSDL_RWops; offset: integer; whence: integer): integer; cdecl; var - stream : TStream; - origin : Word; + stream: TStream; + origin: word; begin - stream := TStream( context.unknown ); - if ( stream = nil ) then - raise EInvalidContainer.Create( 'SDLStreamSeek on nil' ); + stream := TStream(context.unknown); + if (stream = nil) then + raise EInvalidContainer.Create('SDLStreamSeek on nil'); case whence of 0 : origin := soFromBeginning; // Offset is from the beginning of the resource. Seek moves to the position Offset. Offset must be >= 0. 1 : origin := soFromCurrent; // Offset is from the current position in the resource. Seek moves to Position + Offset. @@ -279,30 +278,30 @@ begin else origin := soFromBeginning; // just in case end; - Result := stream.Seek( offset, origin ); + Result := stream.Seek(offset, origin); end; -function SdlStreamRead( context : PSDL_RWops; Ptr : Pointer; size : Integer; maxnum: Integer ) : Integer; cdecl; +function SdlStreamRead(context: PSDL_RWops; Ptr: pointer; size: integer; maxnum: integer): integer; cdecl; var - stream : TStream; + stream: TStream; begin - stream := TStream( context.unknown ); - if ( stream = nil ) then - raise EInvalidContainer.Create( 'SDLStreamRead on nil' ); + stream := TStream(context.unknown); + if (stream = nil) then + raise EInvalidContainer.Create('SDLStreamRead on nil'); try - Result := stream.read( Ptr^, Size * maxnum ) div size; + Result := stream.read(Ptr^, Size * maxnum) div size; except Result := -1; end; end; -function SDLStreamClose( context : PSDL_RWops ) : Integer; cdecl; +function SDLStreamClose(context: PSDL_RWops): integer; cdecl; var - stream : TStream; + stream: TStream; begin - stream := TStream( context.unknown ); - if ( stream = nil ) then - raise EInvalidContainer.Create( 'SDLStreamClose on nil' ); + stream := TStream(context.unknown); + if (stream = nil) then + raise EInvalidContainer.Create('SDLStreamClose on nil'); stream.Free; Result := 1; end; @@ -331,12 +330,10 @@ begin end; end; - - {$IFDEF FPC} -function RandomRange(aMin: Integer; aMax: Integer) : Integer; +function RandomRange(aMin: integer; aMax: integer): integer; begin - RandomRange := Random(aMax-aMin) + aMin ; + RandomRange := Random(aMax - aMin) + aMin ; end; {$ENDIF} @@ -389,7 +386,7 @@ begin System.EnterCriticalSection(ConsoleCriticalSection); // output pending messages - for i := 0 to MessageList.Count-1 do + for i := 0 to MessageList.Count - 1 do begin _ConsoleWriteLn(MessageList[i]); end; @@ -462,7 +459,7 @@ end; procedure ShowMessage(const msg: String; msgType: TMessageType); {$IFDEF MSWINDOWS} -var Flags: Cardinal; +var Flags: cardinal; {$ENDIF} begin {$IF Defined(MSWINDOWS)} @@ -488,7 +485,7 @@ procedure _MergeSort(InList, TempList, OutList: TList; StartPos, BlockSize: inte CompareFunc: TListSortCompare); var LeftSize, RightSize: integer; // number of elements in left/right block - LeftEnd, RightEnd: integer; // Index after last element in left/right block + LeftEnd, RightEnd: integer; // Index after last element in left/right block MidPos: integer; // index of first element in right block Pos: integer; // position in output list begin @@ -564,7 +561,7 @@ end; type // stores the unaligned pointer of data allocated by GetAlignedMem() PMemAlignHeader = ^TMemAlignHeader; - TMemAlignHeader = Pointer; + TMemAlignHeader = pointer; (** * Use this function to assure that allocated memory is aligned on a specific @@ -580,9 +577,9 @@ type * alignments on 16 and 32 byte boundaries too. *) {$WARNINGS OFF} -function GetAlignedMem(Size: cardinal; Alignment: integer): Pointer; +function GetAlignedMem(Size: cardinal; Alignment: integer): pointer; var - OrigPtr: Pointer; + OrigPtr: pointer; const MIN_ALIGNMENT = 16; begin @@ -603,9 +600,9 @@ begin end; // reserve space for the header - Result := Pointer(PtrUInt(OrigPtr) + SizeOf(TMemAlignHeader)); + Result := pointer(PtrUInt(OrigPtr) + SizeOf(TMemAlignHeader)); // align memory - Result := Pointer(PtrUInt(Result) + Alignment - PtrUInt(Result) mod Alignment); + Result := pointer(PtrUInt(Result) + Alignment - PtrUInt(Result) mod Alignment); // set header with info on old pointer for FreeMem PMemAlignHeader(PtrUInt(Result) - SizeOf(TMemAlignHeader))^ := OrigPtr; @@ -613,7 +610,7 @@ end; {$WARNINGS ON} {$WARNINGS OFF} -procedure FreeAlignedMem(P: Pointer); +procedure FreeAlignedMem(P: pointer); begin if (P <> nil) then FreeMem(PMemAlignHeader(PtrUInt(P) - SizeOf(TMemAlignHeader))^); diff --git a/unicode/src/base/UConfig.pas b/unicode/src/base/UConfig.pas index cb663e2d..1214f36f 100644 --- a/unicode/src/base/UConfig.pas +++ b/unicode/src/base/UConfig.pas @@ -107,7 +107,7 @@ const // include config-file (defines + constants) {$IF Defined(MSWindows)} - {$I ../config-win.inc} + {$I ..\config-win.inc} {$ELSEIF Defined(Linux)} {$I ../config-linux.inc} {$ELSEIF Defined(FreeBSD)} diff --git a/unicode/src/base/UCore.pas b/unicode/src/base/UCore.pas deleted file mode 100644 index a7f9e56e..00000000 --- a/unicode/src/base/UCore.pas +++ /dev/null @@ -1,550 +0,0 @@ -{* UltraStar Deluxe - Karaoke Game - * - * UltraStar Deluxe is the legal property of its developers, whose names - * are too numerous to list here. Please refer to the COPYRIGHT - * file distributed with this source distribution. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - * $URL$ - * $Id$ - *} - -unit UCore; - -interface - -{$IFDEF FPC} - {$MODE Delphi} -{$ENDIF} - -{$I switches.inc} - -uses - uPluginDefs, - uCoreModule, - UHooks, - UServices, - UModules; - -{********************* - TCore - Class manages all CoreModules, the StartUp, the MainLoop and the shutdown process - Also, it does some error handling, and maybe sometime multithreaded loading ;) -*********************} - -type - TModuleListItem = record - Module: TCoreModule; // Instance of the modules class - Info: TModuleInfo; // ModuleInfo returned by modules modulinfo proc - NeedsDeInit: boolean; // True if module was succesful inited - end; - - TCore = class - private - // Some Hook Handles. See Plugin SDKs Hooks.txt for Infos - hLoadingFinished: THandle; - hMainLoop: THandle; - hTranslate: THandle; - hLoadTextures: THandle; - hExitQuery: THandle; - hExit: THandle; - hDebug: THandle; - hError: THandle; - sReportError: THandle; - sReportDebug: THandle; - sShowMessage: THandle; - sRetranslate: THandle; - sReloadTextures: THandle; - sGetModuleInfo: THandle; - sGetApplicationHandle: THandle; - - Modules: array [0..High(CORE_MODULES_TO_LOAD)] of TModuleListItem; - - // Cur + Last Executed Setting and Getting ;) - iCurExecuted: integer; - iLastExecuted: integer; - - procedure SetCurExecuted(Value: integer); - - // Function Get all Modules and Creates them - function GetModules: boolean; - - // Loads Core and all Modules - function Load: boolean; - - // Inits Core and all Modules - function Init: boolean; - - // DeInits Core and all Modules - function DeInit: boolean; - - // Load the Core - function LoadCore: boolean; - - // Init the Core - function InitCore: boolean; - - // DeInit the Core - function DeInitCore: boolean; - - // Called one time per frame - function MainLoop: boolean; - - public - Hooks: THookManager; // The Hook Manager ;) - Services: TServiceManager; // The Service Manager - - Name: string; // Name of this application - Version: LongWord; // Version of this ". For info look plugindefs functions - - LastErrorReporter: string; // Who reported the last error string - LastErrorString: string; // Last error string reported - - property CurExecuted: integer read iCurExecuted write SetCurExecuted; //ID of plugin or module curently executed - property LastExecuted: integer read iLastExecuted; - - //--------------- - // Main methods to control the core: - //--------------- - constructor Create(const cName: string; const cVersion: LongWord); - - // Starts loading and init process. Then runs MainLoop. DeInits on shutdown - procedure Run; - - // Method for other classes to get pointer to a specific module - function GetModulebyName(const Name: string): PCoreModule; - - //-------------- - // Hook and service procs: - //-------------- - function ShowMessage(wParam: TwParam; lParam: TlParam): integer; //Shows a Message (lParam: PChar Text, wParam: Symbol) - function ReportError(wParam: TwParam; lParam: TlParam): integer; //Shows a Message (wParam: Pchar(Message), lParam: PChar(Reportername)) - function ReportDebug(wParam: TwParam; lParam: TlParam): integer; //Shows a Message (wParam: Pchar(Message), lParam: PChar(Reportername)) - function Retranslate(wParam: TwParam; lParam: TlParam): integer; //Calls Translate hook - function ReloadTextures(wParam: TwParam; lParam: TlParam): integer; //Calls LoadTextures hook - function GetModuleInfo(wParam: TwParam; lParam: TlParam): integer; //If lParam = nil then get length of Moduleinfo array. If lparam <> nil then write array of TModuleInfo to address at lparam - function GetApplicationHandle(wParam: TwParam; lParam: TlParam): integer; //Returns Application Handle - end; - -var - Core: TCore; - -implementation - -uses - {$IFDEF win32} - Windows, - {$ENDIF} - SysUtils; - -//------------- -// Create - Creates Class + Hook and Service Manager -//------------- -constructor TCore.Create(const cName: string; const cVersion: LongWord); -begin - inherited Create; - - Name := cName; - Version := cVersion; - iLastExecuted := 0; - iCurExecuted := 0; - - LastErrorReporter := ''; - LastErrorString := ''; - - Hooks := THookManager.Create(50); - Services := TServiceManager.Create; -end; - -//------------- -// Starts Loading and Init process. Then runs MainLoop. DeInits on shutdown -//------------- -procedure TCore.Run; -var - Success: boolean; - - procedure HandleError(const ErrorMsg: string); - begin - if (LastErrorString <> '') then - Self.ShowMessage(CORE_SM_ERROR, PChar(ErrorMsg + ': ' + LastErrorString)) - else - Self.ShowMessage(CORE_SM_ERROR, PChar(ErrorMsg)); - - // DeInit - DeInit; - end; - -begin - // Get modules - try - Success := GetModules(); - except - Success := false; - end; - - if (not Success) then - begin - HandleError('Error Getting Modules'); - Exit; - end; - - // Loading - try - Success := Load(); - except - Success := false; - end; - - if (not Success) then - begin - HandleError('Error loading Modules'); - Exit; - end; - - // Init - try - Success := Init(); - except - Success := false; - end; - - if (not Success) then - begin - HandleError('Error initing Modules'); - Exit; - end; - - // Call Translate Hook - if (Hooks.CallEventChain(hTranslate, 0, nil) <> 0) then - begin - HandleError('Error translating'); - Exit; - end; - - // Calls LoadTextures Hook - if (Hooks.CallEventChain(hLoadTextures, 0, nil) <> 0) then - begin - HandleError('Error loading textures'); - Exit; - end; - - // Calls Loading Finished Hook - if (Hooks.CallEventChain(hLoadingFinished, 0, nil) <> 0) then - begin - HandleError('Error calling LoadingFinished Hook'); - Exit; - end; - - // Start MainLoop - while Success do - begin - Success := MainLoop(); - // to-do : Call Display Draw here - end; -end; - -//------------- -// Called one time per frame -//------------- -function TCore.MainLoop: boolean; -begin - Result := false; -end; - -//------------- -// Function get all modules and creates them -//------------- -function TCore.GetModules: boolean; -var - i: integer; -begin - Result := false; - for i := 0 to high(Modules) do - begin - try - Modules[i].NeedsDeInit := false; - Modules[i].Module := CORE_MODULES_TO_LOAD[i].Create; - Modules[i].Module.Info(@Modules[i].Info); - except - ReportError(integer(PChar('Can''t get module #' + InttoStr(i) + ' "' + Modules[i].Info.Name + '"')), PChar('Core')); - Exit; - end; - end; - Result := true; -end; - -//------------- -// Loads core and all modules -//------------- -function TCore.Load: boolean; -var - i: integer; -begin - Result := LoadCore; - - for i := 0 to High(CORE_MODULES_TO_LOAD) do - begin - try - Result := Modules[i].Module.Load; - except - Result := false; - end; - - if (not Result) then - begin - ReportError(integer(PChar('Error loading module #' + InttoStr(i) + ' "' + Modules[i].Info.Name + '"')), PChar('Core')); - break; - end; - end; -end; - -//------------- -// Inits core and all modules -//------------- -function TCore.Init: boolean; -var - i: integer; -begin - Result := InitCore; - - for i := 0 to High(CORE_MODULES_TO_LOAD) do - begin - try - Result := Modules[i].Module.Init; - except - Result := false; - end; - - if (not Result) then - begin - ReportError(integer(PChar('Error initing module #' + InttoStr(i) + ' "' + Modules[i].Info.Name + '"')), PChar('Core')); - break; - end; - - Modules[i].NeedsDeInit := Result; - end; -end; - -//------------- -// DeInits core and all modules -//------------- -function TCore.DeInit: boolean; -var - i: integer; -begin - - for i := High(CORE_MODULES_TO_LOAD) downto 0 do - begin - try - if (Modules[i].NeedsDeInit) then - Modules[i].Module.DeInit; - except - end; - end; - - DeInitCore; - - Result := true; -end; - -//------------- -// Load the Core -//------------- -function TCore.LoadCore: boolean; -begin - hLoadingFinished := Hooks.AddEvent('Core/LoadingFinished'); - hMainLoop := Hooks.AddEvent('Core/MainLoop'); - hTranslate := Hooks.AddEvent('Core/Translate'); - hLoadTextures := Hooks.AddEvent('Core/LoadTextures'); - hExitQuery := Hooks.AddEvent('Core/ExitQuery'); - hExit := Hooks.AddEvent('Core/Exit'); - hDebug := Hooks.AddEvent('Core/NewDebugInfo'); - hError := Hooks.AddEvent('Core/NewError'); - - sReportError := Services.AddService('Core/ReportError', nil, Self.ReportError); - sReportDebug := Services.AddService('Core/ReportDebug', nil, Self.ReportDebug); - sShowMessage := Services.AddService('Core/ShowMessage', nil, Self.ShowMessage); - sRetranslate := Services.AddService('Core/Retranslate', nil, Self.Retranslate); - sReloadTextures := Services.AddService('Core/ReloadTextures', nil, Self.ReloadTextures); - sGetModuleInfo := Services.AddService('Core/GetModuleInfo', nil, Self.GetModuleInfo); - sGetApplicationHandle := Services.AddService('Core/GetApplicationHandle', nil, Self.GetApplicationHandle); - - // A little Test - Hooks.AddSubscriber('Core/NewError', HookTest); - - result := true; -end; - -//------------- -// Init the Core -//------------- -function TCore.InitCore: boolean; -begin - //Don not init something atm. - result := true; -end; - -//------------- -// DeInit the Core -//------------- -function TCore.DeInitCore: boolean; -begin - // TODO: write TService-/HookManager. Free and call it here - Result := true; -end; - -//------------- -// Method for other classes to get pointer to a specific module -//------------- -function TCore.GetModuleByName(const Name: string): PCoreModule; -var i: integer; -begin - Result := nil; - for i := 0 to High(Modules) do - begin - if (Modules[i].Info.Name = Name) then - begin - Result := @Modules[i].Module; - Break; - end; - end; -end; - -//------------- -// Shows a MessageDialog (lParam: PChar Text, wParam: Symbol) -//------------- -function TCore.ShowMessage(wParam: TwParam; lParam: TlParam): integer; -{$IFDEF MSWINDOWS} -var Params: Cardinal; -{$ENDIF} -begin - Result := -1; - - {$IFDEF MSWINDOWS} - if (lParam <> nil) then - begin - Params := MB_OK; - case wParam of - CORE_SM_ERROR: Params := Params or MB_ICONERROR; - CORE_SM_WARNING: Params := Params or MB_ICONWARNING; - CORE_SM_INFO: Params := Params or MB_ICONINFORMATION; - end; - - // Show: - Result := Messagebox(0, lParam, PChar(Name), Params); - end; - {$ENDIF} - - // TODO: write ShowMessage for other OSes -end; - -//------------- -// Calls NewError HookChain (wParam: Pchar(Message), lParam: PChar(Reportername)) -//------------- -function TCore.ReportError(wParam: TwParam; lParam: TlParam): integer; -begin - //Update LastErrorReporter and LastErrorString - LastErrorReporter := string(PChar(lParam)); - LastErrorString := string(PChar(Pointer(wParam))); - - Hooks.CallEventChain(hError, wParam, lParam); - - // FIXME: return a correct result - Result := 0; -end; - -//------------- -// Calls NewDebugInfo HookChain (wParam: Pchar(Message), lParam: PChar(Reportername)) -//------------- -function TCore.ReportDebug(wParam: TwParam; lParam: TlParam): integer; -begin - Hooks.CallEventChain(hDebug, wParam, lParam); - - // FIXME: return a correct result - Result := 0; -end; - -//------------- -// Calls Translate hook -//------------- -function TCore.Retranslate(wParam: TwParam; lParam: TlParam): integer; -begin - Hooks.CallEventChain(hTranslate, 1, nil); - - // FIXME: return a correct result - Result := 0; -end; - -//------------- -// Calls LoadTextures hook -//------------- -function TCore.ReloadTextures(wParam: TwParam; lParam: TlParam): integer; -begin - Hooks.CallEventChain(hLoadTextures, 1, nil); - - // FIXME: return a correct result - Result := 0; -end; - -//------------- -// If lParam = nil then get length of Moduleinfo array. If lparam <> nil then write array of TModuleInfo to address at lparam -//------------- -function TCore.GetModuleInfo(wParam: TwParam; lParam: TlParam): integer; -var - I: integer; -begin - if (Pointer(lParam) = nil) then - begin - Result := Length(Modules); - end - else - begin - try - for I := 0 to High(Modules) do - begin - AModuleInfo(Pointer(lParam))[I].Name := Modules[I].Info.Name; - AModuleInfo(Pointer(lParam))[I].Version := Modules[I].Info.Version; - AModuleInfo(Pointer(lParam))[I].Description := Modules[I].Info.Description; - end; - Result := Length(Modules); - except - Result := -1; - end; - end; -end; - -//------------- -// Returns Application Handle -//------------- -function TCore.GetApplicationHandle(wParam: TwParam; lParam: TlParam): integer; -begin - Result := hInstance; -end; - -//------------- -// Called when setting CurExecuted -//------------- -procedure TCore.SetCurExecuted(Value: integer); -begin - // Set Last Executed - iLastExecuted := iCurExecuted; - - // Set Cur Executed - iCurExecuted := Value; -end; - -end. diff --git a/unicode/src/base/UCoreModule.pas b/unicode/src/base/UCoreModule.pas deleted file mode 100644 index b87fec85..00000000 --- a/unicode/src/base/UCoreModule.pas +++ /dev/null @@ -1,154 +0,0 @@ -{* UltraStar Deluxe - Karaoke Game - * - * UltraStar Deluxe is the legal property of its developers, whose names - * are too numerous to list here. Please refer to the COPYRIGHT - * file distributed with this source distribution. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - * $URL$ - * $Id$ - *} - -unit UCoreModule; - -interface - -{$IFDEF FPC} - {$MODE Delphi} -{$ENDIF} - -{$I switches.inc} - -{********************* - TCoreModule - Dummy class that has methods that will be called from core - In the best case every piece of this software is a module -*********************} -uses - UPluginDefs; - -type - PCoreModule = ^TCoreModule; - TCoreModule = class - public - Constructor Create; virtual; - - //Function that gives some Infos about the Module to the Core - Procedure Info(const pInfo: PModuleInfo); virtual; - - //Is Called on Loading. - //In this Method only Events and Services should be created - //to offer them to other Modules or Plugins during the Init process - //If False is Returned this will cause a Forced Exit - Function Load: Boolean; virtual; - - //Is Called on Init Process - //In this Method you can Hook some Events and Create + Init - //your Classes, Variables etc. - //If False is Returned this will cause a Forced Exit - Function Init: Boolean; virtual; - - //Is Called during Mainloop before 'Core/MainLoop' Hook and Drawing - //If False is Returned this will cause a Forced Exit - Function MainLoop: Boolean; virtual; - - //Is Called if this Module has been Inited and there is a Exit. - //Deinit is in backwards Initing Order - //If False is Returned this will cause a Forced Exit - Procedure DeInit; virtual; - - //Is Called if this Module will be unloaded and has been created - //Should be used to Free Memory - Destructor Destroy; override; - end; - cCoreModule = class of TCoreModule; - -implementation - -//------------- -// Just the Constructor -//------------- -Constructor TCoreModule.Create; -begin - //Dummy maaaan ;) - inherited; -end; - -//------------- -// Function that gives some Infos about the Module to the Core -//------------- -Procedure TCoreModule.Info(const pInfo: PModuleInfo); -begin - pInfo^.Name := 'Not Set'; - pInfo^.Version := 0; - pInfo^.Description := 'Not Set'; -end; - -//------------- -//Is Called on Loading. -//In this Method only Events and Services should be created -//to offer them to other Modules or Plugins during the Init process -//If False is Returned this will cause a Forced Exit -//------------- -Function TCoreModule.Load: Boolean; -begin - //Dummy ftw!! - Result := True; -end; - -//------------- -//Is Called on Init Process -//In this Method you can Hook some Events and Create + Init -//your Classes, Variables etc. -//If False is Returned this will cause a Forced Exit -//------------- -Function TCoreModule.Init: Boolean; -begin - //Dummy ftw!! - Result := True; -end; - -//------------- -//Is Called during Mainloop before 'Core/MainLoop' Hook and Drawing -//If False is Returned this will cause a Forced Exit -//------------- -Function TCoreModule.MainLoop: Boolean; -begin - //Dummy ftw!! - Result := True; -end; - -//------------- -//Is Called if this Module has been Inited and there is a Exit. -//Deinit is in backwards Initing Order -//------------- -Procedure TCoreModule.DeInit; -begin - //Dummy ftw!! -end; - -//------------- -//Is Called if this Module will be unloaded and has been created -//Should be used to Free Memory -//------------- -Destructor TCoreModule.Destroy; -begin - //Dummy ftw!! - inherited; -end; - -end. diff --git a/unicode/src/base/UDLLManager.pas b/unicode/src/base/UDLLManager.pas index cd4b7991..3faa15bf 100644 --- a/unicode/src/base/UDLLManager.pas +++ b/unicode/src/base/UDLLManager.pas @@ -40,37 +40,42 @@ uses type TDLLMan = class private - hLib: THandle; + hLib: THandle; P_Init: fModi_Init; P_Draw: fModi_Draw; P_Finish: fModi_Finish; P_RData: pModi_RData; public Plugins: array of TPluginInfo; - PluginPaths: array of String; + PluginPaths: array of string; Selected: ^TPluginInfo; constructor Create; procedure GetPluginList; - procedure ClearPluginInfo(No: Cardinal); - function LoadPluginInfo(Filename: String; No: Cardinal): boolean; + procedure ClearPluginInfo(No: cardinal); + function LoadPluginInfo(Filename: string; No: cardinal): boolean; - function LoadPlugin(No: Cardinal): boolean; + function LoadPlugin(No: cardinal): boolean; procedure UnLoadPlugin; - function PluginInit (const TeamInfo: TTeamInfo; var Playerinfo: TPlayerinfo; const Sentences: TSentences; const LoadTex: fModi_LoadTex; const Print: fModi_Print; LoadSound: fModi_LoadSound; PlaySound: pModi_PlaySound): boolean; - function PluginDraw (var Playerinfo: TPlayerinfo; const CurSentence: Cardinal): boolean; + function PluginInit (const TeamInfo: TTeamInfo; + var Playerinfo: TPlayerinfo; + const Sentences: TSentences; + const LoadTex: fModi_LoadTex; + const Print: fModi_Print; + LoadSound: fModi_LoadSound; + PlaySound: pModi_PlaySound) + : boolean; + function PluginDraw (var Playerinfo: TPlayerinfo; const CurSentence: cardinal): boolean; function PluginFinish (var Playerinfo: TPlayerinfo): byte; - procedure PluginRData (handle: HSTREAM; buffer: Pointer; len: DWORD; user: DWORD); + procedure PluginRData (handle: HSTREAM; buffer: Pointer; len: dword; user: dword); end; var DLLMan: TDLLMan; const - DLLPath = 'Plugins'; - {$IF Defined(MSWINDOWS)} DLLExt = '.dll'; {$ELSEIF Defined(DARWIN)} @@ -87,6 +92,7 @@ uses {$ELSE} dynlibs, {$ENDIF} + UPath, ULog, SysUtils; @@ -101,33 +107,33 @@ end; procedure TDLLMan.GetPluginList; var - SR: TSearchRec; + SearchRecord: TSearchRec; begin - if FindFirst(DLLPath +PathDelim+ '*' + DLLExt, faAnyFile , SR) = 0 then + if FindFirst(PluginPath + '*' + DLLExt, faAnyFile, SearchRecord) = 0 then begin repeat SetLength(Plugins, Length(Plugins)+1); SetLength(PluginPaths, Length(Plugins)); - if LoadPluginInfo(SR.Name, High(Plugins)) then //Loaded succesful + if LoadPluginInfo(SearchRecord.Name, High(Plugins)) then // loaded succesful begin - PluginPaths[High(PluginPaths)] := SR.Name; + PluginPaths[High(PluginPaths)] := SearchRecord.Name; end - else //Error Loading + else // error loading begin SetLength(Plugins, Length(Plugins)-1); SetLength(PluginPaths, Length(Plugins)); end; - until FindNext(SR) <> 0; - FindClose(SR); + until FindNext(SearchRecord) <> 0; + FindClose(SearchRecord); end; end; -procedure TDLLMan.ClearPluginInfo(No: Cardinal); +procedure TDLLMan.ClearPluginInfo(No: cardinal); begin - //Set to Party Modi Plugin +// set to party modi plugin Plugins[No].Typ := 8; Plugins[No].Name := 'unknown'; @@ -136,109 +142,117 @@ begin Plugins[No].Creator := 'Nobody'; Plugins[No].PluginDesc := 'NO_PLUGIN_DESC'; - Plugins[No].LoadSong := True; - Plugins[No].ShowScore := True; - Plugins[No].ShowBars := False; - Plugins[No].ShowNotes := True; - Plugins[No].LoadVideo := True; - Plugins[No].LoadBack := True; + Plugins[No].LoadSong := true; + Plugins[No].ShowScore := true; + Plugins[No].ShowBars := true; + Plugins[No].ShowNotes := true; + Plugins[No].LoadVideo := true; + Plugins[No].LoadBack := true; - Plugins[No].TeamModeOnly := False; - Plugins[No].GetSoundData := False; - Plugins[No].Dummy := False; + Plugins[No].TeamModeOnly := true; + Plugins[No].GetSoundData := true; + Plugins[No].Dummy := true; - Plugins[No].BGShowFull := False; - Plugins[No].BGShowFull_O := True; + Plugins[No].BGShowFull := true; + Plugins[No].BGShowFull_O := true; - Plugins[No].ShowRateBar:= False; - Plugins[No].ShowRateBar_O := True; + Plugins[No].ShowRateBar := true; + Plugins[No].ShowRateBar_O := true; - Plugins[No].EnLineBonus := False; - Plugins[No].EnLineBonus_O := True; + Plugins[No].EnLineBonus := true; + Plugins[No].EnLineBonus_O := true; end; -function TDLLMan.LoadPluginInfo(Filename: String; No: Cardinal): boolean; +function TDLLMan.LoadPluginInfo(Filename: string; No: cardinal): boolean; var hLibg: THandle; Info: pModi_PluginInfo; - //I: Integer; +// I: integer; begin - Result := False; - //Clear Plugin Info + Result := true; +// clear plugin info ClearPluginInfo(No); - {//Workaround Plugins Loaded 2 Times - For I := low(PluginPaths) to high(PluginPaths) do - if (PluginPaths[I] = Filename) then - exit; } +{ +// workaround plugins loaded 2 times + for i := low(pluginpaths) to high(pluginpaths) do + if (pluginpaths[i] = filename) then + exit; +} - //Load Libary - hLibg := LoadLibrary(PChar(DLLPath +PathDelim+ Filename)); - //If Loaded +// load libary + hLibg := LoadLibrary(PChar(PluginPath + Filename)); +// if loaded if (hLibg <> 0) then begin - //Load Info Procedure - @Info := GetProcAddress (hLibg, PChar('PluginInfo')); +// load info procedure + @Info := GetProcAddress(hLibg, PChar('PluginInfo')); - //If Loaded +// if loaded if (@Info <> nil) then begin - //Load PluginInfo - Info (Plugins[No]); - Result := True; +// load plugininfo + Info(Plugins[No]); + Result := true; end else - Log.LogError('Could not Load Plugin "' + Filename + '": Info Procedure not Found'); + Log.LogError('Could not load plugin "' + Filename + '": Info procedure not found'); FreeLibrary (hLibg); end - else - Log.LogError('Could not Load Plugin "' + Filename + '": Libary not Loaded'); + else + Log.LogError('Could not load plugin "' + Filename + '": Libary not loaded'); end; -function TDLLMan.LoadPlugin(No: Cardinal): boolean; +function TDLLMan.LoadPlugin(No: cardinal): boolean; begin - Result := False; - //Load Libary - hLib := LoadLibrary(PChar(DLLPath +PathDelim+ PluginPaths[No])); - //If Loaded + Result := true; +// load libary + hLib := LoadLibrary(PChar(PluginPath + PluginPaths[No])); +// if loaded if (hLib <> 0) then begin - //Load Info Procedure - @P_Init := GetProcAddress (hLib, PChar('Init')); - @P_Draw := GetProcAddress (hLib, PChar('Draw')); - @P_Finish := GetProcAddress (hLib, PChar('Finish')); +// load info procedure + @P_Init := GetProcAddress (hLib, 'Init'); + @P_Draw := GetProcAddress (hLib, 'Draw'); + @P_Finish := GetProcAddress (hLib, 'Finish'); - //If Loaded - if (@P_Init <> nil) And (@P_Draw <> nil) And (@P_Finish <> nil) then +// if loaded + if (@P_Init <> nil) and (@P_Draw <> nil) and (@P_Finish <> nil) then begin Selected := @Plugins[No]; - Result := True; + Result := true; end else begin - Log.LogError('Could not Load Plugin "' + PluginPaths[No] + '": Procedures not Found'); - + Log.LogError('Could not load plugin "' + PluginPaths[No] + '": Procedures not found'); end; end - else - Log.LogError('Could not Load Plugin "' + PluginPaths[No] + '": Libary not Loaded'); + else + Log.LogError('Could not load plugin "' + PluginPaths[No] + '": Libary not loaded'); end; procedure TDLLMan.UnLoadPlugin; begin -if (hLib <> 0) then - FreeLibrary (hLib); - -//Selected := nil; -@P_Init := nil; -@P_Draw := nil; -@P_Finish := nil; -@P_RData := nil; + if (hLib <> 0) then + FreeLibrary (hLib); + +// Selected := nil; + @P_Init := nil; + @P_Draw := nil; + @P_Finish := nil; + @P_RData := nil; end; -function TDLLMan.PluginInit (const TeamInfo: TTeamInfo; var Playerinfo: TPlayerinfo; const Sentences: TSentences; const LoadTex: fModi_LoadTex; const Print: fModi_Print; LoadSound: fModi_LoadSound; PlaySound: pModi_PlaySound): boolean; +function TDLLMan.PluginInit (const TeamInfo: TTeamInfo; + var Playerinfo: TPlayerinfo; + const Sentences: TSentences; + const LoadTex: fModi_LoadTex; + const Print: fModi_Print; + LoadSound: fModi_LoadSound; + PlaySound: pModi_PlaySound) + : boolean; var Methods: TMethodRec; begin @@ -250,26 +264,26 @@ begin if (@P_Init <> nil) then Result := P_Init (TeamInfo, PlayerInfo, Sentences, Methods) else - Result := False + Result := true end; -function TDLLMan.PluginDraw (var Playerinfo: TPlayerinfo; const CurSentence: Cardinal): boolean; +function TDLLMan.PluginDraw (var Playerinfo: TPlayerinfo; const CurSentence: cardinal): boolean; begin -if (@P_Draw <> nil) then - Result := P_Draw (PlayerInfo, CurSentence) -else - Result := False + if (@P_Draw <> nil) then + Result := P_Draw (PlayerInfo, CurSentence) + else + Result := true end; function TDLLMan.PluginFinish (var Playerinfo: TPlayerinfo): byte; begin -if (@P_Finish <> nil) then - Result := P_Finish (PlayerInfo) -else - Result := 0; + if (@P_Finish <> nil) then + Result := P_Finish (PlayerInfo) + else + Result := 0; end; -procedure TDLLMan.PluginRData (handle: HSTREAM; buffer: Pointer; len: DWORD; user: DWORD); +procedure TDLLMan.PluginRData (handle: HStream; buffer: Pointer; len: dword; user: dword); begin if (@P_RData <> nil) then P_RData (handle, buffer, len, user); diff --git a/unicode/src/base/UDraw.pas b/unicode/src/base/UDraw.pas index 8a66d271..1783986f 100644 --- a/unicode/src/base/UDraw.pas +++ b/unicode/src/base/UDraw.pas @@ -638,7 +638,7 @@ begin // determine lyric help bar position and size Bounds.Left := MoveStartX + BarProgress * MoveDist; Bounds.Right := Bounds.Left + BarWidth; - Bounds.Top := Skin_LyricsT + 3; + Bounds.Top := Theme.LyricBar.IndicatorYOffset + Theme.LyricBar.UpperY ; Bounds.Bottom := Bounds.Top + BarHeight + 3; // draw lyric help bar diff --git a/unicode/src/base/UEditorLyrics.pas b/unicode/src/base/UEditorLyrics.pas index fe8c3ee5..ef9d8dd6 100644 --- a/unicode/src/base/UEditorLyrics.pas +++ b/unicode/src/base/UEditorLyrics.pas @@ -40,7 +40,7 @@ uses UTexture; type - alignment = (left, center, right); + TAlignmentType = (atLeft, atCenter, atRight); TWord = record X: real; @@ -58,7 +58,7 @@ type TEditorLyrics = class private - AlignI: alignment; + AlignI: TAlignmentType; XR: real; YR: real; SizeR: real; @@ -69,7 +69,7 @@ type procedure SetX(Value: real); procedure SetY(Value: real); function GetClientX: real; - procedure SetAlign(Value: alignment); + procedure SetAlign(Value: TAlignmentType); function GetSize: real; procedure SetSize(Value: real); procedure SetSelected(Value: integer); @@ -96,7 +96,7 @@ type property X: real write SetX; property Y: real write SetY; property ClientX: real read GetClientX; - property Align: alignment write SetAlign; + property Align: TAlignmentType write SetAlign; property Size: real read GetSize write SetSize; property Selected: integer read SelectedI write SetSelected; property FontStyle: integer write SetFontStyle; @@ -137,7 +137,7 @@ begin Result := Word[0].X; end; -procedure TEditorLyrics.SetAlign(Value: alignment); +procedure TEditorLyrics.SetAlign(Value: TAlignmentType); begin AlignI := Value; end; @@ -229,7 +229,7 @@ var WordIndex: integer; TotalWidth: real; begin - if AlignI = center then + if AlignI = atCenter then begin TotalWidth := 0; for WordIndex := 0 to High(Word) do diff --git a/unicode/src/base/UGraphic.pas b/unicode/src/base/UGraphic.pas index 17175d02..818e49aa 100644 --- a/unicode/src/base/UGraphic.pas +++ b/unicode/src/base/UGraphic.pas @@ -198,7 +198,14 @@ var Tex_Score_NoteBarRound_Lightest : array [1..6] of TTexture; Tex_Score_Ratings : array [0..7] of TTexture; - + + // arrows for SelectSlide + Tex_SelectS_ArrowL: TTexture; + Tex_SelectS_ArrowR: TTexture; + + // textures for software mouse cursor + Tex_Cursor_Unpressed: TTexture; + Tex_Cursor_Pressed: TTexture; const Skin_BGColorR = 1; Skin_BGColorG = 1; @@ -232,17 +239,6 @@ const Skin_OscG = 0; Skin_OscB = 0; - // TODO: add to theme ini file - Skin_LyricsT = 493; - Skin_LyricsUpperX = 80; - Skin_LyricsUpperW = 640; - Skin_LyricsUpperY = Skin_LyricsT; - Skin_LyricsUpperH = 41; - Skin_LyricsLowerX = 80; - Skin_LyricsLowerW = 640; - Skin_LyricsLowerY = Skin_LyricsT + Skin_LyricsUpperH + 1; - Skin_LyricsLowerH = 41; - Skin_SpectrumT = 470; Skin_SpectrumBot = 570; Skin_SpectrumH = 100; @@ -339,6 +335,15 @@ begin Tex_Ball := Texture.LoadTexture(Skin.GetTextureFileName('Ball'), TEXTURE_TYPE_TRANSPARENT, $FF00FF); Tex_Lyric_Help_Bar := Texture.LoadTexture(Skin.GetTextureFileName('LyricHelpBar'), TEXTURE_TYPE_TRANSPARENT, $FF00FF); + Tex_SelectS_ArrowL := Texture.LoadTexture(Skin.GetTextureFileName('Select_ArrowLeft'), TEXTURE_TYPE_TRANSPARENT, 0); + Tex_SelectS_ArrowR := Texture.LoadTexture(Skin.GetTextureFileName('Select_ArrowRight'), TEXTURE_TYPE_TRANSPARENT, 0); + + Tex_Cursor_Unpressed := Texture.LoadTexture(Skin.GetTextureFileName('Cursor'), TEXTURE_TYPE_TRANSPARENT, 0); + + if (Skin.GetTextureFileName('Cursor_Pressed') <> '') then + Tex_Cursor_Pressed := Texture.LoadTexture(Skin.GetTextureFileName('Cursor_Pressed'), TEXTURE_TYPE_TRANSPARENT, 0) + else + Tex_Cursor_Pressed.TexNum := 0; //TimeBar mod Tex_TimeProgress := Texture.LoadTexture(Skin.GetTextureFileName('TimeBar')); @@ -497,6 +502,7 @@ begin Log.LogStatus('TDisplay.Create', 'UGraphic.Initialize3D'); Display := TDisplay.Create; + //Display.SetCursor; //Log.BenchmarkEnd(2); Log.LogBenchmark('====> Creating Display', 2); @@ -629,15 +635,15 @@ begin begin Log.LogStatus('SDL_SetVideoMode', 'Set Video Mode... Full Screen'); screen := SDL_SetVideoMode(W, H, (Depth+1) * 16, SDL_OPENGL or SDL_FULLSCREEN ); - SDL_ShowCursor(0); end else begin Log.LogStatus('SDL_SetVideoMode', 'Set Video Mode... Windowed'); screen := SDL_SetVideoMode(W, H, 0, SDL_OPENGL or SDL_RESIZABLE); - SDL_ShowCursor(1); end; + SDL_ShowCursor(0); + if (screen = nil) then begin Log.LogCritical('SDL_SetVideoMode Failed', 'Initialize3D'); diff --git a/unicode/src/base/UHooks.pas b/unicode/src/base/UHooks.pas deleted file mode 100644 index acf2bba7..00000000 --- a/unicode/src/base/UHooks.pas +++ /dev/null @@ -1,460 +0,0 @@ -{* UltraStar Deluxe - Karaoke Game - * - * UltraStar Deluxe is the legal property of its developers, whose names - * are too numerous to list here. Please refer to the COPYRIGHT - * file distributed with this source distribution. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - * $URL$ - * $Id$ - *} - -unit UHooks; - -{********************* - THookManager - Class for saving, managing and calling of hooks. - Saves all hookable events and their subscribers -*********************} -interface - -{$IFDEF FPC} - {$MODE Delphi} -{$ENDIF} - -{$I switches.inc} - -uses - uPluginDefs, - SysUtils; - -type - //Record that saves info from Subscriber - PSubscriberInfo = ^TSubscriberInfo; - TSubscriberInfo = record - Self: THandle; // ID of this Subscription (First word: ID of Subscription; 2nd word: ID of Hook) - Next: PSubscriberInfo; // Pointer to next Item in HookChain - - Owner: integer; //For Error Handling and Plugin Unloading. - - // Here is s/t tricky - // To avoid writing of Wrapping Functions to Hook an Event with a Class - // We save a Normal Proc or a Method of a Class - case isClass: boolean of - false: (Proc: TUS_Hook); //Proc that will be called on Event - true: (ProcOfClass: TUS_Hook_of_Object); - end; - - TEventInfo = record - Name: string[60]; // Name of Event - FirstSubscriber: PSubscriberInfo; // First subscriber in chain - LastSubscriber: PSubscriberInfo; // Last " (for easier subscriber adding) - end; - - THookManager = class - private - Events: array of TEventInfo; - SpaceinEvents: word; //Number of empty Items in Events Array. (e.g. Deleted Items) - - procedure FreeSubscriber(const EventIndex: word; const Last, Cur: PSubscriberInfo); - public - constructor Create(const SpacetoAllocate: word); - - function AddEvent (const EventName: Pchar): THandle; - function DelEvent (hEvent: THandle): integer; - - function AddSubscriber (const EventName: Pchar; const Proc: TUS_Hook = nil; const ProcOfClass: TUS_Hook_of_Object = nil): THandle; - function DelSubscriber (const hSubscriber: THandle): integer; - - function CallEventChain (const hEvent: THandle; const wParam: TwParam; lParam: TlParam): integer; - function EventExists (const EventName: Pchar): integer; - - procedure DelbyOwner(const Owner: integer); - end; - -function HookTest(wParam: TwParam; lParam: TlParam): integer; stdcall; - -var - HookManager: THookManager; - -implementation - -uses - ULog, - UCore; - -//------------ -// Create - Creates Class and Set Standard Values -//------------ -constructor THookManager.Create(const SpacetoAllocate: word); -var - I: integer; -begin - inherited Create(); - - //Get the Space and "Zero" it - SetLength (Events, SpacetoAllocate); - for I := 0 to SpacetoAllocate-1 do - Events[I].Name[1] := chr(0); - - SpaceinEvents := SpacetoAllocate; - - {$IFDEF DEBUG} - debugWriteLn('HookManager: Succesful Created.'); - {$ENDIF} -end; - -//------------ -// AddEvent - Adds an Event and return the Events Handle or 0 on Failure -//------------ -function THookManager.AddEvent (const EventName: Pchar): THandle; -var - I: integer; -begin - Result := 0; - - if (EventExists(EventName) = 0) then - begin - if (SpaceinEvents > 0) then - begin - //There is already Space available - //Go Search it! - for I := 0 to High(Events) do - if (Events[I].Name[1] = chr(0)) then - begin //Found Space - Result := I; - Dec(SpaceinEvents); - Break; - end; - - {$IFDEF DEBUG} - debugWriteLn('HookManager: Found Space for Event at Handle: ''' + InttoStr(Result+1) + ''); - {$ENDIF} - end - else - begin //There is no Space => Go make some! - Result := Length(Events); - SetLength(Events, Result + 1); - end; - - //Set Events Data - Events[Result].Name := EventName; - Events[Result].FirstSubscriber := nil; - Events[Result].LastSubscriber := nil; - - //Handle is Index + 1 - Inc(Result); - - {$IFDEF DEBUG} - debugWriteLn('HookManager: Add Event succesful: ''' + EventName + ''); - {$ENDIF} - end - {$IFDEF DEBUG} - else - debugWriteLn('HookManager: Trying to ReAdd Event: ''' + EventName + ''); - {$ENDIF} -end; - -//------------ -// DelEvent - Deletes an Event by Handle Returns False on Failure -//------------ -function THookManager.DelEvent (hEvent: THandle): integer; -var - Cur, Last: PSubscriberInfo; -begin - hEvent := hEvent - 1; //Arrayindex is Handle - 1 - Result := -1; - - if (Length(Events) > hEvent) and (Events[hEvent].Name[1] <> chr(0)) then - begin //Event exists - //Free the Space for all Subscribers - Cur := Events[hEvent].FirstSubscriber; - - while (Cur <> nil) do - begin - Last := Cur; - Cur := Cur.Next; - FreeMem(Last, SizeOf(TSubscriberInfo)); - end; - - {$IFDEF DEBUG} - debugWriteLn('HookManager: Removed Event succesful: ''' + Events[hEvent].Name + ''); - {$ENDIF} - - //Free the Event - Events[hEvent].Name[1] := chr(0); - Inc(SpaceinEvents); //There is one more space for new events - end - - {$IFDEF DEBUG} - else - debugWriteLn('HookManager: Try to Remove not Existing Event. Handle: ''' + InttoStr(hEvent) + ''); - {$ENDIF} -end; - -//------------ -// AddSubscriber - Adds an Subscriber to the Event by Name -// Returns Handle of the Subscribtion or 0 on Failure -//------------ -function THookManager.AddSubscriber (const EventName: Pchar; const Proc: TUS_Hook; const ProcOfClass: TUS_Hook_of_Object): THandle; -var - EventHandle: THandle; - EventIndex: integer; - Cur: PSubscriberInfo; -begin - Result := 0; - - if (@Proc <> nil) or (@ProcOfClass <> nil) then - begin - EventHandle := EventExists(EventName); - - if (EventHandle <> 0) then - begin - EventIndex := EventHandle - 1; - - //Get Memory - GetMem(Cur, SizeOf(TSubscriberInfo)); - - //Fill it with Data - Cur.Next := nil; - - //Add Owner - Cur.Owner := Core.CurExecuted; - - if (@Proc = nil) then - begin //Use the ProcofClass Method - Cur.isClass := true; - Cur.ProcOfClass := ProcofClass; - end - else //Use the normal Proc - begin - Cur.isClass := false; - Cur.Proc := Proc; - end; - - //Create Handle (1st word: Handle of Event; 2nd word: unique ID - if (Events[EventIndex].LastSubscriber = nil) then - begin - if (Events[EventIndex].FirstSubscriber = nil) then - begin - Result := (EventHandle SHL 16); - Events[EventIndex].FirstSubscriber := Cur; - end - else - begin - Result := Events[EventIndex].FirstSubscriber.Self + 1; - end; - end - else - begin - Result := Events[EventIndex].LastSubscriber.Self + 1; - Events[EventIndex].LastSubscriber.Next := Cur; - end; - - Cur.Self := Result; - - //Add to Chain - Events[EventIndex].LastSubscriber := Cur; - - {$IFDEF DEBUG} - debugWriteLn('HookManager: Add Subscriber to Event ''' + Events[EventIndex].Name + ''' succesful. Handle: ''' + InttoStr(Result) + ''' Owner: ' + InttoStr(Cur.Owner)); - {$ENDIF} - end; - end; -end; - -//------------ -// FreeSubscriber - Helper for DelSubscriber. Prevents Loss of Chain Items. Frees Memory. -//------------ -procedure THookManager.FreeSubscriber(const EventIndex: word; const Last, Cur: PSubscriberInfo); -begin - //Delete from Chain - if (Last <> nil) then - begin - Last.Next := Cur.Next; - end - else //Was first Popup - begin - Events[EventIndex].FirstSubscriber := Cur.Next; - end; - - //Was this Last subscription ? - if (Cur = Events[EventIndex].LastSubscriber) then - begin //Change Last Subscriber - Events[EventIndex].LastSubscriber := Last; - end; - - //Free Space: - FreeMem(Cur, SizeOf(TSubscriberInfo)); -end; - -//------------ -// DelSubscriber - Deletes a Subscribtion by Handle, return non Zero on Failure -//------------ -function THookManager.DelSubscriber (const hSubscriber: THandle): integer; -var - EventIndex: integer; - Cur, Last: PSubscriberInfo; -begin - Result := -1; - EventIndex := ((hSubscriber and (High(THandle) xor High(word))) SHR 16) - 1; - - //Existing Event ? - if (EventIndex < Length(Events)) and (Events[EventIndex].Name[1] <> chr(0)) then - begin - Result := -2; //Return -1 on not existing Event, -2 on not existing Subscription - - //Search for Subscription - Cur := Events[EventIndex].FirstSubscriber; - Last := nil; - - //go through the chain ... - while (Cur <> nil) do - begin - if (Cur.Self = hSubscriber) then - begin //Found Subscription we searched for - FreeSubscriber(EventIndex, Last, Cur); - - {$IFDEF DEBUG} - debugWriteLn('HookManager: Del Subscriber from Event ''' + Events[EventIndex].Name + ''' succesful. Handle: ''' + InttoStr(hSubscriber) + ''); - {$ENDIF} - - //Set Result and Break the Loop - Result := 0; - Break; - end; - - Last := Cur; - Cur := Cur.Next; - end; - - end; -end; - -//------------ -// CallEventChain - Calls the Chain of a specified EventHandle -// Returns: -1: Handle doesn't Exist, 0 Chain is called until the End -//------------ -function THookManager.CallEventChain (const hEvent: THandle; const wParam: TwParam; lParam: TlParam): integer; -var - EventIndex: integer; - Cur: PSubscriberInfo; - CurExecutedBackup: integer; // backup of Core.CurExecuted Attribute -begin - Result := -1; - EventIndex := hEvent - 1; - - if ((EventIndex <= High(Events)) and (Events[EventIndex].Name[1] <> chr(0))) then - begin //Existing Event - //Backup CurExecuted - CurExecutedBackup := Core.CurExecuted; - - //Start calling the Chain !!!11 - Cur := Events[EventIndex].FirstSubscriber; - Result := 0; - //Call Hooks until the Chain is at the End or breaked - while ((Cur <> nil) and (Result = 0)) do - begin - //Set CurExecuted - Core.CurExecuted := Cur.Owner; - if (Cur.isClass) then - Result := Cur.ProcOfClass(wParam, lParam) - else - Result := Cur.Proc(wParam, lParam); - - Cur := Cur.Next; - end; - - //Restore CurExecuted - Core.CurExecuted := CurExecutedBackup; - end; - - {$IFDEF DEBUG} - debugWriteLn('HookManager: Called Chain from Event ''' + Events[EventIndex].Name + ''' succesful. Result: ''' + InttoStr(Result) + ''); - {$ENDIF} -end; - -//------------ -// EventExists - Returns non Zero if an Event with the given Name exists -//------------ -function THookManager.EventExists (const EventName: Pchar): integer; -var - I: integer; - Name: string[60]; -begin - Result := 0; - //if (Length(EventName) < - Name := string(EventName); - - //Sure not to search for empty space - if (Name[1] <> chr(0)) then - begin - //Search for Event - for I := 0 to High(Events) do - if (Events[I].Name = Name) then - begin //Event found - Result := I + 1; - Break; - end; - end; -end; - -//------------ -// DelbyOwner - Dels all Subscriptions by a specific Owner. (For Clean Plugin/Module unloading) -//------------ -procedure THookManager.DelbyOwner(const Owner: integer); -var - I: integer; - Cur, Last: PSubscriberInfo; -begin - //Search for Owner in all Hooks Chains - for I := 0 to High(Events) do - begin - if (Events[I].Name[1] <> chr(0)) then - begin - - Last := nil; - Cur := Events[I].FirstSubscriber; - //Went Through Chain - while (Cur <> nil) do - begin - if (Cur.Owner = Owner) then - begin //Found Subscription by Owner -> Delete - FreeSubscriber(I, Last, Cur); - if (Last <> nil) then - Cur := Last.Next - else - Cur := Events[I].FirstSubscriber; - end - else - begin - //Next Item: - Last := Cur; - Cur := Cur.Next; - end; - end; - end; - end; -end; - -function HookTest(wParam: TwParam; lParam: TlParam): integer; stdcall; -begin - Result := 0; //Don't break the chain - Core.ShowMessage(CORE_SM_INFO, Pchar(string(Pchar(Pointer(lParam))) + ': ' + string(Pchar(Pointer(wParam))))); -end; - -end. diff --git a/unicode/src/base/UImage.pas b/unicode/src/base/UImage.pas index 8dc38495..60b0a3a2 100644 --- a/unicode/src/base/UImage.pas +++ b/unicode/src/base/UImage.pas @@ -311,13 +311,13 @@ var hour, minute, second, msecond: word; begin DecodeDate(time, year, month, day); - pngTime.year := year; - pngTime.month := month; - pngTime.day := day; + pngTime.year := png_uint_16(year); + pngTime.month := png_byte(month); + pngTime.day := png_byte(day); DecodeTime(time, hour, minute, second, msecond); - pngTime.hour := hour; - pngTime.minute := minute; - pngTime.second := second; + pngTime.hour := png_byte(hour); + pngTime.minute := png_byte(minute); + pngTime.second := png_byte(second); end; (* @@ -896,8 +896,13 @@ procedure ColorizeImage(ImgSurface: PSDL_Surface; NewColor: cardinal); // replaced by division of longwords, shifted by 10 bits to keep // digits. + // The use of longwards leeds to some type size mismatch warnings + // whenever differences are formed. + // This should not be a problem, since the results should all be positive. + // replacing longword by longint would probably resolve this cosmetic fault :-) + function ColorToHue(const Color: longword): longword; - // returns hue within the range [0.0-6.0] but shl 10, ie. times 1024 + // returns hue within the range [0.0-6.0] but shl 10, ie. times 1024 var Red, Green, Blue: longword; Min, Max, Delta: longword; @@ -919,7 +924,8 @@ procedure ColorizeImage(ImgSurface: PSDL_Surface; NewColor: cardinal); if Blue > Max then Max := Blue; // calc hue - Delta := Max - Min; + Delta := Max - Min; // This gives a type size mismatch warning, because Delta is longword, ie. >= 0 + // But the assignments above are easy enough to be sure, that Max - Min is >= 0. if (Delta = 0) then Result := 0 else @@ -1023,16 +1029,19 @@ begin end else // all colors except black and white begin - Delta := Max - Min; + Delta := Max - Min; // This gives a type size mismatch warning, because Delta is longword, ie. >= 0 + // But the assignments above are easy enough to be sure, that Max - Min is >= 0. Sat := (Delta shl 10) div Max; // shl 10 - // shr 10 corrects that sat and f are shl 10 + // shr 10 corrects that Sat and f are shl 10 // the resulting p, q and t are unshifted p := (Max*(1024-Sat)) shr 10; q := (Max*(1024-(Sat*f) shr 10)) shr 10; t := (Max*(1024-(Sat*(1024-f)) shr 10)) shr 10; + // The above 3 lines give type size mismatch warning, but all variables are longword and the ranges should be ok. + case HueInteger of 0: begin Red := Max; Green := t; Blue := p; end; // (v,t,p) 1: begin Red := q; Green := Max; Blue := p; end; // (q,v,p) @@ -1043,13 +1052,13 @@ begin end; {$IFDEF FPC_BIG_ENDIAN} - PixelColors[3] := Red; - PixelColors[2] := Green; - PixelColors[1] := Blue + PixelColors[3] := byte(Red); + PixelColors[2] := byte(Green); + PixelColors[1] := byte(Blue); {$ELSE} - PixelColors[0] := Red; - PixelColors[1] := Green; - PixelColors[2] := Blue; + PixelColors[0] := byte(Red); + PixelColors[1] := byte(Green); + PixelColors[2] := byte(Blue); {$ENDIF} end; diff --git a/unicode/src/base/UIni.pas b/unicode/src/base/UIni.pas index 241b34e8..9a09ca91 100644 --- a/unicode/src/base/UIni.pas +++ b/unicode/src/base/UIni.pas @@ -155,6 +155,7 @@ type // Controller Joypad: integer; + Mouse: integer; // default encoding for texts (lyrics, song-name, ...) EncodingDefault: TEncoding; @@ -198,14 +199,13 @@ const IBackgroundMusic: array[0..1] of string = ('Off', 'On'); - ITextureSize: array[0..2] of string = ('128', '256', '512'); - ITextureSizeVals: array[0..2] of integer = ( 128, 256, 512); + ITextureSize: array[0..3] of string = ('64', '128', '256', '512'); + ITextureSizeVals: array[0..3] of integer = ( 64, 128, 256, 512); ISingWindow: array[0..1] of string = ('Small', 'Big'); //SingBar Mod - IOscilloscope: array[0..2] of string = ('Off', 'Osci', 'Bar'); -//IOscilloscope: array[0..1] of string = ('Off', 'On'); + IOscilloscope: array[0..1] of string = ('Off', 'On'); ISpectrum: array[0..1] of string = ('Off', 'On'); ISpectrograph: array[0..1] of string = ('Off', 'On'); @@ -246,10 +246,11 @@ const IScreenFade: array[0..1] of string = ('Off', 'On'); IAskbeforeDel: array[0..1] of string = ('Off', 'On'); IOnSongClick: array[0..2] of string = ('Sing', 'Select Players', 'Open Menu'); - ILineBonus: array[0..2] of string = ('Off', 'At Score', 'At Notes'); + ILineBonus: array[0..1] of string = ('Off', 'On'); IPartyPopup: array[0..1] of string = ('Off', 'On'); IJoypad: array[0..1] of string = ('Off', 'On'); + IMouse: array[0..2] of string = ('Off', 'Hardware Cursor', 'Software Cursor'); // Recording options IChannelPlayer: array[0..6] of string = ('Off', '1', '2', '3', '4', '5', '6'); @@ -686,7 +687,7 @@ begin SingWindow := GetArrayIndex(ISingWindow, IniFile.ReadString('Graphics', 'SingWindow', 'Big')); // Oscilloscope - Oscilloscope := GetArrayIndex(IOscilloscope, IniFile.ReadString('Graphics', 'Oscilloscope', 'Bar')); + Oscilloscope := GetArrayIndex(IOscilloscope, IniFile.ReadString('Graphics', 'Oscilloscope', IOscilloscope[0])); // Spectrum Spectrum := GetArrayIndex(ISpectrum, IniFile.ReadString('Graphics', 'Spectrum', 'Off')); @@ -713,16 +714,16 @@ begin PreviewVolume := GetArrayIndex(IPreviewVolume, IniFile.ReadString('Sound', 'PreviewVolume', IPreviewVolume[7])); //Preview Fading - PreviewFading := GetArrayIndex(IPreviewFading, IniFile.ReadString('Sound', 'PreviewFading', IPreviewFading[1])); + PreviewFading := GetArrayIndex(IPreviewFading, IniFile.ReadString('Sound', 'PreviewFading', IPreviewFading[3])); //AudioRepeat aka VoicePassthrough VoicePassthrough := GetArrayIndex(IVoicePassthrough, IniFile.ReadString('Sound', 'VoicePassthrough', IVoicePassthrough[0])); // Lyrics Font - LyricsFont := GetArrayIndex(ILyricsFont, IniFile.ReadString('Lyrics', 'LyricsFont', ILyricsFont[1])); + LyricsFont := GetArrayIndex(ILyricsFont, IniFile.ReadString('Lyrics', 'LyricsFont', ILyricsFont[0])); // Lyrics Effect - LyricsEffect := GetArrayIndex(ILyricsEffect, IniFile.ReadString('Lyrics', 'LyricsEffect', ILyricsEffect[1])); + LyricsEffect := GetArrayIndex(ILyricsEffect, IniFile.ReadString('Lyrics', 'LyricsEffect', ILyricsEffect[2])); // Solmization Solmization := GetArrayIndex(ISolmization, IniFile.ReadString('Lyrics', 'Solmization', ISolmization[0])); @@ -770,7 +771,7 @@ begin OnSongClick := GetArrayIndex(IOnSongClick, IniFile.ReadString('Advanced', 'OnSongClick', 'Sing')); // Linebonus - LineBonus := GetArrayIndex(ILineBonus, IniFile.ReadString('Advanced', 'LineBonus', 'At Score')); + LineBonus := GetArrayIndex(ILineBonus, IniFile.ReadString('Advanced', 'LineBonus', ILineBonus[1])); // PartyPopup PartyPopup := GetArrayIndex(IPartyPopup, IniFile.ReadString('Advanced', 'PartyPopup', 'On')); @@ -778,6 +779,9 @@ begin // Joypad Joypad := GetArrayIndex(IJoypad, IniFile.ReadString('Controller', 'Joypad', IJoypad[0])); + // Mouse + Mouse := GetArrayIndex(IMouse, IniFile.ReadString('Controller', 'Mouse', IMouse[2])); + LoadPaths(IniFile); IniFile.Free; @@ -920,6 +924,9 @@ begin // Joypad IniFile.WriteString('Controller', 'Joypad', IJoypad[Joypad]); + // Mouse + IniFile.WriteString('Controller', 'Mouse', IMouse[Mouse]); + // Directories (add a template if section is missing) // Note: Value must be ' ' and not '', otherwise no key is generated on Linux if (not IniFile.SectionExists('Directories')) then diff --git a/unicode/src/base/UMain.pas b/unicode/src/base/UMain.pas index 8d11b91d..1962e953 100644 --- a/unicode/src/base/UMain.pas +++ b/unicode/src/base/UMain.pas @@ -66,11 +66,6 @@ implementation uses Math, gl, -{ - SDL_ttf, - UParty, - UCore, -} UCatCovers, UCommandLine, UCommon, @@ -88,10 +83,12 @@ uses UPath, UPlaylist, UMusic, + UBeatTimer, UPlatform, USkins, USongs, UThemes, + UParty, UTime; procedure Main; @@ -236,14 +233,12 @@ begin Log.BenchmarkEnd(1); Log.LogBenchmark('Loading PluginManager', 1); -{ // Party Mode Manager Log.BenchmarkStart(1); Log.LogStatus('PartySession Manager', 'Initialization'); PartySession := TPartySession.Create; //Load PartySession Log.BenchmarkEnd(1); Log.LogBenchmark('Loading PartySession Manager', 1); -} // Graphics Log.BenchmarkStart(1); @@ -364,9 +359,11 @@ begin CountMidTime; Delay := Floor(1000 / MAX_FPS - 1000 * TimeMid); + Log.LogError ('MainLoop', 'Delay: ' + intToStr(Delay)); if Delay >= 1 then SDL_Delay(Delay); // dynamic, maximum is 100 fps + Log.LogError ('MainLoop', 'Delay: ok ' + intToStr(Delay)); CountSkipTime; @@ -380,9 +377,26 @@ begin end; end; +procedure DoQuit; +begin + // if question option is enabled then show exit popup + if (Ini.AskbeforeDel = 1) then + begin + Display.CurrentScreen^.CheckFadeTo(nil,'MSG_QUIT_USDX'); + end + else // if ask-for-exit is disabled then simply exit + begin + Display.Fade := 0; + Display.NextScreenWithCheck := nil; + Display.CheckOK := true; + end; +end; + procedure CheckEvents; var - Event: TSDL_event; + Event: TSDL_event; + mouseDown: boolean; + mouseBtn: integer; begin if Assigned(Display.NextScreen) then Exit; @@ -396,17 +410,46 @@ begin Display.NextScreenWithCheck := nil; Display.CheckOK := true; end; - SDL_MOUSEBUTTONDOWN: + + SDL_MOUSEMOTION, SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP: begin -{ - with Event.button do + if (Ini.Mouse > 0) then begin - if State = SDL_BUTTON_LEFT then + case Event.type_ of + SDL_MOUSEMOTION: + begin + mouseDown := false; + mouseBtn := 0; + end; + SDL_MOUSEBUTTONDOWN: + begin + mouseDown := true; + mouseBtn := Event.button.button; + end; + SDL_MOUSEBUTTONUP: + begin + mouseDown := false; + mouseBtn := Event.button.button; + end; + end; + + Display.MoveCursor(Event.button.X * 800 / Screen.w, + Event.button.Y * 600 / Screen.h, + mouseDown and ((mouseBtn <> SDL_BUTTON_WHEELDOWN) or (mouseBtn <> SDL_BUTTON_WHEELUP))); + + if (ScreenPopupError <> nil) and (ScreenPopupError.Visible) then + done := not ScreenPopupError.ParseMouse(mouseBtn, mouseDown, Event.button.x, Event.button.y) + else if (ScreenPopupCheck <> nil) and (ScreenPopupCheck.Visible) then + done := not ScreenPopupCheck.ParseMouse(mouseBtn, mouseDown, Event.button.x, Event.button.y) + else begin - // + done := not Display.CurrentScreen^.ParseMouse(mouseBtn, mouseDown, Event.button.x, Event.button.y); + + // if screen wants to exit + if done then + DoQuit; end; end; -} end; SDL_VIDEORESIZE: begin @@ -442,14 +485,14 @@ begin if boolean( Ini.FullScreen ) then begin SDL_SetVideoMode(ScreenW, ScreenH, (Ini.Depth+1) * 16, SDL_OPENGL or SDL_FULLSCREEN); - SDL_ShowCursor(0); end else begin SDL_SetVideoMode(ScreenW, ScreenH, (Ini.Depth+1) * 16, SDL_OPENGL or SDL_RESIZABLE); - SDL_ShowCursor(1); end; + Display.SetCursor; + glViewPort(0, 0, ScreenW, ScreenH); {$IFEND} end @@ -469,19 +512,7 @@ begin // if screen wants to exit if Done then - begin - // if question option is enabled then show exit popup - if (Ini.AskbeforeDel = 1) then - begin - Display.CurrentScreen^.CheckFadeTo(nil,'MSG_QUIT_USDX'); - end - else // if ask-for-exit is disabled then simply exit - begin - Display.Fade := 0; - Display.NextScreenWithCheck := nil; - Display.CheckOK := true; - end; - end; + DoQuit; end; end; diff --git a/unicode/src/base/UModules.pas b/unicode/src/base/UModules.pas deleted file mode 100644 index 97494180..00000000 --- a/unicode/src/base/UModules.pas +++ /dev/null @@ -1,55 +0,0 @@ -{* UltraStar Deluxe - Karaoke Game - * - * UltraStar Deluxe is the legal property of its developers, whose names - * are too numerous to list here. Please refer to the COPYRIGHT - * file distributed with this source distribution. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - * $URL$ - * $Id$ - *} - -unit UModules; - -interface - -{$IFDEF FPC} - {$MODE Delphi} -{$ENDIF} - -{$I switches.inc} - -{********************* - UModules - Unit Contains all used Modules in its uses clausel - and a const with an array of all Modules to load -*********************} - -uses - UCoreModule, - UPluginLoader; - -const - CORE_MODULES_TO_LOAD: Array[0..2] of cCoreModule = ( - TPluginLoader, //First because it has to look if there are Module replacements (Feature o/t Future) - TCoreModule, //Remove this later, just a dummy - TtehPlugins //Represents the Plugins. Last because they may use CoreModules Services etc. - ); - -implementation - -end. \ No newline at end of file diff --git a/unicode/src/base/UMusic.pas b/unicode/src/base/UMusic.pas index 19c3b942..5fc9805f 100644 --- a/unicode/src/base/UMusic.pas +++ b/unicode/src/base/UMusic.pas @@ -36,7 +36,8 @@ interface uses UTime, SysUtils, - Classes; + Classes, + UBeatTimer; type TNoteType = (ntFreestyle, ntNormal, ntGolden); @@ -99,51 +100,6 @@ type Line: array of TLine; end; - (** - * TLyricsState contains all information concerning the - * state of the lyrics, e.g. the current beat or duration of the lyrics. - *) - TLyricsState = class - private - Timer: TRelativeTimer; // keeps track of the current time - public - OldBeat: integer; // previous discovered beat - CurrentBeat: integer; // current beat (rounded) - MidBeat: real; // current beat (float) - - // now we use this for super synchronization! - // only used when analyzing voice - // TODO: change ...D to ...Detect(ed) - OldBeatD: integer; // previous discovered beat - CurrentBeatD: integer; // current discovered beat (rounded) - MidBeatD: real; // current discovered beat (float) - - // we use this for audible clicks - // TODO: Change ...C to ...Click - OldBeatC: integer; // previous discovered beat - CurrentBeatC: integer; - MidBeatC: real; // like CurrentBeatC - - OldLine: integer; // previous displayed sentence - - StartTime: real; // time till start of lyrics (= Gap) - TotalTime: real; // total song time - - constructor Create(); - procedure Pause(); - procedure Resume(); - - procedure Reset(); - procedure UpdateBeats(); - - (** - * current song time (in seconds) used as base-timer for lyrics etc. - *) - function GetCurrentTime(): real; - procedure SetCurrentTime(Time: real); - end; - - const FFTSize = 512; // size of FFT data (output: FFTSize/2 values) type @@ -977,92 +933,6 @@ begin end; end; - -{ TVoiceRemoval } - -constructor TLyricsState.Create(); -begin - // create a triggered timer, so we can Pause() it, set the time - // and Resume() it afterwards for better synching. - Timer := TRelativeTimer.Create(true); - - // reset state - Reset(); -end; - -procedure TLyricsState.Pause(); -begin - Timer.Pause(); -end; - -procedure TLyricsState.Resume(); -begin - Timer.Resume(); -end; - -procedure TLyricsState.SetCurrentTime(Time: real); -begin - // do not start the timer (if not started already), - // after setting the current time - Timer.SetTime(Time, false); -end; - -function TLyricsState.GetCurrentTime(): real; -begin - Result := Timer.GetTime(); -end; - -(** - * Resets the timer and state of the lyrics. - * The timer will be stopped afterwards so you have to call Resume() - * to start the lyrics timer. - *) -procedure TLyricsState.Reset(); -begin - Pause(); - SetCurrentTime(0); - - StartTime := 0; - TotalTime := 0; - - OldBeat := -1; - MidBeat := -1; - CurrentBeat := -1; - - OldBeatC := -1; - MidBeatC := -1; - CurrentBeatC := -1; - - OldBeatD := -1; - MidBeatD := -1; - CurrentBeatD := -1; -end; - -(** - * Updates the beat information (CurrentBeat/MidBeat/...) according to the - * current lyric time. - *) -procedure TLyricsState.UpdateBeats(); -var - CurLyricsTime: real; -begin - CurLyricsTime := GetCurrentTime(); - - OldBeat := CurrentBeat; - MidBeat := GetMidBeat(CurLyricsTime - StartTime / 1000); - CurrentBeat := Floor(MidBeat); - - OldBeatC := CurrentBeatC; - MidBeatC := GetMidBeat(CurLyricsTime - StartTime / 1000); - CurrentBeatC := Floor(MidBeatC); - - OldBeatD := CurrentBeatD; - // MidBeatD = MidBeat with additional GAP - MidBeatD := -0.5 + GetMidBeat(CurLyricsTime - (StartTime + 120 + 20) / 1000); - CurrentBeatD := Floor(MidBeatD); -end; - - { TAudioConverter } function TAudioConverter.Init(SrcFormatInfo: TAudioFormatInfo; DstFormatInfo: TAudioFormatInfo): boolean; diff --git a/unicode/src/base/UNote.pas b/unicode/src/base/UNote.pas index 5e70bfe1..6da4cf07 100644 --- a/unicode/src/base/UNote.pas +++ b/unicode/src/base/UNote.pas @@ -126,12 +126,10 @@ uses UDLLManager, UParty, UConfig, - UCore, UCommon, UGraphic, UGraphicClasses, UPath, - UPluginDefs, UPlatform, UThemes; diff --git a/unicode/src/base/UParty.pas b/unicode/src/base/UParty.pas index 937aab78..b02d13be 100644 --- a/unicode/src/base/UParty.pas +++ b/unicode/src/base/UParty.pas @@ -34,208 +34,85 @@ interface {$I switches.inc} uses - UPartyDefs, - UCoreModule, - UPluginDefs; + ModiSDK; type - ARounds = array [0..252] of integer; //0..252 needed for - PARounds = ^ARounds; - TRoundInfo = record - Modi: cardinal; + Plugin: word; Winner: byte; end; TeamOrderEntry = record - Teamnum: byte; - Score: byte; + TeamNum: byte; + Score: byte; end; TeamOrderArray = array[0..5] of byte; - TUS_ModiInfoEx = record - Info: TUS_ModiInfo; - Owner: integer; - TimesPlayed: byte; //Helper for setting round plugins + TPartyPlugin = record + ID: byte; + TimesPlayed: byte; end; - TPartySession = class (TCoreModule) + TPartySession = class private - bPartyMode: boolean; //Is this party or single player - CurRound: byte; - - Modis: array of TUS_ModiInfoEx; - Teams: TTeamInfo; - + function GetRandomPlayer(Team: byte): byte; + function GetRandomPlugin(Plugins: array of TPartyPlugin): byte; function IsWinner(Player, Winner: byte): boolean; procedure GenScores; - function GetRandomPlugin(TeamMode: boolean): cardinal; - function GetRandomPlayer(Team: byte): byte; public - //Teams: TTeamInfo; - Rounds: array of TRoundInfo; - - //TCoreModule methods to inherit - constructor Create; override; - procedure Info(const pInfo: PModuleInfo); override; - function Load: boolean; override; - function Init: boolean; override; - procedure DeInit; override; - destructor Destroy; override; - - //Register modus service - function RegisterModi(nothin: TwParam; pModiInfo: TlParam): integer; //Registers a new modus. wParam: Pointer to TUS_ModiInfo - - //Start new Party - function StartParty(NumRounds: TwParam; PAofIRounds: TlParam): integer; //Starts new party mode. Returns non zero on success - function GetCurModi(wParam: TwParam; lParam: TlParam): integer; //Returns pointer to cur. Modis TUS_ModiInfo (to Use with Singscreen) - function StopParty(wParam: TwParam; lParam: TlParam): integer; //Stops party mode. Returns 1 if party mode was enabled before. - function NextRound(wParam: TwParam; lParam: TlParam): integer; //Increases curround by 1; Returns num of round or -1 if last round is already played - - function CallModiInit(wParam: TwParam; lParam: TlParam): integer; //Calls curmodis init proc. If an error occurs, returns nonzero. In this case a new plugin was selected. Please renew loading - function CallModiDeInit(wParam: TwParam; lParam: TlParam): integer; //Calls DeInitProc and ends the round - - function GetTeamInfo(wParam: TwParam; pTeamInfo: TlParam): integer; //Writes TTeamInfo record to pointer at lParam. Returns zero on success - function SetTeamInfo(wParam: TwParam; pTeamInfo: TlParam): integer; //Read TTeamInfo record from pointer at lParam. Returns zero on success - - function GetTeamOrder(wParam: TwParam; lParam: TlParam): integer; //Returns team order. Structure: Bits 1..3: Team at place1; Bits 4..6: Team at place2 ... - function GetWinnerString(wParam: TwParam; lParam: TlParam): integer; //wParam is roundnum. If (Pointer = nil) then return length of the string. Otherwise write the string to address at lParam + Teams: TTeamInfo; + Rounds: array of TRoundInfo; + CurRound: byte; + + constructor Create; + + procedure StartNewParty(NumRounds: byte); + procedure StartRound; + procedure EndRound; + function GetTeamOrder: TeamOrderArray; + function GetWinnerString(Round: byte): string; end; -const - StandardModus = 0; //Modus ID that will be played in non-party mode +var + PartySession: TPartySession; implementation uses - UCore, + UDLLManager, UGraphic, - ULanguage, - ULog, UNote, - SysUtils; - -{********************* - TPluginLoader - Implentation -*********************} - -//------------- -// function that gives some infos about the module to the core -//------------- -procedure TPartySession.Info(const pInfo: PModuleInfo); -begin - pInfo^.Name := 'TPartySession'; - pInfo^.Version := MakeVersion(1,0,0,chr(0)); - pInfo^.Description := 'Manages party modi and party game'; -end; + ULanguage, + ULog; -//------------- -// Just the constructor -//------------- constructor TPartySession.Create; begin inherited; - //UnSet PartyMode - bPartyMode := false; -end; - -//------------- -//Is called on loading. -//In this method only events and services should be created -//to offer them to other modules or plugins during the init process -//If false is returned this will cause a forced exit -//------------- -function TPartySession.Load: boolean; -begin - //Add register party modus service - Result := true; - Core.Services.AddService('Party/RegisterModi', nil, Self.RegisterModi); - Core.Services.AddService('Party/StartParty', nil, Self.StartParty); - Core.Services.AddService('Party/GetCurModi', nil, Self.GetCurModi); -end; - -//------------- -//Is called on init process -//In this method you can hook some events and create + init -//your classes, variables etc. -//If false is returned this will cause a forced exit -//------------- -function TPartySession.Init: boolean; -begin - //Just set private var to true. - Result := true; -end; - -//------------- -//Is called if this module has been inited and there is an exit. -//Deinit is in reverse initing order -//------------- -procedure TPartySession.DeInit; -begin - //Force DeInit -end; - -//------------- -//Is called if this module will be unloaded and has been created -//Should be used to free memory -//------------- -destructor TPartySession.Destroy; -begin - //Just save some memory if it wasn't done now.. - SetLength(Modis, 0); - inherited; -end; - -//------------- -// Registers a new modus. wParam: Pointer to TUS_ModiInfo -// Service for plugins -//------------- -function TPartySession.RegisterModi(nothin: TwParam; pModiInfo: TlParam): integer; -var - Len: integer; - Info: PUS_ModiInfo; -begin - Info := PModiInfo; - //Copy Info if cbSize is correct - if (Info.cbSize = SizeOf(TUS_ModiInfo)) then - begin - Len := Length(Modis); - SetLength(Modis, Len + 1); - - Modis[Len].Info := Info^; - end - else - Core.ReportError(integer(PChar('Plugins try to register modus with wrong pointer, or wrong TUS_ModiInfo record.')), PChar('TPartySession')); - - // FIXME: return a valid result - Result := 0; end; //---------- // Returns a number of a random plugin //---------- -function TPartySession.GetRandomPlugin(TeamMode: boolean): cardinal; +function TPartySession.GetRandomPlugin(Plugins: array of TPartyPlugin): byte; var - LowestTP: byte; + LowestTP: byte; NumPwithLTP: word; - I: integer; - R: word; + I: integer; + R: word; begin - Result := StandardModus; //If there are no matching modi, play standard modus LowestTP := high(byte); NumPwithLTP := 0; //Search for Plugins not often played yet - for I := 0 to high(Modis) do + for I := 0 to high(Plugins) do begin - if (Modis[I].TimesPlayed < lowestTP) and (((Modis[I].Info.LoadingSettings and MLS_TeamOnly) <> 0) = TeamMode) then + if (Plugins[I].TimesPlayed < lowestTP) then begin - lowestTP := Modis[I].TimesPlayed; + lowestTP := Plugins[I].TimesPlayed; NumPwithLTP := 1; end - else if (Modis[I].TimesPlayed = lowestTP) and (((Modis[I].Info.LoadingSettings and MLS_TeamOnly) <> 0) = TeamMode) then + else if (Plugins[I].TimesPlayed = lowestTP) then begin Inc(NumPwithLTP); end; @@ -245,118 +122,97 @@ begin R := Random(NumPwithLTP); //Search for random plugin - for I := 0 to high(Modis) do + for I := 0 to high(Plugins) do begin - if (Modis[I].TimesPlayed = lowestTP) and (((Modis[I].Info.LoadingSettings and MLS_TeamOnly) <> 0) = TeamMode) then + if Plugins[I].TimesPlayed = LowestTP then begin //Plugin found if (R = 0) then begin - Result := I; - Inc(Modis[I].TimesPlayed); + Result := Plugins[I].ID; + Inc(Plugins[I].TimesPlayed); Break; end; - Dec(R); end; end; end; //---------- -// Starts new party mode. Returns non zero on success +//StartNewParty - Reset and prepares for new party //---------- -function TPartySession.StartParty(NumRounds: TwParam; PAofIRounds: TlParam): integer; +procedure TPartySession.StartNewParty(NumRounds: byte); var - I: integer; - aiRounds: PARounds; + Plugins: array of TPartyPlugin; TeamMode: boolean; + Len: integer; + I, J: integer; begin - Result := 0; - if (Teams.NumTeams >= 1) and (NumRounds < High(byte)-1) then - begin - bPartyMode := false; - aiRounds := PAofIRounds; - - try - //Is this team mode (More than one player per team) ? - TeamMode := true; - for I := 0 to Teams.NumTeams-1 do - TeamMode := TeamMode and (Teams.Teaminfo[I].NumPlayers > 1); - - //Set Rounds - SetLength(Rounds, NumRounds); - - for I := 0 to High(Rounds) do - begin //Set plugins - if (aiRounds[I] = -1) then - Rounds[I].Modi := GetRandomPlugin(TeamMode) - else if (aiRounds[I] >= 0) and (aiRounds[I] <= High(Modis)) and (TeamMode or ((Modis[aiRounds[I]].Info.LoadingSettings and MLS_TeamOnly) = 0)) then - Rounds[I].Modi := aiRounds[I] - else - Rounds[I].Modi := StandardModus; - - Rounds[I].Winner := High(byte); //Set winner to not played - end; - - CurRound := High(byte); //Set CurRound to not defined + //Set current round to 1 + CurRound := 255; - //Return true and set party mode - bPartyMode := true; - Result := 1; + PlayersPlay := Teams.NumTeams; - except - Core.ReportError(integer(PChar('Can''t start party mode.')), PChar('TPartySession')); + //Get team-mode and set joker, also set TimesPlayed + TeamMode := true; + for I := 0 to Teams.NumTeams - 1 do + begin + if Teams.Teaminfo[I].NumPlayers < 2 then + begin + TeamMode := false; end; + //Set player attributes + for J := 0 to Teams.TeamInfo[I].NumPlayers-1 do + begin + Teams.TeamInfo[I].Playerinfo[J].TimesPlayed := 0; + end; + Teams.Teaminfo[I].Joker := Round(NumRounds * 0.7); + Teams.Teaminfo[I].Score := 0; end; -end; -//---------- -// Returns pointer to Cur. ModiInfoEx (to use with sing screen) -//---------- -function TPartySession.GetCurModi(wParam: TwParam; lParam: TlParam): integer; -begin - if (bPartyMode) and (CurRound <= High(Rounds)) then - begin //If PartyMode is enabled: - //Return the Plugin of the Cur Round - Result := integer(@Modis[Rounds[CurRound].Modi]); - end - else - begin //Return standard modus - Result := integer(@Modis[StandardModus]); + //Fill plugin array + SetLength(Plugins, 0); + for I := 0 to high(DLLMan.Plugins) do + begin + if TeamMode or (not DLLMan.Plugins[I].TeamModeOnly) then + begin + //Add only those plugins playable with current PlayerConfiguration + Len := Length(Plugins); + SetLength(Plugins, Len + 1); + Plugins[Len].ID := I; + Plugins[Len].TimesPlayed := 0; + end; end; -end; -//---------- -// Stops party mode. Returns 1 if party mode was enabled before and -1 if change was not possible -//---------- -function TPartySession.StopParty(wParam: TwParam; lParam: TlParam): integer; -begin - Result := -1; - if (bPartyMode) then + //Set rounds + if (Length(Plugins) >= 1) then begin - // to-do : Whitü: Check here if sing screen is not shown atm. - bPartyMode := false; - Result := 1; + SetLength (Rounds, NumRounds); + for I := 0 to NumRounds - 1 do + begin + PartySession.Rounds[I].Plugin := GetRandomPlugin(Plugins); + PartySession.Rounds[I].Winner := 255; + end; end else - Result := 0; + SetLength (Rounds, 0); end; -//---------- -//GetRandomPlayer - gives back a random player to play next round -//---------- +{** + * Returns a random player to play next round + *} function TPartySession.GetRandomPlayer(Team: byte): byte; var - I, R: integer; - lowestTP: byte; + I, R: integer; + LowestTP: byte; NumPwithLTP: byte; begin - LowestTP := high(byte); + LowestTP := high(byte); NumPwithLTP := 0; - Result := 0; + Result := 0; //Search for players that have not often played yet - for I := 0 to Teams.Teaminfo[Team].NumPlayers-1 do + for I := 0 to Teams.Teaminfo[Team].NumPlayers - 1 do begin if (Teams.Teaminfo[Team].Playerinfo[I].TimesPlayed < lowestTP) then begin @@ -369,11 +225,11 @@ begin end; end; - //Create random no + //Create random number R := Random(NumPwithLTP); //Search for random player - for I := 0 to Teams.Teaminfo[Team].NumPlayers-1 do + for I := 0 to Teams.Teaminfo[Team].NumPlayers - 1 do begin if Teams.Teaminfo[Team].Playerinfo[I].TimesPlayed = lowestTP then begin @@ -389,212 +245,93 @@ begin end; end; -//---------- -// NextRound - Increases CurRound by 1; Returns num of round or -1 if last round is already played -//---------- -function TPartySession.NextRound(wParam: TwParam; lParam: TlParam): integer; +{** + * Prepares ScreenSingModi for next round and loads plugin + *} +procedure TPartySession.StartRound; var I: integer; begin if ((CurRound < high(Rounds)) or (CurRound = high(CurRound))) then - begin //everythings OK! -> Start the Round, maaaaan + begin + //Increase Current Round Inc(CurRound); - //Set Players to play this Round - for I := 0 to Teams.NumTeams-1 do - Teams.Teaminfo[I].CurPlayer := GetRandomPlayer(I); - - // FIXME: return a valid result - Result := 0; - end - else - Result := -1; -end; - -//---------- -//IsWinner - returns true if the players bit is set in the winner byte -//---------- -function TPartySession.IsWinner(Player, Winner: byte): boolean; -var - Bit: byte; -begin - Bit := 1 shl Player; - - Result := ((Winner and Bit) = Bit); -end; - -//---------- -//GenScores - inc scores for cur. round -//---------- -procedure TPartySession.GenScores; -var - I: byte; -begin - for I := 0 to Teams.NumTeams-1 do - begin - if isWinner(I, Rounds[CurRound].Winner) then - Inc(Teams.Teaminfo[I].Score); - end; -end; + Rounds[CurRound].Winner := 255; + DllMan.LoadPlugin(Rounds[CurRound].Plugin); -//---------- -// CallModiInit - calls CurModis Init Proc. If an error occurs, returns nonzero. In this case a new plugin was selected. Please renew loading -//---------- -function TPartySession.CallModiInit(wParam: TwParam; lParam: TlParam): integer; -begin - if (not bPartyMode) then - begin //Set rounds if not in party mode - SetLength(Rounds, 1); - Rounds[0].Modi := StandardModus; - Rounds[0].Winner := High(byte); - CurRound := 0; - end; + //Select Players + for I := 0 to Teams.NumTeams - 1 do + Teams.Teaminfo[I].CurPlayer := GetRandomPlayer(I); - try - //Core. - except - on E : Exception do - begin - Core.ReportError(integer(PChar('Error starting modus: ' + Modis[Rounds[CurRound].Modi].Info.Name + ' ErrorStr: ' + E.Message)), PChar('TPartySession')); - if (Rounds[CurRound].Modi = StandardModus) then - begin - Core.ReportError(integer(PChar('Can''t start standard modus, will exit now!')), PChar('TPartySession')); - Halt; - end - else //Select standard modus - begin - Rounds[CurRound].Modi := StandardModus - end; - end; + //Set ScreenSingModie Variables + ScreenSingModi.TeamInfo := Teams; end; - - // FIXME: return a valid result - Result := 0; end; //---------- -// CallModiDeInit - calls DeInitProc and ends the round +//EndRound - Get Winner from ScreenSingModi and Save Data to RoundArray //---------- -function TPartySession.CallModiDeInit(wParam: TwParam; lParam: TlParam): integer; +procedure TPartySession.EndRound; var - I: integer; - MaxScore: word; + I: Integer; begin - if (bPartyMode) then - begin - //Get Winner Byte! - if (@Modis[Rounds[CurRound].Modi].Info.ModiDeInit <> nil) then //get winners from plugin - Rounds[CurRound].Winner := Modis[Rounds[CurRound].Modi].Info.ModiDeInit(Modis[Rounds[CurRound].Modi].Info.ID) - else - begin //Create winners by score :/ - Rounds[CurRound].Winner := 0; - MaxScore := 0; - for I := 0 to Teams.NumTeams-1 do - begin - // to-do : recode percentage stuff - //PlayerInfo.Playerinfo[I].Percentage := PlayerInfo.Playerinfo[I].Score div 9999; - if (Player[I].ScoreTotalInt > MaxScore) then - begin - MaxScore := Player[I].ScoreTotalInt; - Rounds[CurRound].Winner := 1 shl I; - end - else if (Player[I].ScoreTotalInt = MaxScore) and (Player[I].ScoreTotalInt <> 0) then - begin - Rounds[CurRound].Winner := Rounds[CurRound].Winner or (1 shl I); - end; - end; - - - //When nobody has points -> everybody looses - if (MaxScore = 0) then - Rounds[CurRound].Winner := 0; - - end; + //Copy Winner + Rounds[CurRound].Winner := ScreenSingModi.Winner; + //Set Scores + GenScores; - //Generate the scores - GenScores; + //Increase TimesPlayed 4 all Players + For I := 0 to Teams.NumTeams-1 do + Inc(Teams.Teaminfo[I].Playerinfo[Teams.Teaminfo[I].CurPlayer].TimesPlayed); - //Inc players TimesPlayed - if ((Modis[Rounds[CurRound-1].Modi].Info.LoadingSettings and MLS_IncTP) = MLS_IncTP) then - begin - for I := 0 to Teams.NumTeams-1 do - Inc(Teams.TeamInfo[I].Playerinfo[Teams.TeamInfo[I].CurPlayer].TimesPlayed); - end; - end - else if (@Modis[Rounds[CurRound].Modi].Info.ModiDeInit <> nil) then - Modis[Rounds[CurRound].Modi].Info.ModiDeInit(Modis[Rounds[CurRound].Modi].Info.ID); - - // FIXME: return a valid result - Result := 0; end; //---------- -// GetTeamInfo - writes TTeamInfo record to pointer at lParam. Returns zero on success +//IsWinner - returns true if the player's bit is set in the winner byte //---------- -function TPartySession.GetTeamInfo(wParam: TwParam; pTeamInfo: TlParam): integer; +function TPartySession.IsWinner(Player, Winner: byte): boolean; var - Info: ^TTeamInfo; + Mask: byte; begin - Result := -1; - Info := pTeamInfo; - if (Info <> nil) then - begin - try - // to - do : Check Delphi memory management in this case - //Not sure if i had to copy PChars to a new address or if delphi manages this o0 - Info^ := Teams; - Result := 0; - except - Result := -2; - end; - end; + Mask := 1 shl Player; + Result := (Winner and Mask) <> 0; end; //---------- -// SetTeamInfo - read TTeamInfo record from pointer at lParam. Returns zero on success +//GenScores - increase scores for current round //---------- -function TPartySession.SetTeamInfo(wParam: TwParam; pTeamInfo: TlParam): integer; +procedure TPartySession.GenScores; var - TeamInfobackup: TTeamInfo; - Info: ^TTeamInfo; + I: byte; begin - Result := -1; - Info := pTeamInfo; - if (Info <> nil) then + for I := 0 to Teams.NumTeams - 1 do begin - try - TeamInfoBackup := Teams; - // to - do : Check Delphi memory management in this case - //Not sure if i had to copy PChars to a new address or if delphi manages this o0 - Teams := Info^; - Result := 0; - except - Teams := TeamInfoBackup; - Result := -2; - end; + if isWinner(I, Rounds[CurRound].Winner) then + Inc(Teams.Teaminfo[I].Score); end; end; //---------- -// GetTeamOrder - returns team order. Structure: Bits 1..3: Team at place1; Bits 4..6: Team at place2 ... +//GetTeamOrder - returns the placement of each Team [First Position of Array is Teamnum of first placed Team, ...] //---------- -function TPartySession.GetTeamOrder(wParam: TwParam; lParam: TlParam): integer; +function TPartySession.GetTeamOrder: TeamOrderArray; var - I, J: integer; - ATeams: array [0..5] of TeamOrderEntry; + I, J: integer; + ATeams: array [0..5] of TeamOrderEntry; TempTeam: TeamOrderEntry; begin - // to-do : PartyMode: Write this in another way, so that teams with the same score get the same place + // TODO: PartyMode: Write this in another way, so that teams with the same score get the same place //Fill Team array - for I := 0 to Teams.NumTeams-1 do + for I := 0 to Teams.NumTeams - 1 do begin ATeams[I].Teamnum := I; ATeams[I].Score := Teams.Teaminfo[I].Score; end; //Sort teams - for J := 0 to Teams.NumTeams-1 do - for I := 1 to Teams.NumTeams-1 do + for J := 0 to Teams.NumTeams - 1 do + for I := 1 to Teams.NumTeams - 1 do if ATeams[I].Score > ATeams[I-1].Score then begin TempTeam := ATeams[I-1]; @@ -603,63 +340,44 @@ begin end; //Copy to Result - Result := 0; for I := 0 to Teams.NumTeams-1 do - Result := Result or (ATeams[I].TeamNum Shl I*3); + Result[I] := ATeams[I].TeamNum; end; //---------- -// GetWinnerString - wParam is Roundnum. If (pointer = nil) then return length of the string. Otherwise write the string to address at lParam +//GetWinnerString - Get string with WinnerTeam Name, when there is more than one Winner than Connect with and or , //---------- -function TPartySession.GetWinnerString(wParam: TwParam; lParam: TlParam): integer; +function TPartySession.GetWinnerString(Round: byte): string; var Winners: array of UTF8String; - I: integer; - ResultStr: String; - S: ^String; + I: integer; begin - ResultStr := Language.Translate('PARTY_NOBODY'); + Result := Language.Translate('PARTY_NOBODY'); + + if (Round > High(Rounds)) then + exit; - if (wParam <= High(Rounds)) then + if (Rounds[Round].Winner = 0) then begin - if (Rounds[wParam].Winner <> 0) then - begin - if (Rounds[wParam].Winner = 255) then - begin - ResultStr := Language.Translate('PARTY_NOTPLAYEDYET'); - end - else - begin - SetLength(Winners, 0); - for I := 0 to Teams.NumTeams-1 do - begin - if isWinner(I, Rounds[wParam].Winner) then - begin - SetLength(Winners, Length(Winners) + 1); - Winners[high(Winners)] := Teams.TeamInfo[I].Name; - end; - end; - ResultStr := Language.Implode(Winners); - end; - end; + exit; end; - //Now return what we have got - if (lParam = nil) then - begin //Return string length - Result := Length(ResultStr); - end - else - begin //Return string - try - S := lParam; - S^ := ResultStr; - Result := 0; - except - Result := -1; + if (Rounds[Round].Winner = 255) then + begin + Result := Language.Translate('PARTY_NOTPLAYEDYET'); + exit; + end; + SetLength(Winners, 0); + for I := 0 to Teams.NumTeams - 1 do + begin + if isWinner(I, Rounds[Round].Winner) then + begin + SetLength(Winners, Length(Winners) + 1); + Winners[high(Winners)] := Teams.TeamInfo[I].Name; end; end; + Result := Language.Implode(Winners); end; end. diff --git a/unicode/src/base/UPlatform.pas b/unicode/src/base/UPlatform.pas index e4cb6f0c..6f13481c 100644 --- a/unicode/src/base/UPlatform.pas +++ b/unicode/src/base/UPlatform.pas @@ -43,9 +43,9 @@ uses type TDirectoryEntry = record - Name : WideString; - IsDirectory : boolean; - IsFile : boolean; + Name: WideString; + IsDirectory: boolean; + IsFile: boolean; end; TDirectoryEntryArray = array of TDirectoryEntry; @@ -54,12 +54,12 @@ type function GetExecutionDir(): string; procedure Init; virtual; function DirectoryFindFiles(Dir, Filter: WideString; ReturnAllSubDirs: boolean): TDirectoryEntryArray; virtual; abstract; - function TerminateIfAlreadyRunning(var WndTitle : string): boolean; virtual; + function TerminateIfAlreadyRunning(var WndTitle: string): boolean; virtual; function FindSongFile(Dir, Mask: WideString): WideString; virtual; procedure Halt; virtual; - function GetLogPath : WideString; virtual; abstract; - function GetGameSharedPath : WideString; virtual; abstract; - function GetGameUserPath : WideString; virtual; abstract; + function GetLogPath: WideString; virtual; abstract; + function GetGameSharedPath: WideString; virtual; abstract; + function GetGameUserPath: WideString; virtual; abstract; function CopyFile(const Source, Target: WideString; FailIfExists: boolean): boolean; virtual; end; @@ -79,13 +79,13 @@ uses ULog; -// I have modified it to use the Platform_singleton in this location ( in the implementaiton ) +// I modified it to use the Platform_singleton in this location (in the implementation) // so that this variable can NOT be overwritten from anywhere else in the application. // the accessor function platform, emulates all previous calls to work the same way. var - Platform_singleton : TPlatform; + Platform_singleton: TPlatform; -function Platform : TPlatform; +function Platform: TPlatform; begin Result := Platform_singleton; end; @@ -117,7 +117,7 @@ end; (** * Default TerminateIfAlreadyRunning() implementation *) -function TPlatform.TerminateIfAlreadyRunning(var WndTitle : string): Boolean; +function TPlatform.TerminateIfAlreadyRunning(var WndTitle: string): boolean; begin Result := false; end; @@ -143,7 +143,7 @@ const var SourceFile, TargetFile: TFileStream; FileCopyBuffer: array [0..COPY_BUFFER_SIZE-1] of byte; // temporary copy-buffer. - NumberOfBytes: integer; // number of bytes read from SourceFile + NumberOfBytes: integer; // number of bytes read from SourceFile begin Result := false; SourceFile := nil; diff --git a/unicode/src/base/UPluginInterface.pas b/unicode/src/base/UPluginInterface.pas deleted file mode 100644 index f299796f..00000000 --- a/unicode/src/base/UPluginInterface.pas +++ /dev/null @@ -1,186 +0,0 @@ -{* UltraStar Deluxe - Karaoke Game - * - * UltraStar Deluxe is the legal property of its developers, whose names - * are too numerous to list here. Please refer to the COPYRIGHT - * file distributed with this source distribution. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - * $URL$ - * $Id$ - *} - -unit uPluginInterface; -{********************* - uPluginInterface - Unit fills a TPluginInterface structure with method pointers - Unit contains all functions called directly by plugins -*********************} - -interface - -{$IFDEF FPC} - {$MODE Delphi} -{$ENDIF} - -{$I switches.inc} - -uses - uPluginDefs; - -//--------------- -// Methods for Plugin -//--------------- - {******** Hook specific Methods ********} - {Function Creates a new Hookable Event and Returns the Handle - or 0 on Failure. (Name already exists)} - Function CreateHookableEvent (EventName: PChar): THandle; stdcall; - - {Function Destroys an Event and Unhooks all Hooks to this Event. - 0 on success, not 0 on Failure} - Function DestroyHookableEvent (hEvent: THandle): integer; stdcall; - - {Function start calling the Hook Chain - 0 if Chain is called until the End, -1 if Event Handle is not valid - otherwise Return Value of the Hook that breaks the Chain} - Function NotivyEventHooks (hEvent: THandle; wParam: TwParam; lParam: TlParam): integer; stdcall; - - {Function Hooks an Event by Name. - Returns Hook Handle on Success, otherwise 0} - Function HookEvent (EventName: PChar; HookProc: TUS_Hook): THandle; stdcall; - - {Function Removes the Hook from the Chain - Returns 0 on Success} - Function UnHookEvent (hHook: THandle): Integer; stdcall; - - {Function Returns Non Zero if a Event with the given Name Exists, - otherwise 0} - Function EventExists (EventName: PChar): Integer; stdcall; - - {******** Service specific Methods ********} - {Function Creates a new Service and Returns the Services Handle - or 0 on Failure. (Name already exists)} - Function CreateService (ServiceName: PChar; ServiceProc: TUS_Service): THandle; stdcall; - - {Function Destroys a Service. - 0 on success, not 0 on Failure} - Function DestroyService (hService: THandle): integer; stdcall; - - {Function Calls a Services Proc - Returns Services Return Value or SERVICE_NOT_FOUND on Failure} - Function CallService (ServiceName: PChar; wParam: TwParam; lParam: TlParam): integer; stdcall; - - {Function Returns Non Zero if a Service with the given Name Exists, - otherwise 0} - Function ServiceExists (ServiceName: PChar): Integer; stdcall; - -implementation -uses UCore; - -{******** Hook specific Methods ********} -//--------------- -// Function Creates a new Hookable Event and Returns the Handle -// or 0 on Failure. (Name already exists) -//--------------- -Function CreateHookableEvent (EventName: PChar): THandle; stdcall; -begin - Result := Core.Hooks.AddEvent(EventName); -end; - -//--------------- -// Function Destroys an Event and Unhooks all Hooks to this Event. -// 0 on success, not 0 on Failure -//--------------- -Function DestroyHookableEvent (hEvent: THandle): integer; stdcall; -begin - Result := Core.Hooks.DelEvent(hEvent); -end; - -//--------------- -// Function start calling the Hook Chain -// 0 if Chain is called until the End, -1 if Event Handle is not valid -// otherwise Return Value of the Hook that breaks the Chain -//--------------- -Function NotivyEventHooks (hEvent: THandle; wParam: TwParam; lParam: TlParam): integer; stdcall; -begin - Result := Core.Hooks.CallEventChain(hEvent, wParam, lParam); -end; - -//--------------- -// Function Hooks an Event by Name. -// Returns Hook Handle on Success, otherwise 0 -//--------------- -Function HookEvent (EventName: PChar; HookProc: TUS_Hook): THandle; stdcall; -begin - Result := Core.Hooks.AddSubscriber(EventName, HookProc); -end; - -//--------------- -// Function Removes the Hook from the Chain -// Returns 0 on Success -//--------------- -Function UnHookEvent (hHook: THandle): Integer; stdcall; -begin - Result := Core.Hooks.DelSubscriber(hHook); -end; - -//--------------- -// Function Returns Non Zero if a Event with the given Name Exists, -// otherwise 0 -//--------------- -Function EventExists (EventName: PChar): Integer; stdcall; -begin - Result := Core.Hooks.EventExists(EventName); -end; - - {******** Service specific Methods ********} -//--------------- -// Function Creates a new Service and Returns the Services Handle -// or 0 on Failure. (Name already exists) -//--------------- -Function CreateService (ServiceName: PChar; ServiceProc: TUS_Service): THandle; stdcall; -begin - Result := Core.Services.AddService(ServiceName, ServiceProc); -end; - -//--------------- -// Function Destroys a Service. -// 0 on success, not 0 on Failure -//--------------- -Function DestroyService (hService: THandle): integer; stdcall; -begin - Result := Core.Services.DelService(hService); -end; - -//--------------- -// Function Calls a Services Proc -// Returns Services Return Value or SERVICE_NOT_FOUND on Failure -//--------------- -Function CallService (ServiceName: PChar; wParam: TwParam; lParam: TlParam): integer; stdcall; -begin - Result := Core.Services.CallService(ServiceName, wParam, lParam); -end; - -//--------------- -// Function Returns Non Zero if a Service with the given Name Exists, -// otherwise 0 -//--------------- -Function ServiceExists (ServiceName: PChar): Integer; stdcall; -begin - Result := Core.Services.ServiceExists(ServiceName); -end; - -end. diff --git a/unicode/src/base/UPluginLoader.pas b/unicode/src/base/UPluginLoader.pas deleted file mode 100644 index 8836cb78..00000000 --- a/unicode/src/base/UPluginLoader.pas +++ /dev/null @@ -1,794 +0,0 @@ -{* UltraStar Deluxe - Karaoke Game - * - * UltraStar Deluxe is the legal property of its developers, whose names - * are too numerous to list here. Please refer to the COPYRIGHT - * file distributed with this source distribution. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - * $URL: https://ultrastardx.svn.sourceforge.net/svnroot/ultrastardx/trunk/src/base/uPluginLoader.pas $ - * $Id: uPluginLoader.pas 1403 2008-09-23 21:17:22Z k-m_schindler $ - *} - -unit UPluginLoader; -{********************* - UPluginLoader - Unit contains two classes - TPluginLoader: Class searching for and loading the plugins - TtehPlugins: Class representing the plugins in modules chain -*********************} - -interface - -{$IFDEF FPC} - {$MODE Delphi} -{$ENDIF} - -{$I switches.inc} - -uses - UPluginDefs, - UCoreModule, - UPath; - -type - TPluginListItem = record - Info: TUS_PluginInfo; - State: byte; // State of this plugin: 0 - undefined; 1 - loaded; 2 - inited / running; 4 - unloaded; 254 - loading aborted by plugin; 255 - unloaded because of error - Path: string; // path to this plugin - NeedsDeInit: boolean; // if this is inited correctly this should be true - hLib: THandle; // handle of loaded libary - Procs: record // procs offered by plugin. Don't call this directly use wrappers of TPluginLoader - Load: Func_Load; - Init: Func_Init; - DeInit: Proc_DeInit; - end; - end; - {********************* - TPluginLoader - Class searches for plugins and manages loading and unloading - *********************} - PPluginLoader = ^TPluginLoader; - TPluginLoader = class (TCoreModule) - private - LoadingProcessFinished: boolean; - sUnloadPlugin: THandle; - sLoadPlugin: THandle; - sGetPluginInfo: THandle; - sGetPluginState: THandle; - - procedure FreePlugin(Index: integer); - public - PluginInterface: TUS_PluginInterface; - Plugins: array of TPluginListItem; - - // TCoreModule methods to inherit - constructor Create; override; - procedure Info(const pInfo: PModuleInfo); override; - function Load: boolean; override; - function Init: boolean; override; - procedure DeInit; override; - Destructor Destroy; override; - - // New methods - procedure BrowseDir(Path: string); // browses the path at _Path_ for plugins - function PluginExists(Name: string): integer; // if plugin exists: Index of plugin, else -1 - procedure AddPlugin(Filename: string); // adds plugin to the array - - function CallLoad(Index: integer): integer; - function CallInit(Index: integer): integer; - procedure CallDeInit(Index: integer); - - //Services offered - function LoadPlugin(wParam: TwParam; lParam: TlParam): integer; //wParam PChar(PluginName/PluginPath) | lParam (if wParam = nil) ID of the Plugin - function UnloadPlugin(wParam: TwParam; lParam: TlParam): integer; //wParam PChar(PluginName/PluginPath) | lParam (if wParam = nil) ID of the Plugin - function GetPluginInfo(wParam: TwParam; lParam: TlParam): integer; //If wParam = -1 then (If lParam = nil then get length of Moduleinfo Array. If lparam <> nil then write array of TUS_PluginInfo to address at lparam) else (Get PluginInfo of Plugin with Index(wParam) to Address at lParam) - function GetPluginState(wParam: TwParam; lParam: TlParam): integer; //If wParam = -1 then (If lParam = nil then get length of Moduleinfo Array. If lparam <> nil then write array of TUS_PluginInfo to address at lparam) else (Return PluginInfo of Plugin with Index(wParam)) - - end; - - {********************* - TtehPlugins - Class represents the plugins in module chain. - It calls the plugins procs and funcs - *********************} - TtehPlugins = class (TCoreModule) - private - PluginLoader: PPluginLoader; - public - // TCoreModule methods to inherit - constructor Create; override; - - procedure Info(const pInfo: PModuleInfo); override; - function Load: boolean; override; - function Init: boolean; override; - procedure DeInit; override; - end; - -const -{$IF Defined(MSWINDOWS)} - PluginFileExtension = '.dll'; -{$ELSEIF Defined(DARWIN)} - PluginFileExtension = '.dylib'; -{$ELSEIF Defined(UNIX)} - PluginFileExtension = '.so'; -{$IFEND} - -implementation - -uses - UCore, - UPluginInterface, -{$IFDEF MSWINDOWS} - windows, -{$ELSE} - dynlibs, -{$ENDIF} - UMain, - SysUtils; - -{********************* - TPluginLoader - Implementation -*********************} - -//------------- -// function that gives some infos about the module to the core -//------------- -procedure TPluginLoader.Info(const pInfo: PModuleInfo); -begin - pInfo^.Name := 'TPluginLoader'; - pInfo^.Version := MakeVersion(1,0,0,chr(0)); - pInfo^.Description := 'Searches for plugins, loads and unloads them'; -end; - -//------------- -// Just the constructor -//------------- -constructor TPluginLoader.Create; -begin - inherited; - - // Init PluginInterface - // Using methods from UPluginInterface - PluginInterface.CreateHookableEvent := CreateHookableEvent; - PluginInterface.DestroyHookableEvent := DestroyHookableEvent; - PluginInterface.NotivyEventHooks := NotivyEventHooks; - PluginInterface.HookEvent := HookEvent; - PluginInterface.UnHookEvent := UnHookEvent; - PluginInterface.EventExists := EventExists; - - PluginInterface.CreateService := @CreateService; - PluginInterface.DestroyService := DestroyService; - PluginInterface.CallService := CallService; - PluginInterface.ServiceExists := ServiceExists; - - // UnSet private var - LoadingProcessFinished := false; -end; - -//------------- -// Is called on loading. -// In this method only events and services should be created -// to offer them to other modules or plugins during the init process -// if false is returned this will cause a forced exit -//------------- -function TPluginLoader.Load: boolean; -begin - Result := true; - - try - // Start searching for plugins - BrowseDir(PluginPath); - except - Result := false; - Core.ReportError(integer(PChar('Error browsing and loading.')), PChar('TPluginLoader')); - end; -end; - -//------------- -// Is called on init process -// In this method you can hook some events and create + init -// your classes, variables etc. -// If false is returned this will cause a forced exit -//------------- -function TPluginLoader.Init: boolean; -begin - // Just set private var to true. - LoadingProcessFinished := true; - Result := true; -end; - -//------------- -// Is called if this module has been inited and there is a exit. -// Deinit is in backwards initing order -//------------- -procedure TPluginLoader.DeInit; -var - I: integer; -begin - // Force deinit - // if some plugins aren't deinited for some reason o0 - for I := 0 to High(Plugins) do - begin - if (Plugins[I].State < 4) then - FreePlugin(I); - end; - - // Nothing to do here. Core will remove the hooks -end; - -//------------- -// Is called if this module will be unloaded and has been created -// Should be used to free memory -//------------- -Destructor TPluginLoader.Destroy; -begin - // Just save some memory if it wasn't done now.. - SetLength(Plugins, 0); - inherited; -end; - -//-------------- -// Browses the path at _Path_ for plugins -//-------------- -procedure TPluginLoader.BrowseDir(Path: string); -var - SR: TSearchRec; -begin - // Search for other dirs to browse - if FindFirst(Path + '*', faDirectory, SR) = 0 then begin - repeat - if (SR.Name <> '.') and (SR.Name <> '..') then - BrowseDir(Path + Sr.Name + PathDelim); - until FindNext(SR) <> 0; - end; - FindClose(SR); - - // Search for plugins at path - if FindFirst(Path + '*' + PluginFileExtension, 0, SR) = 0 then - begin - repeat - AddPlugin(Path + SR.Name); - until FindNext(SR) <> 0; - end; - FindClose(SR); -end; - -//-------------- -// If plugin exists: Index of plugin, else -1 -//-------------- -function TPluginLoader.PluginExists(Name: string): integer; -var - I: integer; -begin - Result := -1; - - if (Length(Name) <= 32 { =>Length(TUS_PluginInfo.Name)}) then - begin - for I := 0 to High(Plugins) do - if (Plugins[I].Info.Name = Name) then - begin //Found the Plugin - Result := I; - Break; - end; - end; -end; - -//-------------- -// Adds plugin to the array -//-------------- -procedure TPluginLoader.AddPlugin(Filename: string); -var - hLib: THandle; - PInfo: Proc_PluginInfo; - Info: TUS_PluginInfo; - PluginID: integer; -begin - if (FileExists(Filename)) then - begin //Load Libary - hLib := LoadLibrary(PChar(Filename)); - if (hLib <> 0) then - begin // Try to get address of the info proc - PInfo := GetProcAddress (hLib, PChar('USPlugin_Info')); - if (@PInfo <> nil) then - begin - Info.cbSize := SizeOf(TUS_PluginInfo); - - try // Call info proc - PInfo(@Info); - except - Info.Name := ''; - Core.ReportError(integer(PChar('Error getting plugin info: ' + Filename)), PChar('TPluginLoader')); - end; - - // Is name set ? - if (Trim(Info.Name) <> '') then - begin - PluginID := PluginExists(Info.Name); - - if (PluginID > 0) and (Plugins[PluginID].State >=4) then - PluginID := -1; - - if (PluginID = -1) then - begin - // Add new item to array - PluginID := Length(Plugins); - SetLength(Plugins, PluginID + 1); - - // Fill with info: - Plugins[PluginID].Info := Info; - Plugins[PluginID].State := 0; - Plugins[PluginID].Path := Filename; - Plugins[PluginID].NeedsDeInit := false; - Plugins[PluginID].hLib := hLib; - - // Try to get procs - Plugins[PluginID].Procs.Load := GetProcAddress (hLib, PChar('USPlugin_Load')); - Plugins[PluginID].Procs.Init := GetProcAddress (hLib, PChar('USPlugin_Init')); - Plugins[PluginID].Procs.DeInit := GetProcAddress (hLib, PChar('USPlugin_DeInit')); - - if (@Plugins[PluginID].Procs.Load = nil) or (@Plugins[PluginID].Procs.Init = nil) or (@Plugins[PluginID].Procs.DeInit = nil) then - begin - Plugins[PluginID].State := 255; - FreeLibrary(hLib); - Core.ReportError(integer(PChar('Can''t get plugin procs from libary: "' + Info.Name + '" ' + Filename)), PChar('TPluginLoader')); - end; - - // Emulate loading process if this plugin is loaded too late - if (LoadingProcessFinished) then - begin - CallLoad(PluginID); - CallInit(PluginID); - end; - end - else if (LoadingProcessFinished = false) then - begin - if (Plugins[PluginID].Info.Version < Info.Version) then - begin // Found newer version of this plugin - Core.ReportDebug(integer(PChar('Found a newer version of plugin: ' + string(Info.Name))), PChar('TPluginLoader')); - - // Unload old plugin - UnloadPlugin(PluginID, nil); - - // Fill with new info - Plugins[PluginID].Info := Info; - Plugins[PluginID].State := 0; - Plugins[PluginID].Path := Filename; - Plugins[PluginID].NeedsDeInit := false; - Plugins[PluginID].hLib := hLib; - - // Try to get procs - Plugins[PluginID].Procs.Load := GetProcAddress (hLib, PChar('USPlugin_Load')); - Plugins[PluginID].Procs.Init := GetProcAddress (hLib, PChar('USPlugin_Init')); - Plugins[PluginID].Procs.DeInit := GetProcAddress (hLib, PChar('USPlugin_DeInit')); - - if (@Plugins[PluginID].Procs.Load = nil) or (@Plugins[PluginID].Procs.Init = nil) or (@Plugins[PluginID].Procs.DeInit = nil) then - begin - FreeLibrary(hLib); - Plugins[PluginID].State := 255; - Core.ReportError(integer(PChar('Can''t get plugin procs from libary: "' + Info.Name + '" ' + Filename)), PChar('TPluginLoader')); - end; - end - else - begin // Newer Version already loaded - FreeLibrary(hLib); - end; - end - else - begin - FreeLibrary(hLib); - Core.ReportError(integer(PChar('Plugin with this name already exists: ' + string(Info.Name))), PChar('TPluginLoader')); - end; - end - else - begin - FreeLibrary(hLib); - Core.ReportError(integer(PChar('No name reported: ' + Filename)), PChar('TPluginLoader')); - end; - end - else - begin - FreeLibrary(hLib); - Core.ReportError(integer(PChar('Can''t find info procedure: ' + Filename)), PChar('TPluginLoader')); - end; - end - else - Core.ReportError(integer(PChar('Can''t load plugin libary: ' + Filename)), PChar('TPluginLoader')); - end; -end; - -//-------------- -// Calls load func of plugin with the given index -//-------------- -function TPluginLoader.CallLoad(Index: integer): integer; -begin - Result := -2; - if(Index < Length(Plugins)) then - begin - if (@Plugins[Index].Procs.Load <> nil) and (Plugins[Index].State = 0) then - begin - try - Result := Plugins[Index].Procs.Load(@PluginInterface); - except - Result := -3; - end; - - if (Result = 0) then - Plugins[Index].State := 1 - else - begin - FreePlugin(Index); - Plugins[Index].State := 255; - Core.ReportError(integer(PChar('Error calling load function from plugin: ' + string(Plugins[Index].Info.Name))), PChar('TPluginLoader')); - end; - end; - end; -end; - -//-------------- -// Calls init func of plugin with the given index -//-------------- -function TPluginLoader.CallInit(Index: integer): integer; -begin - Result := -2; - if(Index < Length(Plugins)) then - begin - if (@Plugins[Index].Procs.Init <> nil) and (Plugins[Index].State = 1) then - begin - try - Result := Plugins[Index].Procs.Init(@PluginInterface); - except - Result := -3; - end; - - if (Result = 0) then - begin - Plugins[Index].State := 2; - Plugins[Index].NeedsDeInit := true; - end - else - begin - FreePlugin(Index); - Plugins[Index].State := 255; - Core.ReportError(integer(PChar('Error calling init function from plugin: ' + string(Plugins[Index].Info.Name))), PChar('TPluginLoader')); - end; - end; - end; -end; - -//-------------- -// Calls deinit proc of plugin with the given index -//-------------- -procedure TPluginLoader.CallDeInit(Index: integer); -begin - if(Index < Length(Plugins)) then - begin - if (Plugins[Index].State < 4) then - begin - if (@Plugins[Index].Procs.DeInit <> nil) and (Plugins[Index].NeedsDeInit) then - try - Plugins[Index].Procs.DeInit(@PluginInterface); - except - - end; - - // Don't forget to remove services and subscriptions by this plugin - Core.Hooks.DelbyOwner(-1 - Index); - - FreePlugin(Index); - end; - end; -end; - -//-------------- -// Frees all plugin sources (procs and handles) - helper for deiniting functions -//-------------- -procedure TPluginLoader.FreePlugin(Index: integer); -begin - Plugins[Index].State := 4; - Plugins[Index].Procs.Load := nil; - Plugins[Index].Procs.Init := nil; - Plugins[Index].Procs.DeInit := nil; - - if (Plugins[Index].hLib <> 0) then - FreeLibrary(Plugins[Index].hLib); -end; - -//-------------- -// wParam PChar(PluginName/PluginPath) | wParam (if lParam = nil) ID of the plugin -//-------------- -function TPluginLoader.LoadPlugin(wParam: TwParam; lParam: TlParam): integer; -var - Index: integer; - sFile: string; -begin - Result := -1; - sFile := ''; - // lParam is ID - if (lParam = nil) then - begin - Index := wParam; - end - else - begin //lParam is PChar - try - sFile := string(PChar(lParam)); - Index := PluginExists(sFile); - if (Index < 0) and FileExists(sFile) then - begin // Is filename - AddPlugin(sFile); - Result := Plugins[High(Plugins)].State; - end; - except - Index := -2; - end; - end; - - if (Index >= 0) and (Index < Length(Plugins)) then - begin - AddPlugin(Plugins[Index].Path); - Result := Plugins[Index].State; - end; -end; - -//-------------- -// wParam PChar(PluginName/PluginPath) | wParam (if lParam = nil) ID of the plugin -//-------------- -function TPluginLoader.UnloadPlugin(wParam: TwParam; lParam: TlParam): integer; -var - Index: integer; - sName: string; -begin - Result := -1; - // lParam is ID - if (lParam = nil) then - begin - Index := wParam; - end - else - begin // wParam is PChar - try - sName := string(PChar(lParam)); - Index := PluginExists(sName); - except - Index := -2; - end; - end; - - if (Index >= 0) and (Index < Length(Plugins)) then - CallDeInit(Index) -end; - -//-------------- -// if wParam = -1 then (if lParam = nil then get length of moduleinfo array. if lparam <> nil then write array of TUS_PluginInfo to address at lparam) else (Get PluginInfo of plugin with Index(wParam) to address at lParam) -//-------------- -function TPluginLoader.GetPluginInfo(wParam: TwParam; lParam: TlParam): integer; -var I: integer; -begin - Result := 0; - if (wParam > 0) then - begin // Get info of 1 plugin - if (lParam <> nil) and (wParam < Length(Plugins)) then - begin - try - Result := 1; - PUS_PluginInfo(lParam)^ := Plugins[wParam].Info; - except - - end; - end; - end - else if (lParam = nil) then - begin // Get length of plugin (info) array - Result := Length(Plugins); - end - else //Write PluginInfo Array to Address in lParam - begin - try - for I := 0 to high(Plugins) do - PAUS_PluginInfo(lParam)^[I] := Plugins[I].Info; - Result := Length(Plugins); - except - Core.ReportError(integer(PChar('Could not write PluginInfo Array')), PChar('TPluginLoader')); - end; - end; - -end; - -//-------------- -// if wParam = -1 then (if lParam = nil then get length of plugin state array. if lparam <> nil then write array of byte to address at lparam) else (return state of plugin with index(wParam)) -//-------------- -function TPluginLoader.GetPluginState(wParam: TwParam; lParam: TlParam): integer; -var I: integer; -begin - Result := -1; - if (wParam > 0) then - begin // Get state of 1 plugin - if (wParam < Length(Plugins)) then - begin - Result := Plugins[wParam].State; - end; - end - else if (lParam = nil) then - begin // Get length of plugin (info) array - Result := Length(Plugins); - end - else // Write plugininfo array to address in lParam - begin - try - for I := 0 to high(Plugins) do - byte(Pointer(integer(lParam) + I)^) := Plugins[I].State; - Result := Length(Plugins); - except - Core.ReportError(integer(PChar('Could not write pluginstate array')), PChar('TPluginLoader')); - end; - end; -end; - -{********************* - TtehPlugins - Implementation -*********************} - -//------------- -// function that gives some infos about the module to the core -//------------- -procedure TtehPlugins.Info(const pInfo: PModuleInfo); -begin - pInfo^.Name := 'TtehPlugins'; - pInfo^.Version := MakeVersion(1,0,0,chr(0)); - pInfo^.Description := 'Module executing the Plugins!'; -end; - -//------------- -// Just the constructor -//------------- -constructor TtehPlugins.Create; -begin - inherited; - PluginLoader := nil; -end; - -//------------- -// Is called on loading. -// In this method only events and services should be created -// to offer them to other modules or plugins during the init process -// if false is returned this will cause a forced exit -//------------- -function TtehPlugins.Load: boolean; -var - i: integer; // Counter - CurExecutedBackup: integer; //backup of Core.CurExecuted Attribute -begin - // Get pointer to pluginloader - PluginLoader := PPluginLoader(Core.GetModulebyName('TPluginLoader')); - if (PluginLoader = nil) then - begin - Result := false; - Core.ReportError(integer(PChar('Could not get pointer to pluginLoader')), PChar('TtehPlugins')); - end - else - begin - Result := true; - - // Backup curexecuted - CurExecutedBackup := Core.CurExecuted; - - // Start loading the plugins - for i := 0 to High(PluginLoader.Plugins) do - begin - Core.CurExecuted := -1 - i; - - try - // Unload plugin if not correctly executed - if (PluginLoader.CallLoad(i) <> 0) then - begin - PluginLoader.CallDeInit(i); - PluginLoader.Plugins[i].State := 254; // Plugin asks for unload - Core.ReportDebug(integer(PChar('Plugin selfabort during loading process: ' + string(PluginLoader.Plugins[i].Info.Name))), PChar('TtehPlugins')); - end - else - begin - Core.ReportDebug(integer(PChar('Plugin loaded succesfully: ' + string(PluginLoader.Plugins[i].Info.Name))), PChar('TtehPlugins')); - end; - except - // Plugin could not be loaded. - // => Show error message, then shutdown plugin - on E: Exception do - begin - PluginLoader.CallDeInit(i); - PluginLoader.Plugins[i].State := 255; // Plugin causes error - Core.ReportError(integer(PChar('Plugin causes error during loading process: ' + PluginLoader.Plugins[i].Info.Name + ', ErrorMsg: "' + E.Message + '"')), PChar('TtehPlugins')); - end; - end; - end; - - // Reset CurExecuted - Core.CurExecuted := CurExecutedBackup; - end; -end; - -//------------- -// Is called on init process -// in this method you can hook some events and create + init -// your classes, variables etc. -// if false is returned this will cause a forced exit -//------------- -function TtehPlugins.Init: boolean; -var - i: integer; // Counter - CurExecutedBackup: integer; // backup of Core.CurExecuted attribute -begin - Result := true; - - // Backup CurExecuted - CurExecutedBackup := Core.CurExecuted; - - // Start loading the plugins - for i := 0 to High(PluginLoader.Plugins) do - try - Core.CurExecuted := -1 - i; - - // Unload plugin if not correctly executed - if (PluginLoader.CallInit(i) <> 0) then - begin - PluginLoader.CallDeInit(i); - PluginLoader.Plugins[i].State := 254; //Plugin asks for unload - Core.ReportDebug(integer(PChar('Plugin selfabort during init process: ' + string(PluginLoader.Plugins[i].Info.Name))), PChar('TtehPlugins')); - end - else - Core.ReportDebug(integer(PChar('Plugin inited succesfully: ' + string(PluginLoader.Plugins[i].Info.Name))), PChar('TtehPlugins')); - except - // Plugin could not be loaded. - // => Show error message, then shut down plugin - PluginLoader.CallDeInit(i); - PluginLoader.Plugins[i].State := 255; //Plugin causes Error - Core.ReportError(integer(PChar('Plugin causes error during init process: ' + string(PluginLoader.Plugins[i].Info.Name))), PChar('TtehPlugins')); - end; - - // Reset CurExecuted - Core.CurExecuted := CurExecutedBackup; -end; - -//------------- -// Is called if this module has been inited and there is a exit. -// Deinit is in backwards initing order -//------------- -procedure TtehPlugins.DeInit; -var - i: integer; // Counter - CurExecutedBackup: integer; // backup of Core.CurExecuted attribute -begin - // Backup CurExecuted - CurExecutedBackup := Core.CurExecuted; - - // Start loop - - for i := 0 to High(PluginLoader.Plugins) do - begin - try - // DeInit plugin - PluginLoader.CallDeInit(i); - except - end; - end; - - // Reset CurExecuted - Core.CurExecuted := CurExecutedBackup; -end; - -end. diff --git a/unicode/src/base/URecord.pas b/unicode/src/base/URecord.pas index 8f37262d..2c2093a0 100644 --- a/unicode/src/base/URecord.pas +++ b/unicode/src/base/URecord.pas @@ -54,7 +54,7 @@ type function GetToneString: string; // converts a tone to its string represenatation; - procedure BoostBuffer(Buffer: PByteArray; Size: cardinal); + procedure BoostBuffer(Buffer: PByteArray; Size: integer); procedure ProcessNewBuffer(Buffer: PByteArray; BufferSize: integer); // we call it to analyze sound by checking Autocorrelation @@ -135,7 +135,7 @@ type procedure UpdateInputDeviceConfig; // handle microphone input - procedure HandleMicrophoneData(Buffer: PByteArray; Size: cardinal; + procedure HandleMicrophoneData(Buffer: PByteArray; Size: integer; InputDevice: TAudioInputDevice); end; @@ -459,7 +459,7 @@ begin Result := '-'; end; -procedure TCaptureBuffer.BoostBuffer(Buffer: PByteArray; Size: cardinal); +procedure TCaptureBuffer.BoostBuffer(Buffer: PByteArray; Size: integer); var i: integer; Value: longint; @@ -602,7 +602,7 @@ end; * Length - number of bytes in Buffer * Input - Soundcard-Input used for capture *} -procedure TAudioInputProcessor.HandleMicrophoneData(Buffer: PByteArray; Size: cardinal; InputDevice: TAudioInputDevice); +procedure TAudioInputProcessor.HandleMicrophoneData(Buffer: PByteArray; Size: integer; InputDevice: TAudioInputDevice); var MultiChannelBuffer: PByteArray; // buffer handled as array of bytes (offset relative to channel) SingleChannelBuffer: PByteArray; // temporary buffer for new samples per channel @@ -611,13 +611,11 @@ var CaptureChannel: TCaptureBuffer; AudioFormat: TAudioFormatInfo; SampleSize: integer; - SampleCount: integer; SamplesPerChannel: integer; i: integer; begin AudioFormat := InputDevice.AudioFormat; SampleSize := AudioSampleSize[AudioFormat.Format]; - SampleCount := Size div SampleSize; SamplesPerChannel := Size div AudioFormat.FrameSize; SingleChannelBufferSize := SamplesPerChannel * SampleSize; diff --git a/unicode/src/base/UServices.pas b/unicode/src/base/UServices.pas deleted file mode 100644 index 3783c543..00000000 --- a/unicode/src/base/UServices.pas +++ /dev/null @@ -1,384 +0,0 @@ -{* UltraStar Deluxe - Karaoke Game - * - * UltraStar Deluxe is the legal property of its developers, whose names - * are too numerous to list here. Please refer to the COPYRIGHT - * file distributed with this source distribution. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - * $URL$ - * $Id$ - *} - -unit UServices; - -interface - -{$IFDEF FPC} - {$MODE Delphi} -{$ENDIF} - -{$I switches.inc} - -uses - uPluginDefs, - SysUtils; -{********************* - TServiceManager - Class for saving, managing and calling of Services. - Saves all Services and their Procs -*********************} - -type - TServiceName = String[60]; - PServiceInfo = ^TServiceInfo; - TServiceInfo = record - Self: THandle; //Handle of this Service - Hash: Integer; //4 Bit Hash of the Services Name - Name: TServiceName; //Name of this Service - - Owner: Integer; //If < 0 [-(DLLMan Pluginindex + 1)]; 0 - undefined, On Error Full shutdown, If < 0 [ModuleIndex - 1] - - Next: PServiceInfo; //Pointer to the Next Service in teh list - - //Here is s/t tricky - //To avoid writing of Wrapping Functions to offer a Service from a Class - //We save a Normal Proc or a Method of a Class - Case isClass: boolean of - False: (Proc: TUS_Service); //Proc that will be called on Event - True: (ProcOfClass: TUS_Service_of_Object); - end; - - TServiceManager = class - private - //Managing Service List - FirstService: PServiceInfo; - LastService: PServiceInfo; - - //Some Speed improvement by caching the last 4 called Services - //Most of the time a Service is called multiple times - ServiceCache: Array[0..3] of PServiceInfo; - NextCacheItem: Byte; - - //Next Service added gets this Handle: - NextHandle: THandle; - public - Constructor Create; - - Function AddService(const ServiceName: PChar; const Proc: TUS_Service = nil; const ProcofClass: TUS_Service_of_Object = nil): THandle; - Function DelService(const hService: THandle): integer; - - Function CallService(const ServiceName: PChar; const wParam: TwParam; lParam: TlParam): integer; - - Function NametoHash(const ServiceName: TServiceName): Integer; - Function ServiceExists(const ServiceName: PChar): Integer; - end; - -var - ServiceManager: TServiceManager; - -implementation -uses - ULog, - UCore; - -//------------ -// Create - Creates Class and Set Standard Values -//------------ -Constructor TServiceManager.Create; -begin - inherited; - - FirstService := nil; - LastService := nil; - - ServiceCache[0] := nil; - ServiceCache[1] := nil; - ServiceCache[2] := nil; - ServiceCache[3] := nil; - - NextCacheItem := 0; - - NextHandle := 1; - - {$IFDEF DEBUG} - debugWriteln('ServiceManager: Succesful created!'); - {$ENDIF} -end; - -//------------ -// Function Creates a new Service and Returns the Services Handle, -// 0 on Failure. (Name already exists) -//------------ -Function TServiceManager.AddService(const ServiceName: PChar; const Proc: TUS_Service; const ProcofClass: TUS_Service_of_Object): THandle; -var - Cur: PServiceInfo; -begin - Result := 0; - - If (@Proc <> nil) or (@ProcOfClass <> nil) then - begin - If (ServiceExists(ServiceName) = 0) then - begin //There is a Proc and the Service does not already exist - //Ok Add it! - - //Get Memory - GetMem(Cur, SizeOf(TServiceInfo)); - - //Fill it with Data - Cur.Next := nil; - - If (@Proc = nil) then - begin //Use the ProcofClass Method - Cur.isClass := True; - Cur.ProcOfClass := ProcofClass; - end - else //Use the normal Proc - begin - Cur.isClass := False; - Cur.Proc := Proc; - end; - - Cur.Self := NextHandle; - //Zero Name - Cur.Name := #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0; - Cur.Name := String(ServiceName); - Cur.Hash := NametoHash(Cur.Name); - - //Add Owner to Service - Cur.Owner := Core.CurExecuted; - - //Add Service to the List - If (FirstService = nil) then - FirstService := Cur; - - If (LastService <> nil) then - LastService.Next := Cur; - - LastService := Cur; - - {$IFDEF DEBUG} - debugWriteln('ServiceManager: Service added: ''' + ServiceName + ''', Handle: ' + InttoStr(Cur.Self)); - {$ENDIF} - - //Inc Next Handle - Inc(NextHandle); - end - {$IFDEF DEBUG} - else debugWriteln('ServiceManager: Try to readd Service: ' + ServiceName); - {$ENDIF} - end; -end; - -//------------ -// Function Destroys a Service, 0 on success, not 0 on Failure -//------------ -Function TServiceManager.DelService(const hService: THandle): integer; -var - Last, Cur: PServiceInfo; - I: Integer; -begin - Result := -1; - - Last := nil; - Cur := FirstService; - - //Search for Service to Delete - While (Cur <> nil) do - begin - If (Cur.Self = hService) then - begin //Found Service => Delete it - - //Delete from List - If (Last = nil) then //Found first Service - FirstService := Cur.Next - Else //Service behind the first - Last.Next := Cur.Next; - - //IF this is the LastService, correct LastService - If (Cur = LastService) then - LastService := Last; - - //Search for Service in Cache and delete it if found - For I := 0 to High(ServiceCache) do - If (ServiceCache[I] = Cur) then - begin - ServiceCache[I] := nil; - end; - - {$IFDEF DEBUG} - debugWriteln('ServiceManager: Removed Service succesful: ' + Cur.Name); - {$ENDIF} - - //Free Memory - Freemem(Cur, SizeOf(TServiceInfo)); - - //Break the Loop - Break; - end; - - //Go to Next Service - Last := Cur; - Cur := Cur.Next; - end; -end; - -//------------ -// Function Calls a Services Proc -// Returns Services Return Value or SERVICE_NOT_FOUND on Failure -//------------ -Function TServiceManager.CallService(const ServiceName: PChar; const wParam: TwParam; lParam: TlParam): integer; -var - SExists: Integer; - Service: PServiceInfo; - CurExecutedBackup: Integer; //backup of Core.CurExecuted Attribute -begin - Result := SERVICE_NOT_FOUND; - SExists := ServiceExists(ServiceName); - If (SExists <> 0) then - begin - //Backup CurExecuted - CurExecutedBackup := Core.CurExecuted; - - Service := Pointer(SExists); - - If (Service.isClass) then - //Use Proc of Class - Result := Service.ProcOfClass(wParam, lParam) - Else - //Use normal Proc - Result := Service.Proc(wParam, lParam); - - //Restore CurExecuted - Core.CurExecuted := CurExecutedBackup; - end; - - {$IFDEF DEBUG} - debugWriteln('ServiceManager: Service ''' + ServiceName + ''' called. Result: ' + InttoStr(Result)); - {$ENDIF} -end; - -//------------ -// Generates the Hash for the given Name -//------------ -Function TServiceManager.NametoHash(const ServiceName: TServiceName): Integer; -// FIXME: check if the non-asm version is fast enough and use it by default if so -{$IF Defined(CPUX86_64)} -{$IFDEF FPC} - {$ASMMODE Intel} -{$ENDIF} -asm - { CL: Counter; RAX: Result; RDX: Current Memory Address } - Mov RCX, 14 - Mov RDX, ServiceName {Save Address of String that should be "Hashed"} - Mov RAX, [RDX] - @FoldLoop: ADD RDX, 4 {jump 4 Byte(32 Bit) to the next tile } - ADD RAX, [RDX] {Add the Value of the next 4 Byte of the String to the Hash} - LOOP @FoldLoop {Fold again if there are Chars Left} -end; -{$ELSEIF Defined(CPU386) or Defined(CPUI386)} -{$IFDEF FPC} - {$ASMMODE Intel} -{$ENDIF} -asm - { CL: Counter; EAX: Result; EDX: Current Memory Address } - Mov ECX, 14 {Init Counter, Fold 14 Times to get 4 Bytes out of 60} - Mov EDX, ServiceName {Save Address of String that should be "Hashed"} - Mov EAX, [EDX] - @FoldLoop: ADD EDX, 4 {jump 4 Byte(32 Bit) to the next tile } - ADD EAX, [EDX] {Add the Value of the next 4 Byte of the String to the Hash} - LOOP @FoldLoop {Fold again if there are Chars Left} -end; -{$ELSE} -var - i: integer; - ptr: ^integer; -begin - ptr := @ServiceName; - Result := 0; - for i := 1 to 14 do - begin - Result := Result + ptr^; - Inc(ptr); - end; -end; -{$IFEND} - - -//------------ -// Function Returns Non Zero if a Service with the given Name Exists, otherwise 0 -//------------ -Function TServiceManager.ServiceExists(const ServiceName: PChar): Integer; -var - Name: TServiceName; - Hash: Integer; - Cur: PServiceInfo; - I: Byte; -begin - Result := 0; - // to-do : Write a Metbod (in ASM) to Zero and Add in one turn (faster then this dirty hack ;) - //Zero Name: - Name := #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0 + #0; - //Add Service Name - Name := String(ServiceName); - Hash := NametoHash(Name); - - //First of all Look for the Service in Cache - For I := 0 to High(ServiceCache) do - begin - If (ServiceCache[I] <> nil) AND (ServiceCache[I].Hash = Hash) then - begin - If (ServiceCache[I].Name = Name) then - begin //Found Service in Cache - Result := Integer(ServiceCache[I]); - - {$IFDEF DEBUG} - debugWriteln('ServiceManager: Found Service in Cache: ''' + ServiceName + ''''); - {$ENDIF} - - Break; - end; - end; - end; - - If (Result = 0) then - begin - Cur := FirstService; - While (Cur <> nil) do - begin - If (Cur.Hash = Hash) then - begin - If (Cur.Name = Name) then - begin //Found the Service - Result := Integer(Cur); - - {$IFDEF DEBUG} - debugWriteln('ServiceManager: Found Service in List: ''' + ServiceName + ''''); - {$ENDIF} - - //Add to Cache - ServiceCache[NextCacheItem] := Cur; - NextCacheItem := (NextCacheItem + 1) AND 3; - Break; - end; - end; - - Cur := Cur.Next; - end; - end; -end; - -end. diff --git a/unicode/src/base/USingScores.pas b/unicode/src/base/USingScores.pas index 2d9b1e5e..89896d2d 100644 --- a/unicode/src/base/USingScores.pas +++ b/unicode/src/base/USingScores.pas @@ -34,211 +34,211 @@ interface {$I switches.inc} uses - UThemes, gl, + UThemes, UTexture; ////////////////////////////////////////////////////////////// // ATTENTION: // -// Enabled Flag does not Work atm. This should cause Popups // -// Not to Move and Scores to stay until Renenabling. // -// To use e.g. in Pause Mode // -// Also InVisible Flag causes Attributes not to change. // -// This should be fixed after next Draw when Visible = True,// -// but not testet yet // +// Enabled flag does not work atm. This should cause popups // +// not to move and scores to stay until re-enabling. // +// To use e.g. in pause mode // +// also invisible flag causes attributes not to change. // +// This should be fixed after next draw when visible = true,// +// but not tested yet // ////////////////////////////////////////////////////////////// -//Some constants containing options that could change by time +// some constants containing options that could change by time const - MaxPlayers = 6; //Maximum of Players that could be added - MaxPositions = 6; //Maximum of Score Positions that could be added + MaxPlayers = 6; // maximum of players that could be added + MaxPositions = 6; // maximum of score positions that could be added type //----------- - // TScorePlayer - Record Containing Information about a Players Score + // TScorePlayer - record containing information about a players score //----------- TScorePlayer = record - Position: Byte; //Index of the Position where the Player should be Drawn - Enabled: Boolean; //Is the Score Display Enabled - Visible: Boolean; //Is the Score Display Visible - Score: Word; //Current Score of the Player - ScoreDisplayed: Word; //Score cur. Displayed(for counting up) - ScoreBG: TTexture;//Texture of the Players Scores BG - Color: TRGB; //Teh Players Color - RBPos: Real; //Cur. Percentille of the Rating Bar - RBTarget: Real; //Target Position of Rating Bar - RBVisible:Boolean; //Is Rating bar Drawn + Position: byte; // index of the position where the player should be drawn + Enabled: boolean; // is the score display enabled + Visible: boolean; // is the score display visible + Score: word; // current score of the player + ScoreDisplayed: word; // score cur. displayed (for counting up) + ScoreBG: TTexture; // texture of the players scores bg + Color: TRGB; // the players color + RBPos: real; // cur. percentille of the rating bar + RBTarget: real; // target position of rating bar + RBVisible: boolean; // is rating bar drawn end; - aScorePlayer = array[0..MaxPlayers-1] of TScorePlayer; + aScorePlayer = array [0..MaxPlayers-1] of TScorePlayer; //----------- - // TScorePosition - Record Containing Information about a Score Position, that can be used + // TScorePosition - record containing information about a score position, that can be used //----------- PScorePosition = ^TScorePosition; TScorePosition = record - //The Position is Used for Which Playercount - PlayerCount: Byte; - // 1 - One Player per Screen - // 2 - 2 Players per Screen - // 4 - 3 Players per Screen - // 6 would be 2 and 3 Players per Screen - - BGX: Real; //X Position of the Score BG - BGY: Real; //Y Position of the Score BG - BGW: Real; //Width of the Score BG - BGH: Real; //Height of the Score BG - - RBX: Real; //X Position of the Rating Bar - RBY: Real; //Y Position of the Rating Bar - RBW: Real; //Width of the Rating Bar - RBH: Real; //Height of the Rating Bar - - TextX: Real; //X Position of the Score Text - TextY: Real; //Y Position of the Score Text - TextFont: Byte; //Font of the Score Text - TextSize: integer; //Size of the Score Text - - PUW: Real; //Width of the LineBonus Popup - PUH: Real; //Height of the LineBonus Popup - PUFont: Byte; //Font for the PopUps - PUFontSize: integer; //FontSize for the PopUps - PUStartX: Real; //X Start Position of the LineBonus Popup - PUStartY: Real; //Y Start Position of the LineBonus Popup - PUTargetX: Real; //X Target Position of the LineBonus Popup - PUTargetY: Real; //Y Target Position of the LineBonus Popup + // the position is used for which playercount + PlayerCount: byte; + // 1 - 1 player per screen + // 2 - 2 players per screen + // 4 - 3 players per screen + // 6 would be 2 and 3 players per screen + + BGX: real; // x position of the score bg + BGY: real; // y position of the score bg + BGW: real; // width of the score bg + BGH: real; // height of the score bg + + RBX: real; // x position of the rating bar + RBY: real; // y position of the rating bar + RBW: real; // width of the rating bar + RBH: real; // height of the rating bar + + TextX: real; // x position of the score text + TextY: real; // y position of the score text + TextFont: byte; // font of the score text + TextSize: integer; // size of the score text + + PUW: real; // width of the line bonus popup + PUH: real; // height of the line bonus popup + PUFont: byte; // font for the popups + PUFontSize: integer; // font size for the popups + PUStartX: real; // x start position of the line bonus popup + PUStartY: real; // y start position of the line bonus popup + PUTargetX: real; // x target position of the line bonus popup + PUTargetY: real; // y target position of the line bonus popup end; - aScorePosition = array[0..MaxPositions-1] of TScorePosition; + aScorePosition = array [0..MaxPositions-1] of TScorePosition; //----------- - // TScorePopUp - Record Containing Information about a LineBonus Popup - // List, Next Item is Saved in Next attribute + // TScorePopUp - record containing information about a line bonus popup + // list, next item is saved in next attribute //----------- PScorePopUp = ^TScorePopUp; TScorePopUp = record - Player: Byte; //Index of the PopUps Player - TimeStamp: Cardinal; //Timestamp of Popups Spawn - Rating: Byte; //0 to 8, Type of Rating (Cool, bad, etc.) - ScoreGiven:Word; //Score that has already been given to the Player - ScoreDiff: Word; //Difference Between Cur Score at Spawn and Old Score - Next: PScorePopUp; //Next Item in List + Player: byte; // index of the popups player + TimeStamp: cardinal; // timestamp of popups spawn + Rating: byte; // 0 to 8, type of rating (cool, bad, etc.) + ScoreGiven: word; // score that has already been given to the player + ScoreDiff: word; // difference between cur score at spawn and old score + Next: PScorePopUp; // next item in list end; aScorePopUp = array of TScorePopUp; //----------- - // TSingScores - Class containing Scores Positions and Drawing Scores, Rating Bar + Popups + // TSingScores - class containing scores positions and drawing scores, rating bar + popups //----------- TSingScores = class private Positions: aScorePosition; - aPlayers: aScorePlayer; - oPositionCount: Byte; - oPlayerCount: Byte; + aPlayers: aScorePlayer; + oPositionCount: byte; + oPlayerCount: byte; - //Saves the First and Last Popup of the List + // saves the first and last popup of the list FirstPopUp: PScorePopUp; LastPopUp: PScorePopUp; - // Draws a Popup by Pointer + // draws a popup by pointer procedure DrawPopUp(const PopUp: PScorePopUp); - // Draws a Score by Playerindex - procedure DrawScore(const Index: Integer); + // draws a score by playerindex + procedure DrawScore(const Index: integer); - // Draws the RatingBar by Playerindex - procedure DrawRatingBar(const Index: Integer); + // draws the rating bar by playerindex + procedure DrawRatingBar(const Index: integer); - // Removes a PopUp w/o destroying the List + // removes a popup w/o destroying the list procedure KillPopUp(const last, cur: PScorePopUp); public - Settings: record //Record containing some Displaying Options - Phase1Time: Real; //time for Phase 1 to complete (in msecs) - //The Plop Up of the PopUp - Phase2Time: Real; //time for Phase 2 to complete (in msecs) - //The Moving (mainly Upwards) of the Popup - Phase3Time: Real; //time for Phase 3 to complete (in msecs) - //The Fade out and Score adding + Settings: record // Record containing some Displaying Options + Phase1Time: real; // time for phase 1 to complete (in msecs) + // the plop up of the popup + Phase2Time: real; // time for phase 2 to complete (in msecs) + // the moving (mainly upwards) of the popup + Phase3Time: real; // time for phase 3 to complete (in msecs) + // the fade out and score adding - PopUpTex: array [0..8] of TTexture; //Textures for every Popup Rating + PopUpTex: array [0..8] of TTexture; // textures for every popup rating - RatingBar_BG_Tex: TTexture; //Rating Bar Texs - RatingBar_FG_Tex: TTexture; - RatingBar_Bar_Tex: TTexture; + RatingBar_BG_Tex: TTexture; // rating bar texs + RatingBar_FG_Tex: TTexture; + RatingBar_Bar_Tex: TTexture; end; - Visible: Boolean; //Visibility of all Scores - Enabled: Boolean; //Scores are changed, PopUps are Moved etc. - RBVisible: Boolean; //Visibility of all Rating Bars + Visible: boolean; // visibility of all scores + Enabled: boolean; // scores are changed, popups are moved etc. + RBVisible: boolean; // visibility of all rating bars - //Propertys for Reading Position and Playercount - property PositionCount: Byte read oPositionCount; - property PlayerCount: Byte read oPlayerCount; - property Players: aScorePlayer read aPlayers; + // properties for reading position and playercount + property PositionCount: byte read oPositionCount; + property PlayerCount: byte read oPlayerCount; + property Players: aScorePlayer read aPlayers; - //Constructor just sets some standard Settings + // constructor just sets some standard settings constructor Create; - // Adds a Position to Array and Increases Position Count + // adds a position to array and increases position count procedure AddPosition(const pPosition: PScorePosition); - // Adds a Player to Array and Increases Player Count - procedure AddPlayer(const ScoreBG: TTexture; const Color: TRGB; const Score: Word = 0; const Enabled: Boolean = True; const Visible: Boolean = True); + // adds a player to array and increases player count + procedure AddPlayer(const ScoreBG: TTexture; const Color: TRGB; const Score: word = 0; const Enabled: boolean = true; const Visible: boolean = true); - //Change a Players Visibility, Enable - procedure ChangePlayerVisibility(const Index: Byte; const pVisible: Boolean); - procedure ChangePlayerEnabled(const Index: Byte; const pEnabled: Boolean); + // change a players visibility, enable + procedure ChangePlayerVisibility(const Index: byte; const pVisible: boolean); + procedure ChangePlayerEnabled(const Index: byte; const pEnabled: boolean); - // Deletes all Player Information + // deletes all player information procedure ClearPlayers; - // Deletes Positions and Playerinformation + // deletes positions and playerinformation procedure Clear; - // Loads some Settings and the Positions from Theme + // loads some settings and the positions from theme procedure LoadfromTheme; - // has to be called after Positions and Players have been added, before first call of Draw - //It gives every Player a Score Position + // has to be called after positions and players have been added, before first call of draw + // it gives every player a score position procedure Init; - //Spawns a new Line Bonus PopUp for the Player - procedure SpawnPopUp(const PlayerIndex: Byte; const Rating: Byte; const Score: Word); + // spawns a new line bonus popup for the player + procedure SpawnPopUp(const PlayerIndex: byte; const Rating: byte; const Score: word); - //Removes all PopUps from Mem + // removes all popups from mem procedure KillAllPopUps; - // Draws Scores and Linebonus PopUps + // draws scores and line bonus popups procedure Draw; end; - implementation -uses SDL, - SysUtils, - ULog, - UGraphic, - TextGL; +uses + SysUtils, + SDL, + TextGL, + ULog, + UGraphic; {** - * Sets some standard Settings + * sets some standard settings *} -Constructor TSingScores.Create; +constructor TSingScores.Create; begin inherited; - //Clear PopupList Pointers + // clear popuplist pointers FirstPopUp := nil; LastPopUp := nil; - //Clear Variables - Visible := True; - Enabled := True; - RBVisible := True; + // clear variables + Visible := true; + Enabled := true; + RBVisible := true; - //Clear Position Index - oPositionCount := 0; - oPlayerCount := 0; + // clear position index + oPositionCount := 0; + oPlayerCount := 0; Settings.Phase1Time := 350; // plop it up . -> [ ] Settings.Phase2Time := 550; // shift it up ^[ ]^ @@ -260,22 +260,21 @@ begin end; {** - * Adds a Position to Array and Increases Position Count + * adds a position to array and increases position count *} -Procedure TSingScores.AddPosition(const pPosition: PScorePosition); +procedure TSingScores.AddPosition(const pPosition: PScorePosition); begin if (PositionCount < MaxPositions) then begin Positions[PositionCount] := pPosition^; - Inc(oPositionCount); end; end; {** - * Adds a Player to Array and Increases Player Count + * adds a player to array and increases player count *} -Procedure TSingScores.AddPlayer(const ScoreBG: TTexture; const Color: TRGB; const Score: Word; const Enabled: Boolean; const Visible: Boolean); +procedure TSingScores.AddPlayer(const ScoreBG: TTexture; const Color: TRGB; const Score: word; const Enabled: boolean; const Visible: boolean); begin if (PlayerCount < MaxPlayers) then begin @@ -283,48 +282,48 @@ begin aPlayers[PlayerCount].Enabled := Enabled; aPlayers[PlayerCount].Visible := Visible; aPlayers[PlayerCount].Score := Score; - aPlayers[PlayerCount].ScoreDisplayed := Score; + aPlayers[PlayerCount].ScoreDisplayed := Score; aPlayers[PlayerCount].ScoreBG := ScoreBG; aPlayers[PlayerCount].Color := Color; aPlayers[PlayerCount].RBPos := 0.5; aPlayers[PlayerCount].RBTarget := 0.5; - aPlayers[PlayerCount].RBVisible := True; + aPlayers[PlayerCount].RBVisible := true; Inc(oPlayerCount); end; end; {** - * Change a Players Visibility + * change a players visibility *} -Procedure TSingScores.ChangePlayerVisibility(const Index: Byte; const pVisible: Boolean); +procedure TSingScores.ChangePlayerVisibility(const Index: byte; const pVisible: boolean); begin if (Index < MaxPlayers) then aPlayers[Index].Visible := pVisible; end; {** - * Change Player Enabled + * change player enabled *} -Procedure TSingScores.ChangePlayerEnabled(const Index: Byte; const pEnabled: Boolean); +procedure TSingScores.ChangePlayerEnabled(const Index: byte; const pEnabled: boolean); begin if (Index < MaxPlayers) then aPlayers[Index].Enabled := pEnabled; end; {** - * Procedure Deletes all Player Information + * procedure deletes all player information *} -Procedure TSingScores.ClearPlayers; +procedure TSingScores.ClearPlayers; begin KillAllPopUps; oPlayerCount := 0; end; {** - * Procedure Deletes Positions and Playerinformation + * procedure deletes positions and playerinformation *} -Procedure TSingScores.Clear; +procedure TSingScores.Clear; begin KillAllPopUps; oPlayerCount := 0; @@ -332,14 +331,16 @@ begin end; {** - * Procedure Loads some Settings and the Positions from Theme + * procedure loads some settings and the positions from theme *} -Procedure TSingScores.LoadfromTheme; -var I: Integer; - Procedure AddbyStatics(const PC: Byte; const ScoreStatic, SingBarStatic: TThemeStatic; ScoreText: TThemeText); - var nPosition: TScorePosition; +procedure TSingScores.LoadfromTheme; +var + I: integer; + procedure AddbyStatics(const PC: byte; const ScoreStatic, SingBarStatic: TThemeStatic; ScoreText: TThemeText); + var + nPosition: TScorePosition; begin - nPosition.PlayerCount := PC; //Only for one Player Playing + nPosition.PlayerCount := PC; // only for one player playing nPosition.BGX := ScoreStatic.X; nPosition.BGY := ScoreStatic.Y; @@ -373,54 +374,55 @@ var I: Integer; begin Clear; - //Set Textures - //Popup Tex - For I := 0 to 8 do + // set textures + // popup tex + for I := 0 to 8 do Settings.PopUpTex[I] := Tex_SingLineBonusBack[I]; - //Rating Bar Tex + // rating bar tex Settings.RatingBar_BG_Tex := Tex_SingBar_Back; Settings.RatingBar_FG_Tex := Tex_SingBar_Front; Settings.RatingBar_Bar_Tex := Tex_SingBar_Bar; - //Load Positions from Theme + // load positions from theme - // Player1: + // player 1: AddByStatics(1, Theme.Sing.StaticP1ScoreBG, Theme.Sing.StaticP1SingBar, Theme.Sing.TextP1Score); AddByStatics(2, Theme.Sing.StaticP1TwoPScoreBG, Theme.Sing.StaticP1TwoPSingBar, Theme.Sing.TextP1TwoPScore); AddByStatics(4, Theme.Sing.StaticP1ThreePScoreBG, Theme.Sing.StaticP1ThreePSingBar, Theme.Sing.TextP1ThreePScore); - // Player2: + // player 2: AddByStatics(2, Theme.Sing.StaticP2RScoreBG, Theme.Sing.StaticP2RSingBar, Theme.Sing.TextP2RScore); AddByStatics(4, Theme.Sing.StaticP2MScoreBG, Theme.Sing.StaticP2MSingBar, Theme.Sing.TextP2MScore); - // Player3: + // player 3: AddByStatics(4, Theme.Sing.StaticP3RScoreBG, Theme.Sing.StaticP3SingBar, Theme.Sing.TextP3RScore); end; {** - * Spawns a new Line Bonus PopUp for the Player + * spawns a new line bonus popup for the player *} -Procedure TSingScores.SpawnPopUp(const PlayerIndex: Byte; const Rating: Byte; const Score: Word); -var Cur: PScorePopUp; +procedure TSingScores.SpawnPopUp(const PlayerIndex: byte; const Rating: byte; const Score: word); +var + Cur: PScorePopUp; begin if (PlayerIndex < PlayerCount) then begin - //Get Memory and Add Data + // get memory and add data GetMem(Cur, SizeOf(TScorePopUp)); - Cur.Player := PlayerIndex; + Cur.Player := PlayerIndex; Cur.TimeStamp := SDL_GetTicks; - //limit rating value to 8 - //a higher value would cause a crash when selecting the bg textur + // limit rating value to 8 + // a higher value would cause a crash when selecting the bg texture if (Rating > 8) then Cur.Rating := 8 else Cur.Rating := Rating; Cur.ScoreGiven:= 0; - If (Players[PlayerIndex].Score < Score) then + if (Players[PlayerIndex].Score < Score) then begin Cur.ScoreDiff := Score - Players[PlayerIndex].Score; aPlayers[PlayerIndex].Score := Score; @@ -429,77 +431,77 @@ begin Cur.ScoreDiff := 0; Cur.Next := nil; - //Log.LogError('TSingScores.SpawnPopUp| Player: ' + InttoStr(PlayerIndex) + ', Score: ' + InttoStr(Score) + ', ScoreDiff: ' + InttoStr(Cur.ScoreDiff)); + // Log.LogError('TSingScores.SpawnPopUp| Player: ' + InttoStr(PlayerIndex) + ', Score: ' + InttoStr(Score) + ', ScoreDiff: ' + InttoStr(Cur.ScoreDiff)); - //Add it to the Chain + // add it to the chain if (FirstPopUp = nil) then - //the first PopUp in the List + // the first popup in the list FirstPopUp := Cur else - //second or earlier popup + // second or earlier popup LastPopUp.Next := Cur; - //Set new Popup to Last PopUp in the List + // set new popup to last popup in the list LastPopUp := Cur; end else - Log.LogError('TSingScores: Try to add PopUp for not existing player'); + Log.LogError('TSingScores: Try to add popup for non-existing player'); end; {** - * Removes a PopUp w/o destroying the List + * removes a popup w/o destroying the list *} -Procedure TSingScores.KillPopUp(const last, cur: PScorePopUp); +procedure TSingScores.KillPopUp(const last, cur: PScorePopUp); begin - //Give Player the Last Points that missing till now + // give player the last points that missing till now aPlayers[Cur.Player].ScoreDisplayed := aPlayers[Cur.Player].ScoreDisplayed + Cur.ScoreDiff - Cur.ScoreGiven; - //Change Bars Position + // change bars position if (Cur.ScoreDiff > 0) THEN - begin //Popup w/ scorechange -> give missing Percentille + begin // popup w/ scorechange -> give missing percentille aPlayers[Cur.Player].RBTarget := aPlayers[Cur.Player].RBTarget + (Cur.ScoreDiff - Cur.ScoreGiven) / Cur.ScoreDiff * (Cur.Rating / 20 - 0.26); end else - begin //Popup w/o scorechange -> give complete Percentille + begin // popup w/o scorechange -> give complete percentille aPlayers[Cur.Player].RBTarget := aPlayers[Cur.Player].RBTarget + (Cur.Rating / 20 - 0.26); end; - If (aPlayers[Cur.Player].RBTarget > 1) then + if (aPlayers[Cur.Player].RBTarget > 1) then aPlayers[Cur.Player].RBTarget := 1 else - If (aPlayers[Cur.Player].RBTarget < 0) then + if (aPlayers[Cur.Player].RBTarget < 0) then aPlayers[Cur.Player].RBTarget := 0; - //If this is the First PopUp => Make Next PopUp the First - If (Cur = FirstPopUp) then + // if this is the first popup => make next popup the first + if (Cur = FirstPopUp) then FirstPopUp := Cur.Next - //Else => Remove Curent Popup from Chain + // else => remove curent popup from chain else Last.Next := Cur.Next; - //If this is the Last PopUp, Make PopUp before the Last - If (Cur = LastPopUp) then + // if this is the last popup, make popup before the last + if (Cur = LastPopUp) then LastPopUp := Last; - //Free the Memory + // free the memory FreeMem(Cur, SizeOf(TScorePopUp)); end; {** - * Removes all PopUps from Mem + * removes all popups from mem *} -Procedure TSingScores.KillAllPopUps; +procedure TSingScores.KillAllPopUps; var Cur: PScorePopUp; Last: PScorePopUp; begin Cur := FirstPopUp; - //Remove all PopUps: - While (Cur <> nil) do + // remove all popups: + while (Cur <> nil) do begin Last := Cur; Cur := Cur.Next; @@ -511,40 +513,42 @@ begin end; {** - * Has to be called after Positions and Players have been added, before first call of Draw - * It gives every Player a Score Position + * has to be called after positions and players have been added, before first call of draw + * it gives each player a score position *} -Procedure TSingScores.Init; +procedure TSingScores.Init; var - PlC: Array [0..1] of Byte; //Playercount First Screen and Second Screen - I, J: Integer; - MaxPlayersperScreen: Byte; - CurPlayer: Byte; - - Function GetPositionCountbyPlayerCount(bPlayerCount: Byte): Byte; - var I: Integer; + PlC: array [0..1] of byte; // playercount first screen and second screen + I, J: integer; + MaxPlayersperScreen: byte; + CurPlayer: byte; + + function GetPositionCountbyPlayerCount(bPlayerCount: byte): byte; + var + I: integer; begin Result := 0; bPlayerCount := 1 shl (bPlayerCount - 1); - For I := 0 to PositionCount-1 do + for I := 0 to PositionCount - 1 do begin - If ((Positions[I].PlayerCount AND bPlayerCount) <> 0) then + if ((Positions[I].PlayerCount and bPlayerCount) <> 0) then Inc(Result); end; end; - Function GetPositionbyPlayernum(bPlayerCount, bPlayer: Byte): Byte; - var I: Integer; + function GetPositionbyPlayernum(bPlayerCount, bPlayer: byte): byte; + var + I: integer; begin bPlayerCount := 1 shl (bPlayerCount - 1); - Result := High(Byte); + Result := High(byte); - For I := 0 to PositionCount-1 do + for I := 0 to PositionCount - 1 do begin - If ((Positions[I].PlayerCount AND bPlayerCount) <> 0) then + if ((Positions[I].PlayerCount and bPlayerCount) <> 0) then begin - If (bPlayer = 0) then + if (bPlayer = 0) then begin Result := I; Break; @@ -558,17 +562,16 @@ var begin MaxPlayersPerScreen := 0; - For I := 1 to 6 do + for I := 1 to 6 do begin - //If there are enough Positions -> Write to MaxPlayers - If (GetPositionCountbyPlayerCount(I) = I) then + // if there are enough positions -> write to maxplayers + if (GetPositionCountbyPlayerCount(I) = I) then MaxPlayersPerScreen := I else Break; end; - - //Split Players to both Screen or Display on One Screen + // split players to both screens or display on one screen if (Screens = 2) and (MaxPlayersPerScreen < PlayerCount) then begin PlC[0] := PlayerCount div 2 + PlayerCount mod 2; @@ -580,9 +583,8 @@ begin PlC[1] := 0; end; - - //Check if there are enough Positions for all Players - For I := 0 to Screens - 1 do + // check if there are enough positions for all players + for I := 0 to Screens - 1 do begin if (PlC[I] > MaxPlayersperScreen) then begin @@ -592,34 +594,34 @@ begin end; CurPlayer := 0; - //Give every Player a Position - For I := 0 to Screens - 1 do - For J := 0 to PlC[I]-1 do + // give every player a position + for I := 0 to Screens - 1 do + for J := 0 to PlC[I]-1 do begin - aPlayers[CurPlayer].Position := GetPositionbyPlayernum(PlC[I], J) OR (I shl 7); - //Log.LogError('Player ' + InttoStr(CurPlayer) + ' gets Position: ' + InttoStr(aPlayers[CurPlayer].Position)); + aPlayers[CurPlayer].Position := GetPositionbyPlayernum(PlC[I], J) or (I shl 7); + // Log.LogError('Player ' + InttoStr(CurPlayer) + ' gets Position: ' + InttoStr(aPlayers[CurPlayer].Position)); Inc(CurPlayer); end; end; {** - * Draws Scores and Linebonus PopUps + * draws scores and linebonus popups *} -Procedure TSingScores.Draw; +procedure TSingScores.Draw; var - I: Integer; - CurTime: Cardinal; + I: integer; + CurTime: cardinal; CurPopUp, LastPopUp: PScorePopUp; begin CurTime := SDL_GetTicks; - If Visible then + if Visible then begin - //Draw Popups + // draw popups LastPopUp := nil; CurPopUp := FirstPopUp; - While (CurPopUp <> nil) do + while (CurPopUp <> nil) do begin if (CurTime - CurPopUp.TimeStamp > Settings.Phase1Time + Settings.Phase2Time + Settings.Phase3Time) then begin @@ -638,64 +640,64 @@ begin end; - IF (RBVisible) then - //Draw Players w/ Rating Bar - For I := 0 to PlayerCount-1 do + if (RBVisible) then + // draw players w/ rating bar + for I := 0 to PlayerCount-1 do begin DrawScore(I); DrawRatingBar(I); end else - //Draw Players w/o Rating Bar - For I := 0 to PlayerCount-1 do + // draw players w/o rating bar + for I := 0 to PlayerCount-1 do begin DrawScore(I); end; - end; //eo Visible + end; // eo visible end; {** - * Draws a Popup by Pointer + * draws a popup by pointer *} -Procedure TSingScores.DrawPopUp(const PopUp: PScorePopUp); +procedure TSingScores.DrawPopUp(const PopUp: PScorePopUp); var - Progress: Real; - CurTime: Cardinal; - X, Y, W, H, Alpha: Real; - FontSize: integer; - FontOffset: Real; - TimeDiff: Cardinal; - PIndex: Byte; - TextLen: Real; - ScoretoAdd: Word; - PosDiff: Real; + Progress: real; + CurTime: cardinal; + X, Y, W, H, Alpha: real; + FontSize: integer; + FontOffset: real; + TimeDiff: cardinal; + PIndex: byte; + TextLen: real; + ScoretoAdd: word; + PosDiff: real; begin if (PopUp <> nil) then begin - //Only Draw if Player has a Position + // only draw if player has a position PIndex := Players[PopUp.Player].Position; - If PIndex <> high(byte) then + if PIndex <> High(byte) then begin - //Only Draw if Player is on Cur Screen - If ((Players[PopUp.Player].Position AND 128) = 0) = (ScreenAct = 1) then + // only draw if player is on cur screen + if ((Players[PopUp.Player].Position and 128) = 0) = (ScreenAct = 1) then begin CurTime := SDL_GetTicks; - If Not (Enabled AND Players[PopUp.Player].Enabled) then - //Increase Timestamp with TIem where there is no Movement ... + if not (Enabled and Players[PopUp.Player].Enabled) then + // increase timestamp with tiem where there is no movement ... begin - //Inc(PopUp.TimeStamp, LastRender); + // Inc(PopUp.TimeStamp, LastRender); end; TimeDiff := CurTime - PopUp.TimeStamp; - //Get Position of PopUp - PIndex := PIndex AND 127; + // get position of popup + PIndex := PIndex and 127; - //Check for Phase ... - If (TimeDiff <= Settings.Phase1Time) then + // check for phase ... + if (TimeDiff <= Settings.Phase1Time) then begin - //Phase 1 - The Ploping up + // phase 1 - the ploping up Progress := TimeDiff / Settings.Phase1Time; @@ -706,25 +708,25 @@ begin Y := Positions[PIndex].PUStartY + (Positions[PIndex].PUH - H)/2; FontSize := Round(Progress * Positions[PIndex].PUFontSize); - FontOffset := (H - FontSize) / 2; + FontOffset := (H - FontSize) / 2; Alpha := 1; end - Else If (TimeDiff <= Settings.Phase2Time + Settings.Phase1Time) then + else if (TimeDiff <= Settings.Phase2Time + Settings.Phase1Time) then begin - //Phase 2 - The Moving + // phase 2 - the moving Progress := (TimeDiff - Settings.Phase1Time) / Settings.Phase2Time; W := Positions[PIndex].PUW; H := Positions[PIndex].PUH; PosDiff := Positions[PIndex].PUTargetX - Positions[PIndex].PUStartX; - If PosDiff > 0 then + if PosDiff > 0 then PosDiff := PosDiff + W; X := Positions[PIndex].PUStartX + PosDiff * sqr(Progress); PosDiff := Positions[PIndex].PUTargetY - Positions[PIndex].PUStartY; - If PosDiff < 0 then + if PosDiff < 0 then PosDiff := PosDiff + Positions[PIndex].BGH; Y := Positions[PIndex].PUStartY + PosDiff * sqr(Progress); @@ -735,65 +737,68 @@ begin else begin - //Phase 3 - The Fading out + Score adding + // phase 3 - the fading out + score adding Progress := (TimeDiff - Settings.Phase1Time - Settings.Phase2Time) / Settings.Phase3Time; - If (PopUp.Rating > 0) then + if (PopUp.Rating > 0) then begin - //Add Scores if Player Enabled - If (Enabled AND Players[PopUp.Player].Enabled) then + // add scores if player enabled + if (Enabled and Players[PopUp.Player].Enabled) then begin ScoreToAdd := Round(PopUp.ScoreDiff * Progress) - PopUp.ScoreGiven; Inc(PopUp.ScoreGiven, ScoreToAdd); aPlayers[PopUp.Player].ScoreDisplayed := Players[PopUp.Player].ScoreDisplayed + ScoreToAdd; - //Change Bars Position - aPlayers[PopUp.Player].RBTarget := aPlayers[PopUp.Player].RBTarget + ScoreToAdd/PopUp.ScoreDiff * (PopUp.Rating / 20 - 0.26); - If (aPlayers[PopUp.Player].RBTarget > 1) then + // change bar positions + if PopUp.ScoreDiff = 0 then + Log.LogError('TSingScores.DrawPopUp', 'PopUp.ScoreDiff is 0 and we want to divide by it. No idea how this happens.') + else + aPlayers[PopUp.Player].RBTarget := aPlayers[PopUp.Player].RBTarget + ScoreToAdd/PopUp.ScoreDiff * (PopUp.Rating / 20 - 0.26); + if (aPlayers[PopUp.Player].RBTarget > 1) then aPlayers[PopUp.Player].RBTarget := 1 - else If (aPlayers[PopUp.Player].RBTarget < 0) then + else if (aPlayers[PopUp.Player].RBTarget < 0) then aPlayers[PopUp.Player].RBTarget := 0; end; - //Set Positions etc. - Alpha := 0.7 - 0.7 * Progress; + // set positions etc. + Alpha := 0.7 - 0.7 * Progress; W := Positions[PIndex].PUW; H := Positions[PIndex].PUH; PosDiff := Positions[PIndex].PUTargetX - Positions[PIndex].PUStartX; - If (PosDiff > 0) then + if (PosDiff > 0) then PosDiff := W else PosDiff := 0; X := Positions[PIndex].PUTargetX + PosDiff * Progress; PosDiff := Positions[PIndex].PUTargetY - Positions[PIndex].PUStartY; - If (PosDiff < 0) then + if (PosDiff < 0) then PosDiff := -Positions[PIndex].BGH else PosDiff := 0; - Y := Positions[PIndex].PUTargetY - PosDiff * (1-Progress); + Y := Positions[PIndex].PUTargetY - PosDiff * (1 - Progress); FontSize := Positions[PIndex].PUFontSize; FontOffset := (H - FontSize) / 2; end else begin - //Here the Effect that Should be shown if a PopUp without Score is Drawn - //And or Spawn with the GraphicObjects etc. - //Some Work for Blindy to do :P + // here the effect that should be shown if a popup without score is drawn + // and or spawn with the graphicobjects etc. + // some work for blindy to do :p - //ATM: Just Let it Slide in the Scores just like the Normal PopUp + // atm: just let it slide in the scores just like the normal popup Alpha := 0; end; end; - //Draw PopUp + // draw popup - if (Alpha > 0) AND (Players[PopUp.Player].Visible) then + if (Alpha > 0) and (Players[PopUp.Player].Visible) then begin - //Draw BG: + // draw bg: glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); @@ -811,45 +816,46 @@ begin glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); - //Set FontStyle and Size + // set font style and size SetFontStyle(Positions[PIndex].PUFont); - SetFontItalic(False); + SetFontItalic(false); SetFontSize(FontSize); + SetFontReflection(false, 0); - //Draw Text + // draw text TextLen := glTextWidth(Theme.Sing.LineBonusText[PopUp.Rating]); - //Color and Pos + // color and pos SetFontPos (X + (W - TextLen) / 2, Y + FontOffset); glColor4f(1, 1, 1, Alpha); - //Draw + // draw glPrint(Theme.Sing.LineBonusText[PopUp.Rating]); - end; //eo Alpha check - end; //eo Right Screen - end; //eo Player has Position + end; // eo alpha check + end; // eo right screen + end; // eo player has position end else - Log.LogError('TSingScores: Try to Draw a not existing PopUp'); + Log.LogError('TSingScores: Try to draw a non-existing popup'); end; {** - * Draws a Score by Playerindex + * draws a score by playerindex *} -Procedure TSingScores.DrawScore(const Index: Integer); +procedure TSingScores.DrawScore(const Index: integer); var Position: PScorePosition; ScoreStr: String; begin - //Only Draw if Player has a Position - If Players[Index].Position <> high(byte) then + // only draw if player has a position + if Players[Index].Position <> High(byte) then begin - //Only Draw if Player is on Cur Screen - If (((Players[Index].Position AND 128) = 0) = (ScreenAct = 1)) AND Players[Index].Visible then + // only draw if player is on cur screen + if (((Players[Index].Position and 128) = 0) = (ScreenAct = 1)) and Players[Index].Visible then begin Position := @Positions[Players[Index].Position and 127]; - //Draw ScoreBG + // draw scorebg glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); @@ -867,50 +873,51 @@ begin glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); - //Draw Score Text + // draw score text SetFontStyle(Position.TextFont); - SetFontItalic(False); + SetFontItalic(false); SetFontSize(Position.TextSize); SetFontPos(Position.TextX, Position.TextY); + SetFontReflection(false, 0); ScoreStr := InttoStr(Players[Index].ScoreDisplayed div 10) + '0'; - While (Length(ScoreStr) < 5) do + while (Length(ScoreStr) < 5) do ScoreStr := '0' + ScoreStr; glPrint(ScoreStr); - end; //eo Right Screen - end; //eo Player has Position + end; // eo right screen + end; // eo player has position end; -Procedure TSingScores.DrawRatingBar(const Index: Integer); +procedure TSingScores.DrawRatingBar(const Index: integer); var - Position: PScorePosition; - R,G,B, Size: Real; - Diff: Real; + Position: PScorePosition; + R, G, B: real; + Size, Diff: real; begin - //Only Draw if Player has a Position - if Players[Index].Position <> high(byte) then + // only draw if player has a position + if Players[Index].Position <> High(byte) then begin - //Only Draw if Player is on Cur Screen + // only draw if player is on cur screen if (((Players[Index].Position and 128) = 0) = (ScreenAct = 1) and Players[index].RBVisible and Players[index].Visible) then begin Position := @Positions[Players[Index].Position and 127]; - if (Enabled AND Players[Index].Enabled) then + if (Enabled and Players[Index].Enabled) then begin - //Move Position if Enabled + // move position if enabled Diff := Players[Index].RBTarget - Players[Index].RBPos; - If(Abs(Diff) < 0.02) then + if (Abs(Diff) < 0.02) then aPlayers[Index].RBPos := aPlayers[Index].RBTarget else aPlayers[Index].RBPos := aPlayers[Index].RBPos + Diff*0.1; end; - //Get Colors for RatingBar + // get colors for rating bar if (Players[index].RBPos <= 0.22) then begin R := 1; @@ -920,7 +927,7 @@ begin else if (Players[index].RBPos <= 0.42) then begin R := 1; - G := Players[index].RBPos*5; + G := Players[index].RBPos * 5; B := 0; end else if (Players[index].RBPos <= 0.57) then @@ -931,7 +938,7 @@ begin end else if (Players[index].RBPos <= 0.77) then begin - R := 1-(Players[index].RBPos-0.57)*5; + R := 1 - (Players[index].RBPos - 0.57) * 5; G := 1; B := 0; end @@ -942,12 +949,12 @@ begin B := 0; end; - //Enable all glFuncs Needed + // enable all glfuncs needed glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - //Draw RatingBar BG + // draw rating bar bg glColor4f(1, 1, 1, 0.8); glBindTexture(GL_TEXTURE_2D, Settings.RatingBar_BG_Tex.TexNum); @@ -965,7 +972,7 @@ begin glVertex2f(Position.RBX+Position.RBW, Position.RBY); glEnd; - //Draw Rating bar itself + // draw rating bar itself Size := Position.RBX + Position.RBW * Players[Index].RBPos; glColor4f(R, G, B, 1); glBindTexture(GL_TEXTURE_2D, Settings.RatingBar_Bar_Tex.TexNum); @@ -983,7 +990,7 @@ begin glVertex2f(Size, Position.RBY); glEnd; - //Draw Ratingbar FG (Teh thing with the 3 lines to get better readability) + // draw rating bar fg (the thing with the 3 lines to get better readability) glColor4f(1, 1, 1, 0.6); glBindTexture(GL_TEXTURE_2D, Settings.RatingBar_FG_Tex.TexNum); glBegin(GL_QUADS); @@ -1000,11 +1007,11 @@ begin glVertex2f(Position.RBX + Position.RBW, Position.RBY); glEnd; - //Disable all Enabled glFuncs + // disable all enabled glfuncs glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); - end; //eo Right Screen - end; //eo Player has Position + end; // eo Right Screen + end; // eo Player has Position end; end. diff --git a/unicode/src/base/USongs.pas b/unicode/src/base/USongs.pas index 852ccfc4..7a996262 100644 --- a/unicode/src/base/USongs.pas +++ b/unicode/src/base/USongs.pas @@ -73,35 +73,35 @@ type ); TBPM = record - BPM: real; - StartBeat: real; + BPM: real; + StartBeat: real; end; TScore = record - Name: widestring; - Score: integer; - Length: string; + Name: widestring; + Score: integer; + Length: string; end; {$IFDEF USE_PSEUDO_THREAD} - TSongs = class( TPseudoThread ) + TSongs = class(TPseudoThread) {$ELSE} - TSongs = class( TThread ) + TSongs = class(TThread) {$ENDIF} private - fNotify, fWatch : longint; - fParseSongDirectory : boolean; - fProcessing : boolean; + fNotify, fWatch: longint; + fParseSongDirectory: boolean; + fProcessing: boolean; {$ifdef MSWINDOWS} - fDirWatch : TDirectoryWatch; + fDirWatch: TDirectoryWatch; {$endif} procedure int_LoadSongList; procedure DoDirChanged(Sender: TObject); protected procedure Execute; override; public - SongList : TList; // array of songs - Selected : integer; // selected song index + SongList: TList; // array of songs + Selected: integer; // selected song index constructor Create(); destructor Destroy(); override; @@ -112,7 +112,7 @@ type procedure BrowseXMLFiles(Dir: widestring); procedure Sort(Order: integer); function FindSongFile(Dir, Mask: widestring): widestring; - property Processing : boolean read fProcessing; + property Processing: boolean read fProcessing; end; @@ -121,24 +121,24 @@ type Selected: integer; // selected song index Order: integer; // order type (0=title) CatNumShow: integer; // Category Number being seen - CatCount: integer; //Number of Categorys + CatCount: integer; // Number of Categorys procedure SortSongs(); - procedure Refresh; // refreshes arrays by recreating them from Songs array - procedure ShowCategory(Index: integer); // expands all songs in category - procedure HideCategory(Index: integer); // hides all songs in category - procedure ClickCategoryButton(Index: integer); // uses ShowCategory and HideCategory when needed - procedure ShowCategoryList; //Hides all Songs And Show the List of all Categorys - function FindNextVisible(SearchFrom:integer): integer; //Find Next visible Song - function VisibleSongs: integer; // returns number of visible songs (for tabs) - function VisibleIndex(Index: integer): integer; // returns visible song index (skips invisible) - - function SetFilter(FilterStr: UTF8String; Filter: TSongFilter): Cardinal; + procedure Refresh; // refreshes arrays by recreating them from Songs array + procedure ShowCategory(Index: integer); // expands all songs in category + procedure HideCategory(Index: integer); // hides all songs in category + procedure ClickCategoryButton(Index: integer); // uses ShowCategory and HideCategory when needed + procedure ShowCategoryList; // Hides all Songs And Show the List of all Categorys + function FindNextVisible(SearchFrom: integer): integer; // Find Next visible Song + function VisibleSongs: integer; // returns number of visible songs (for tabs) + function VisibleIndex(Index: integer): integer; // returns visible song index (skips invisible) + + function SetFilter(FilterStr: UTF8String; Filter: TSongFilter): cardinal; end; var - Songs: TSongs; // all songs - CatSongs: TCatSongs; // categorized songs + Songs: TSongs; // all songs + CatSongs: TCatSongs; // categorized songs const IN_ACCESS = $00000001; //* File was accessed */ @@ -177,7 +177,7 @@ begin // FIXME: threaded loading does not work this way. // It will just cause crashes but nothing else at the moment. - (* +(* {$ifdef MSWINDOWS} fDirWatch := TDirectoryWatch.create(nil); fDirWatch.OnChange := DoDirChanged; @@ -188,7 +188,7 @@ begin // now we can start the thread Resume(); - *) +*) // until it is fixed, simply load the song-list int_LoadSongList(); @@ -196,7 +196,7 @@ end; destructor TSongs.Destroy(); begin - FreeAndNil( SongList ); + FreeAndNil(SongList); inherited; end; @@ -207,7 +207,7 @@ end; procedure TSongs.Execute(); var - fChangeNotify : THandle; + fChangeNotify: THandle; begin {$IFDEF USE_PSEUDO_THREAD} int_LoadSongList(); @@ -241,13 +241,13 @@ begin for I := 0 to SongPaths.Count-1 do BrowseDir(SongPaths[I]); - if assigned( CatSongs ) then + if assigned(CatSongs) then CatSongs.Refresh; - if assigned( CatCovers ) then + if assigned(CatCovers) then CatCovers.Load; - //if assigned( Covers ) then + //if assigned(Covers) then // Covers.Load; if assigned(ScreenSong) then @@ -273,81 +273,81 @@ end; procedure TSongs.BrowseDir(Dir: widestring); begin - BrowseTXTFiles(Dir); - BrowseXMLFiles(Dir); + BrowseTXTFiles(Dir); + BrowseXMLFiles(Dir); end; procedure TSongs.BrowseTXTFiles(Dir: widestring); var - i : integer; - Files : TDirectoryEntryArray; - lSong : TSong; + i: integer; + Files: TDirectoryEntryArray; + lSong: TSong; begin try - Files := Platform.DirectoryFindFiles( Dir, '.txt', true) + Files := Platform.DirectoryFindFiles(Dir, '.txt', true) except Log.LogError('Couldn''t deal with directory/file: ' + Dir + ' in TSongs.BrowseTXTFiles') end; - for i := 0 to Length(Files)-1 do + for i := 0 to Length(Files) - 1 do begin if Files[i].IsDirectory then begin - BrowseTXTFiles( Dir + Files[i].Name + PathDelim ); //Recursive Call + BrowseTXTFiles(Dir + Files[i].Name + PathDelim); //Recursive Call end else begin - lSong := TSong.create( Dir + Files[i].Name ); + lSong := TSong.create(Dir + Files[i].Name); if lSong.Analyse then - SongList.add( lSong ) + SongList.add(lSong) else begin Log.LogError('AnalyseFile failed for "' + Files[i].Name + '".'); - freeandnil( lSong ); + freeandnil(lSong); end; end; end; - SetLength( Files, 0); + SetLength(Files, 0); end; procedure TSongs.BrowseXMLFiles(Dir: widestring); var - i : integer; - Files : TDirectoryEntryArray; - lSong : TSong; + i: integer; + Files: TDirectoryEntryArray; + lSong: TSong; begin try - Files := Platform.DirectoryFindFiles( Dir, '.xml', true) + Files := Platform.DirectoryFindFiles(Dir, '.xml', true) except Log.LogError('Couldn''t deal with directory/file: ' + Dir + ' in TSongs.BrowseXMLFiles') end; - for i := 0 to Length(Files)-1 do + for i := 0 to Length(Files) - 1 do begin if Files[i].IsDirectory then begin - BrowseXMLFiles( Dir + Files[i].Name + PathDelim ); //Recursive Call + BrowseXMLFiles(Dir + Files[i].Name + PathDelim); // Recursive Call end else begin - lSong := TSong.create( Dir + Files[i].Name ); + lSong := TSong.create(Dir + Files[i].Name); if lSong.AnalyseXML then - SongList.add( lSong ) + SongList.add(lSong) else begin Log.LogError('AnalyseFile failed for "' + Files[i].Name + '".'); - freeandnil( lSong ); + freeandnil(lSong); end; end; end; - SetLength( Files, 0); + SetLength(Files, 0); end; @@ -421,7 +421,7 @@ end; function TSongs.FindSongFile(Dir, Mask: widestring): widestring; var - SR: TSearchRec; // for parsing song directory + SR: TSearchRec; // for parsing song directory begin Result := ''; if FindFirst(Dir + Mask, faDirectory, SR) = 0 then @@ -490,13 +490,13 @@ var Inc(Order); CatIndex := Length(Song); SetLength(Song, CatIndex+1); - Song[CatIndex] := TSong.Create(); - Song[CatIndex].Artist := '[' + CategoryName + ']'; - Song[CatIndex].Main := true; + Song[CatIndex] := TSong.Create(); + Song[CatIndex].Artist := '[' + CategoryName + ']'; + Song[CatIndex].Main := true; Song[CatIndex].OrderTyp := 0; Song[CatIndex].OrderNum := Order; - Song[CatIndex].Cover := CatCovers.GetCover(Ini.Sorting, CategoryName); - Song[CatIndex].Visible := true; + Song[CatIndex].Cover := CatCovers.GetCover(Ini.Sorting, CategoryName); + Song[CatIndex].Visible := true; // set number of songs in previous category PrevCatBtnIndex := CatIndex - CatNumber - 1; @@ -507,21 +507,21 @@ var end; begin - CatNumShow := -1; + CatNumShow := -1; SortSongs(); CurCategory := ''; - Order := 0; - CatNumber := 0; + Order := 0; + CatNumber := 0; // Note: do NOT set Letter to ' ', otherwise no category-button will be // created for songs beginning with ' ' if songs of this category exist. // TODO: trim song-properties so ' ' will not occur as first chararcter. - Letter := 0; + Letter := 0; // clear song-list - for SongIndex := 0 to Songs.SongList.Count-1 do + for SongIndex := 0 to Songs.SongList.Count - 1 do begin // free category buttons // Note: do NOT delete songs, they are just references to Songs.SongList entries @@ -531,7 +531,7 @@ begin end; SetLength(Song, 0); - for SongIndex := 0 to Songs.SongList.Count-1 do + for SongIndex := 0 to Songs.SongList.Count - 1 do begin CurSong := TSong(Songs.SongList[SongIndex]); // if tabs are on, add section buttons for each new section @@ -545,11 +545,11 @@ begin // TODO: remove this block if it is not needed anymore { - if CurSection = 'Singstar Part 2' then CoverName := 'Singstar'; - if CurSection = 'Singstar German' then CoverName := 'Singstar'; - if CurSection = 'Singstar Spanish' then CoverName := 'Singstar'; - if CurSection = 'Singstar Italian' then CoverName := 'Singstar'; - if CurSection = 'Singstar French' then CoverName := 'Singstar'; + if CurSection = 'Singstar Part 2' then CoverName := 'Singstar'; + if CurSection = 'Singstar German' then CoverName := 'Singstar'; + if CurSection = 'Singstar Spanish' then CoverName := 'Singstar'; + if CurSection = 'Singstar Italian' then CoverName := 'Singstar'; + if CurSection = 'Singstar French' then CoverName := 'Singstar'; if CurSection = 'Singstar 80s Polish' then CoverName := 'Singstar 80s'; } @@ -668,15 +668,14 @@ begin CurSong.Visible := true else if (Ini.Tabs = 1) then CurSong.Visible := false; - - { +{ if (Ini.Tabs = 1) and (Order = 1) then begin //open first tab CurSong.Visible := true; end; CurSong.Visible := true; - } +} end; // set CatNumber of last category @@ -694,7 +693,7 @@ end; procedure TCatSongs.ShowCategory(Index: integer); var - S: integer; // song + S: integer; // song begin CatNumShow := Index; for S := 0 to high(CatSongs.Song) do @@ -706,13 +705,13 @@ begin CatSongs.Song[S].Visible := false; } // KMS: This should be the same, but who knows :-) - CatSongs.Song[S].Visible := ( (CatSongs.Song[S].OrderNum = Index) and (not CatSongs.Song[S].Main) ); + CatSongs.Song[S].Visible := ((CatSongs.Song[S].OrderNum = Index) and (not CatSongs.Song[S].Main)); end; end; procedure TCatSongs.HideCategory(Index: integer); // hides all songs in category var - S: integer; // song + S: integer; // song begin for S := 0 to high(CatSongs.Song) do begin @@ -723,7 +722,7 @@ end; procedure TCatSongs.ClickCategoryButton(Index: integer); var - Num: integer; + Num: integer; begin Num := CatSongs.Song[Index].OrderNum; if Num <> CatNumShow then @@ -739,7 +738,7 @@ end; //Hide Categorys when in Category Hack procedure TCatSongs.ShowCategoryList; var - S: integer; + S: integer; begin // Hide All Songs Show All Cats for S := 0 to high(CatSongs.Song) do @@ -749,8 +748,8 @@ begin end; //Hide Categorys when in Category Hack End -//Wrong song selected when tabs on bug -function TCatSongs.FindNextVisible(SearchFrom:integer): integer;//Find next Visible Song +// Wrong song selected when tabs on bug +function TCatSongs.FindNextVisible(SearchFrom:integer): integer;// Find next Visible Song var I: integer; begin @@ -761,11 +760,11 @@ begin Inc (I); if (I>high(CatSongs.Song)) then I := low(CatSongs.Song); - if (I = SearchFrom) then //Make One Round and no song found->quit + if (I = SearchFrom) then // Make One Round and no song found->quit break; end; end; -//Wrong song selected when tabs on bug End +// Wrong song selected when tabs on bug End (** * Returns the number of visible songs. @@ -791,16 +790,16 @@ var SongIndex: integer; begin Result := 0; - for SongIndex := 0 to Index-1 do + for SongIndex := 0 to Index - 1 do begin if (CatSongs.Song[SongIndex].Visible) then Inc(Result); end; end; -function TCatSongs.SetFilter(FilterStr: UTF8String; Filter: TSongFilter): Cardinal; +function TCatSongs.SetFilter(FilterStr: UTF8String; Filter: TSongFilter): cardinal; var - I, J: integer; + I, J: integer; TmpString: UTF8String; WordArray: array of UTF8String; begin @@ -838,8 +837,8 @@ begin fltArtist: TmpString := Song[I].Artist; end; - Song[i].Visible:=True; - // Look for every Searched Word + Song[i].Visible := true; + // Look for every searched word for J := 0 to High(WordArray) do begin Song[i].Visible := Song[i].Visible and @@ -849,7 +848,7 @@ begin Inc(Result); end else - Song[i].Visible := False; + Song[i].Visible := false; end; CatNumShow := -2; end diff --git a/unicode/src/base/UTexture.pas b/unicode/src/base/UTexture.pas index 962bd2b0..97f244fe 100644 --- a/unicode/src/base/UTexture.pas +++ b/unicode/src/base/UTexture.pas @@ -336,8 +336,8 @@ begin X := 0; Y := 0; Z := 0; - W := 0; - H := 0; + W := oldWidth; + H := oldHeight; ScaleW := 1; ScaleH := 1; Rot := 0; diff --git a/unicode/src/base/UThemes.pas b/unicode/src/base/UThemes.pas index 9bf858ed..3fd77853 100644 --- a/unicode/src/base/UThemes.pas +++ b/unicode/src/base/UThemes.pas @@ -42,13 +42,13 @@ uses type TRGB = record - R: single; - G: single; - B: single; + R: single; + G: single; + B: single; end; TRGBA = record - R, G, B, A: Double; + R, G, B, A: double; end; type @@ -175,11 +175,12 @@ type W: integer; H: integer; Z: real; + SBGW: integer; TextSize: integer; - //SBGW Mod - SBGW: integer; + showArrows:boolean; + oneItemOnly:boolean; Text: string; ColR, ColG, ColB, Int: real; @@ -359,6 +360,11 @@ type PausePopUp: TThemeStatic; end; + TThemeLyricBar = record + IndicatorYOffset, UpperX, UpperW, UpperY, UpperH, + LowerX, LowerW, LowerY, LowerH : integer; + end; + TThemeScore = class(TThemeBasic) TextArtist: TThemeText; TextTitle: TThemeText; @@ -723,6 +729,7 @@ type Level: TThemeLevel; Song: TThemeSong; Sing: TThemeSing; + LyricBar: TThemeLyricBar; Score: TThemeScore; Top5: TThemeTop5; Options: TThemeOptions; @@ -1031,9 +1038,19 @@ begin ThemeLoadStatic(Song.StaticTeam3Joker5, 'SongStaticTeam3Joker5'); + //LyricBar asd + LyricBar.UpperX := ThemeIni.ReadInteger('SingLyricsUpperBar', 'X', 0); + LyricBar.UpperW := ThemeIni.ReadInteger('SingLyricsUpperBar', 'W', 0); + LyricBar.UpperY := ThemeIni.ReadInteger('SingLyricsUpperBar', 'Y', 0); + LyricBar.UpperH := ThemeIni.ReadInteger('SingLyricsUpperBar', 'H', 0); + LyricBar.IndicatorYOffset := ThemeIni.ReadInteger('SingLyricsUpperBar', 'IndicatorYOffset', 0); + LyricBar.LowerX := ThemeIni.ReadInteger('SingLyricsLowerBar', 'X', 0); + LyricBar.LowerW := ThemeIni.ReadInteger('SingLyricsLowerBar', 'W', 0); + LyricBar.LowerY := ThemeIni.ReadInteger('SingLyricsLowerBar', 'Y', 0); + LyricBar.LowerH := ThemeIni.ReadInteger('SingLyricsLowerBar', 'H', 0); + // Sing ThemeLoadBasic(Sing, 'Sing'); - //TimeBar mod ThemeLoadStatic(Sing.StaticTimeProgress, 'SingTimeProgress'); ThemeLoadText(Sing.TextTimeText, 'SingTimeText'); @@ -1769,7 +1786,7 @@ begin ThemeSelectS.SkipX := ThemeIni.ReadInteger(Name, 'SkipX', 0); - ThemeSelectS.SBGW := ThemeIni.ReadInteger(Name, 'SBGW', 450); + ThemeSelectS.SBGW := ThemeIni.ReadInteger(Name, 'SBGW', 400); LoadColor(ThemeSelectS.ColR, ThemeSelectS.ColG, ThemeSelectS.ColB, ThemeIni.ReadString(Name, 'Color', '')); ThemeSelectS.Int := ThemeIni.ReadFloat(Name, 'Int', 1); diff --git a/unicode/src/base/UTime.pas b/unicode/src/base/UTime.pas index 3f35dffd..83844cb5 100644 --- a/unicode/src/base/UTime.pas +++ b/unicode/src/base/UTime.pas @@ -61,20 +61,20 @@ procedure CountSkipTime; procedure CountMidTime; var - USTime : TTime; + USTime: TTime; VideoBGTimer: TRelativeTimer; - TimeNew : int64; - TimeOld : int64; - TimeSkip : real; - TimeMid : real; - TimeMidTemp : int64; + TimeNew: int64; + TimeOld: int64; + TimeSkip: real; + TimeMid: real; + TimeMidTemp: int64; implementation uses sdl, - ucommon; + UCommon; const cSDLCorrectionRatio = 1000; @@ -91,14 +91,14 @@ http://www.gamedev.net/community/forums/topic.asp?topic_id=466145&whichpage=1%EE procedure CountSkipTimeSet; begin - TimeNew := SDL_GetTicks(); + TimeNew := SDL_GetTicks(); end; procedure CountSkipTime; begin - TimeOld := TimeNew; - TimeNew := SDL_GetTicks(); - TimeSkip := (TimeNew-TimeOld) / cSDLCorrectionRatio; + TimeOld := TimeNew; + TimeNew := SDL_GetTicks(); + TimeSkip := (TimeNew-TimeOld) / cSDLCorrectionRatio; end; procedure CountMidTime; @@ -127,10 +127,10 @@ end; **} (* - * Creates a new timer. - * If TriggerMode is false (default), the timer + * creates a new timer. + * if triggermode is false (default), the timer * will immediately begin with counting. - * If TriggerMode is true, it will wait until Get/SetTime() or Pause() is called + * if triggermode is true, it will wait until get/settime() or pause() is called * for the first time. *) constructor TRelativeTimer.Create(TriggerMode: boolean); -- cgit v1.2.3