blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
d2143a9f3f3678f95592a0f7201d2a4ec7babde8
dbd2ec6fe53b491b11dff401e5afad1c6252a2c3
/Unit1.cpp
ce9d972a72a2ac99bfae0ec183e65ed64e3b3e28
[]
no_license
relipse/reindeerchessclient
8fd269da7377f482621c266f871f3b813f2ab154
8d2fa379de014d67c413e185e7e8533c571f82ca
refs/heads/master
2021-01-10T05:06:31.858535
2010-10-07T18:58:01
2010-10-07T18:58:01
48,654,217
0
1
null
null
null
null
UTF-8
C++
false
false
23,510
cpp
// Last Updated: 10-11-02 - 23:07 // // What was done: // --Added Message compose that will send another message if it is too big // --fixed online list and added // --added a People that will be notified when you depart list // --fixed All List // --Got messages to display correclty in message form // --Replaced Parsing function // --moved all constants to ICCINFO.h // --Removed TMediaPlayer and used a windows function to play the sounds // --Documented functions and code // --Implemented Buttons in Message Client // // What needs to be done: // --Finish Implementing observing of games etc // --Implement looks of different types of text sent from the server // --Create new window for each tell // //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit1.h" #include <windows.h> #include <algorithm> //for sound playing #include <mmsystem.h> #include "gameboard.h" #include <string.h> #include "login.h" #include "buddylist.h" #include "console.h" #include "mes.h" #include "instanttell.h" //include all of the icc constants #include "iccinfo.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "Trayicon" #pragma link "CSPIN" #pragma link "trayicon" #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- //*********************************************************** //* This function parses a string and returns a stringlist * //* ******************************************************** AnsiString __fastcall TForm1::GetTokens(AnsiString GivenText, AnsiString Split1, AnsiString Split2, int amount) { //Step 1: find split1 //Step 2: Delete everything before and including Split 1 //Step 3: find split 2 //Step 4: Copy string from start to split 2 (not including split2) // into a temporary string //Step 5: Delete eveyrthing from start to split 2 //Step 6: Add temporary string to stringlist //Step 7 Increment # of strings //Step 8: if amount==0then check whether your at the end of the given text //Step 9: if # of strings equals amount, return tstringlist // otherwise repeat steps 1-8 //make sure SentText starts with the pretext deleted //(96 {} { }{wohl}) // ( , ) , 0 TStringList *Tokens = new TStringList; // declare the list boolean IsEnd=false; AnsiString s = GivenText, ts; int i=0; while (IsEnd==false) { //steps 1 and 2 s.Delete(1,s.Pos(Split1)+Split1.Length()-1 ); //steps 3 and 4 if (Split2 == "") ts = s.SubString(1,s.Pos(Split1)-1); else ts = s.SubString(1,s.Pos(Split2)-1); //steps 6 and 7 if (ts.Trim()!="") Tokens->Add(ts); i++; //step 5 if (Split2 == "") s.Delete(1,s.Pos(Split1)+Split1.Length()-1); else s.Delete(1,s.Pos(Split2)+Split2.Length()-1); //steps 8 and 9 if (((amount==0) && (s.Pos(Split1)==0)) || (i==amount)) IsEnd=true; } //ShowMessage(Tokens->Text); return Tokens->Text; } void __fastcall TForm1::ClientRead(TObject *Sender, TCustomWinSocket *Socket) { /*Initializations*/ TColor linecol=0x000080FF; TStringList *DGList = new TStringList; // declare the list int DGcode, index = CForm->DisplayEdit->Lines->Count; AnsiString item, TrimmedLine, s2, s = Client->Socket->ReceiveText() ; s2 = s; if (s.Pos("Present company in your notify list:")>0) isnotlist=true; if (s.Pos("The following will be notified when you depart:")>0) isdepartlist=true; if (s.Pos("(")>0) { s2.TrimLeft(); s2.Delete(1,s2.Pos("(")-1); DGList->Text = GetTokens(s2,"(",")", 0) ; for (int i=0; i < DGList->Count;i++) { DGcode = GetDG(DGList->Strings[i]) ; ProcessDG(DGcode,DGList->Strings[i]) ; } CForm->DisplayEdit->Lines->Add(s) ; } else CForm->DisplayEdit->Lines->Add(s); CForm->DisplayEdit->SelStart = CForm->DisplayEdit->Perform(EM_LINEINDEX, index, 0); CForm->DisplayEdit->SelLength = s.Length(); CForm->DisplayEdit->SelAttributes->Color = linecol; } void __fastcall TForm1::OnServerLogin() { SendCmd("set interface Reindeer 0.9"); SendCmd("set style 13"); SendCmd("set-2 68 1"); SendCmd("z"); Form1->Caption = " "+MyHandle+" - "+Form1->Caption ; BuddyListForm->Caption = MyHandle+"'s Lists" ; } /************************************************* ** This function uses the DG code and processes ** ** the actions depending on the code ** **************************************************/ void __fastcall TForm1::ProcessDG(int DG, AnsiString SentText) { AnsiString s3=SentText, s2=SentText, s=SentText; //Set colors and all that type of stuff switch(DG) { //***Examples above case statements***// //::(0 BloodLust {}) case DG_WHO_AM_I: { s.Delete(1,s.Pos("(0 ")+2) ; s.Delete(s.Pos(" {"),s.Length() ) ; s.Trim(); MyHandle = s ; OnServerLogin(); } break; //Present company in your notify list: //(96 {} { }{sauce})The following will be notified when you depart: //(96 {} { }{sauce})aics% case DG_LIST: { //it is a string list but you can't tell what list it is //so must rely on boolean value from before if (isnotlist==true) { BuddyListForm->NotifyList->Items->Text = GetTokens(s,"{","}",0); isnotlist=false; } if (isdepartlist==true) { BuddyListForm->DepartList->Items->Text = GetTokens(s,"{","}",0); isdepartlist=false; } } break; // Called when you log on or enter the command "z" case DG_MY_NOTIFY_LIST: { s.Delete(1,2); //ShowMessage(s); AnsiString TempBuddyHandle=s.SubString(1,s.Length()-2); TempBuddyHandle.Trim() ; TempBuddyHandle = TempBuddyHandle.LowerCase (); TempBuddyHandle.Delete(TempBuddyHandle.Pos("\n")-1, TempBuddyHandle.Length() ) ; AnsiString onlist=s.SubString(s.Length()-1,s.Length()); //ShowMessage(TempBuddyHandle); // ShowMessage(onlist.Trim()); if (onlist.Trim()=="1") //if added to list { BuddyListForm->AllNotList->Items->Add(TempBuddyHandle.TrimLeft() ) ; } else if (onlist.Trim()=="0") // if removed from list { AnsiString item; //remove from the All List for (int i=0;i<BuddyListForm->AllNotList->Items->Count;i++) { item = BuddyListForm->AllNotList->Items->Strings[i].LowerCase(); if (item.Pos(TempBuddyHandle.LowerCase())!=0) BuddyListForm->AllNotList->Items->Delete(i) ; } //Remove from the online list for (int i=0;i<BuddyListForm->NotifyList->Items->Count;i++) { item = BuddyListForm->NotifyList->Items->Strings[i].LowerCase(); if (item.Pos(TempBuddyHandle.LowerCase())!=0) BuddyListForm->NotifyList->Items->Delete(i) ; } } } break; //(94 {messages })(95 1 recoil 23:27 21-Aug-02 {hello this is message 1})2. recoil (23:27 21-Aug-02 EDT): hello this is message 2 case DG_MESSAGELIST_BEGIN: { MesForm->MesListBox->Clear(); } //(95 2 recoil 23:27 21-Aug-02 {hello this is message 2})aics% case DG_MESSAGELIST_ITEM: { AnsiString mes=SentText; mes.Delete(1,2); mes.Delete(mes.Pos("{"),2) ; mes.Delete(mes.Pos("}"),mes.Length() ) ; if (mes.Trim() != "messages") MesForm->MesListBox->Items->Add(mes); MesForm->Show(); MesForm->Width = 450; MesForm->Height = 250; } break; //(32 pille {C} 1 {California has 2 PM hehe})aics% case DG_SHOUT: { // make it so it looks something like: "pille shouts: Calif..." } break; // {text} telltype //(31 BloodLust {} {hi} 1) case DG_PERSONAL_TELL: { int TELL_TYPE, index = CForm->DisplayEdit->Lines->Count; AnsiString PtH=s, TellText=s, TempS; PersTellHandle = GetTokens(s," ","",1); PersTellHandle.Delete(PersTellHandle.Length()-1,PersTellHandle.Length()); PersTellHandle = PersTellHandle.LowerCase(); PlaySound("tell.wav", 0, SND_FILENAME | SND_ASYNC); s.Delete(s.Pos(")"), s.Length() ) ; TellText.Delete(1,TellText.Pos("{")+1 ) ; TellText.Delete(TellText.Pos("}"), TellText.Length() ) ; TELL_TYPE=StrToInt (s.SubString( s.Length()-1,s.Length() ) ); switch(TELL_TYPE) { //say case 0: //personal tell case 1: { //need to implement window creation for each tell CForm->TellList->Items->Insert(0, (".:: "+FormatDateTime("hh:mm:ss", Now())+" ::. "+ PersTellHandle+" - "+TellText) ); TempS = PersTellHandle+" tells you: "+TellText; CForm->DisplayEdit->Lines->Add(TempS); CForm->DisplayEdit->SelStart = CForm->DisplayEdit->Perform(EM_LINEINDEX, index, 0); CForm->DisplayEdit->SelLength = TempS.Length(); CForm->DisplayEdit->SelAttributes->Color = clYellow; } //end normal tell case break; //ptell case 2: break; //qtell case 3: break; //atell case 4: break; }//end Tell Switch }// end Tell Case break; //(64 anat)(64 ranchero)(64 TheBohemian)(64 LazyPawn) case DG_NOTIFY_ARRIVED: { s.Delete(1,2); AnsiString TempBuddyHandle=s; TempBuddyHandle.Trim() ; TempBuddyHandle.Delete(TempBuddyHandle.Pos("\n")-1, TempBuddyHandle.Length() ) ; BuddyListForm->NotifyList->Items->Add(TempBuddyHandle.TrimLeft() ) ; BuddyListForm->NotifyList->Color = clWhite; TimerNot->Enabled = true; PlaySound("notify.wav", 0, SND_FILENAME | SND_ASYNC); } break; //(65 BloodLust) case DG_NOTIFY_LEFT: { s.Delete(1,2); s.Delete(s.Pos("\n")-1,s.Length() ) ; s.Trim(); AnsiString item; for (int i=0;i<BuddyListForm->NotifyList->Items->Count;i++) { item = BuddyListForm->NotifyList->Items->Strings[i]; if (item.Pos(s)!=0) BuddyListForm->NotifyList->Items->Delete(i) ; } }// end case break; //(24 227 e7e6 298) case DG_SEND_MOVES: { AnsiString Move=SentText ,T=SentText; Square oSq, nSq; T.Delete(T.Pos(")"),T.Length() ) ; for (int i=0;i<3;i++) T.Delete(1,T.Pos(" ") ); time = StrToIntDef(T,0); Move.Delete(1,Move.Pos(CurGameNum)+CurGameNum.Length() ) ; Move.Delete(Move.Pos(" "),Move.Length() ) ; oSq = Form2->Chessboard->StringToSquare(Move.SubString(1,2) ) ; nSq = Form2->Chessboard->StringToSquare(Move.SubString(3,2) ) ; Form2->Chessboard->PerformMove(oSq, nSq) ; if (time!=0) { if (Form2->Chessboard->WhiteToMove==false) //white just moved { Form2->TimeWhiteLabel->Caption = IntToStr(time/60)+":"+IntToStr(time%60) ; Form2->WhiteTimer->Enabled=false; Form2->BlackTimer->Enabled=true; } } else // black just moved { Form2->TimeBlackLabel->Caption = IntToStr(time/60)+":"+IntToStr(time%60) ; Form2->WhiteTimer->Enabled=true; Form2->BlackTimer->Enabled=false; } } // end case break; //(15 274 BloodLust icc-listings 0 Blitz 0 5 0 5 0 1 {} 2000 2200 1053940195 {} {} 0 0 0 {} 0) case DG_MY_GAME_STARTED: { Form2->Chessboard->NewGame() ; Form2->WhiteTimer->Enabled=true; s2.Delete(1,s2.Pos("(15 ")+3) ; s2.Delete(1,s2.Pos(" ")); s=s2; s3.Delete(1,s3.Pos("(15 ")+3) ; s3.Delete(s3.Pos(" "),s3.Length() ) ; CurGameNum = s3; s2.Delete(s2.Pos(" "), s2.Length() ); s2.Trim(); if (s2==MyHandle) // if You are White { s.Delete(s.Pos(MyHandle), s.Pos(" ") ) ; s.Delete(s.Pos(" "),s.Length() ) ; Form2->Caption=CurGameNum+" - "+MyHandle+" vs. "+s ; Form2->Chessboard->WhiteOnTop=false; Form2->Chessboard->ComputerPlaysBlack=false; if (EngineOn1->Checked) Form2->Chessboard->ComputerPlaysWhite=true; // switch the clocks Form2->TimeWhiteLabel->Top = 384 ; Form2->TimeBlackLabel->Top = 40 ; } else // if you are Black { s.Delete(s.Pos(MyHandle), s.Length() ); Form2->Caption=CurGameNum+" - "+s+" vs. "+MyHandle ; Form2->Chessboard->WhiteOnTop=true; // switch the clocks int temptop; temptop = Form2->TimeWhiteLabel->Top ; Form2->TimeWhiteLabel->Top = Form2->TimeBlackLabel->Top ; Form2->TimeBlackLabel->Top = temptop; Form2->Chessboard->ComputerPlaysWhite=false; if (EngineOn1->Checked) Form2->Chessboard->ComputerPlaysBlack=true; }//end if }// end case break; //(16 504 0 Res 0-1 {White resigns} {E00})Game was not rated. No rating adjustment. case DG_MY_GAME_RESULT: { Form2->WhiteTimer->Enabled=false; Form2->BlackTimer->Enabled=false; Form2->Caption = "was game( "+Form2->Caption+" )" ; if (EngineOn1->Checked) { SendCmd("say Thankyou for the game") ; SendCmd("say Running on Reindeer created by Bloodlust") ; SendCmd("seek 1 1 r"); SendCmd("seek 3 3 r"); SendCmd("seek 2 2 r"); }//end if }// end case default: break; } } // /************************************************* ** This function gets the DG code from the ** ** command sent and converts it to an integer ** ** to be then processed by ProcessDG() ** **************************************************/ int __fastcall TForm1::GetDG(AnsiString SentText) { AnsiString s=SentText; s.Delete(s.Pos(" "), s.Length() ) ; return StrToIntDef(s, 999); } /************************************************* ** This function just keeps you from idling ** **************************************************/ void __fastcall TForm1::Timer1Timer(TObject *Sender) { SendCmd("z") ; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- void __fastcall TForm1::TellListKeyDown(TObject *Sender, WORD &Key, TShiftState Shift) { if (Key==VK_DELETE) { CForm->TellList->Items->Delete(CForm->TellList->ItemIndex) ; CForm->TellList->ItemIndex++; } } //--------------------------------------------------------------------------- void __fastcall TForm1::TimerNotTimer(TObject *Sender) { BuddyListForm->NotifyList->Color = clBlack ; CForm->TellList->Color = clBlack ; TimerNot->Enabled = false; } //--------------------------------------------------------------------------- /************************************************* ** This function sets all of the level2settings ** ** that need to be set before entering your ** ** username and password.. read help plugins ** **************************************************/ void __fastcall TForm1::ClientConnect(TObject *Sender, TCustomWinSocket *Socket) { AnsiString level2code; char l2settings[117], dest[200]="level2settings="; //*** Set to all 0's *** for (int i=0;i<117;i++) l2settings[i] = '0'; l2settings[DG_WHO_AM_I]='1'; l2settings[DG_SEND_MOVES]='1'; l2settings[DG_MOVE_SMITH]='1'; l2settings[DG_MOVE_CLOCK]='1'; l2settings[DG_MY_GAME_STARTED]='1'; l2settings[DG_MY_GAME_RESULT]='1'; l2settings[DG_MY_GAME_ENDED]='1'; l2settings[DG_PERSONAL_TELL]='1'; l2settings[DG_SHOUT]='1'; l2settings[DG_NOTIFY_ARRIVED]='1'; l2settings[DG_NOTIFY_LEFT]='1'; l2settings[DG_MATCH]='1'; l2settings[DG_MATCH_REMOVED]='1'; // l2settings[DG_MY_NOTIFY_LIST]='1'; switch to onconnect instead l2settings[DG_LIST]='1'; l2settings[DG_MESSAGELIST_BEGIN]='1'; l2settings[DG_MESSAGELIST_ITEM]='1'; l2settings[DG_STRINGLIST_BEGIN]='1'; l2settings[DG_STRINGLIST_ITEM]='1'; l2settings[DG_NOTIFY_STATE]='0'; strcat(dest,l2settings); level2code=dest; level2code.Delete(level2code.Length()-2,level2code.Length() ) ; SendCmd(level2code); SendCmd(LoginForm->HandleEdit->Text); SendCmd(LoginForm->PasswordEdit->Text); } //--------------------------------------------------------------------------- /************************************************* ** This function sends the command to the ** ** server, and automatically sends the ** ** necessary "\n\r" ** **************************************************/ void __fastcall TForm1::SendCmd(AnsiString Command) { Client->Socket->SendText(Command+"\n\r"); //test what was sent if (Command.Pos("+not")>0) Form1->SendCmd("z"); if (Command.Pos("-not")>0) Form1->SendCmd("z"); } void __fastcall TForm1::EngineOn1Click(TObject *Sender) { if (EngineOn1->Checked) EngineOn1->Checked = false ; else EngineOn1->Checked = true ; } //--------------------------------------------------------------------------- /************************************************* ** These next functions change the level of the ** ** automatic computer engine ** **************************************************/ // ***** ****** ******* ****** ******// void __fastcall TForm1::N11Click(TObject *Sender) { if (N11->Checked) z = 0 ; else { Form2->Chessboard->SearchDepth = 1; N11->Checked = true ; } } //--------------------------------------------------------------------------- void __fastcall TForm1::N21Click(TObject *Sender) { if (N21->Checked) z = 0 ; else { Form2->Chessboard->SearchDepth = 2; N21->Checked = true ; } } //--------------------------------------------------------------------------- void __fastcall TForm1::N31Click(TObject *Sender) { if (N31->Checked) z = 0 ; else { Form2->Chessboard->SearchDepth = 3; N31->Checked = true ; } } //--------------------------------------------------------------------------- void __fastcall TForm1::N41Click(TObject *Sender) { if (N41->Checked) z = 0 ; else { Form2->Chessboard->SearchDepth = 4; N41->Checked = true ; } } //--------------------------------------------------------------------------- void __fastcall TForm1::N51Click(TObject *Sender) { if (N51->Checked) z = 0 ; else { Form2->Chessboard->SearchDepth = 5; N51->Checked = true ; } } //--------------------------------------------------------------------------- void __fastcall TForm1::N61Click(TObject *Sender) { if (N61->Checked) z = 0 ; else { Form2->Chessboard->SearchDepth = 6; N61->Checked = true ; } } //--------------------------------------------------------------------------- void __fastcall TForm1::N71Click(TObject *Sender) { if (N71->Checked) z = 0 ; else { Form2->Chessboard->SearchDepth = 1; N71->Checked = true ; } } //--------------------------------------------------------------------------- void __fastcall TForm1::N81Click(TObject *Sender) { if (N81->Checked) z = 0 ; else { Form2->Chessboard->SearchDepth = 8; N81->Checked = true ; } } // ***** ****** ******* ****** ******// //--------------------------------------------------------------------------- /************************************************* ** This function automatically starts the login** ** form on startup ** **************************************************/ void __fastcall TForm1::StartupTimerTimer(TObject *Sender) { LoginForm->SetFocus(); Form1->Hide(); StartupTimer->Enabled=false; Form2->Close(); MesForm->Hide(); } //--------------------------------------------------------------------------- /************************************************* ** This function opens up the buddylist ** **************************************************/ void __fastcall TForm1::BuddyList1Click(TObject *Sender) { BuddyListForm->Visible=true ; } //--------------------------------------------------------------------------- /************************************************* ** This function opens up chessnotes.txt ** **************************************************/ void __fastcall TForm1::TButtonNotesClick(TObject *Sender) { //Open up chessnotes.txt with shellexecute } //--------------------------------------------------------------------------- /************************************************* ** this function shows the seek graph ** **************************************************/ void __fastcall TForm1::TButtonSeekGraphClick(TObject *Sender) { //turn on seek Datagrams and show seek graph } //--------------------------------------------------------------------------- /************************************************* ** this function sends the question to ch 1 ** **************************************************/ void __fastcall TForm1::TButtonHelpClick(TObject *Sender) { // call an inputquery to send a tell to channel 1 } //--------------------------------------------------------------------------- /************************************************* ** this function shows the message client ** **************************************************/ void __fastcall TForm1::Messages1Click(TObject *Sender) { SendCmd("mes"); } //--------------------------------------------------------------------------- void __fastcall TForm1::Chessboard1Click(TObject *Sender) { ITellForm->Show(); } //---------------------------------------------------------------------------
[ [ [ 1, 742 ] ] ]
c7b2175f3fc4dc40919d62519059d169d23be8e6
374d23f6a603046a5299596fc59171dc1c6b09b4
/tensores/vtkMarcacionElipse/vtkMarcacionElipsoide.cxx
b695d7c2969f590f47cd9c12fcd802402c9691c1
[]
no_license
mounyeh/tensorespablo
aa9b403ceef82094872e50f7ddd0cdd89b6b7421
f045a5c1e1decf7302de17f4448abbd284b3c2de
refs/heads/master
2021-01-10T06:09:53.357175
2010-09-19T22:57:16
2010-09-19T22:57:16
51,831,049
1
0
null
null
null
null
ISO-8859-1
C++
false
false
4,952
cxx
///////////////////////////////////////////////////////////////////// // Programa: Visualization Toolkit // Módulo: vtkMarcacionElipsoide.cxx // Descripción: Genera un elipsoide para interaccion con 3D slicer // Fecha: 2004/08/31 // Última modificación: 2006/05/22 // Lenguaje: C++ // Autor: Lucilio Cordero Grande // ETSI Telecomunicacion, Universidad de Valladolid // Campus Miguel Delibes, Camino del Cementerio, s/n // e-mail: [email protected] // ////////////////////////////////////////////////////////////////////// #include "vtkMarcacionElipsoide.h" #include "vtkObjectFactory.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkPolyDataWriter.h" #include "vtkPolyDataReader.h" #include "vtkPointData.h" #include "vtkLookupTable.h" vtkMarcacionElipsoide* vtkMarcacionElipsoide::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkMarcacionElipsoide"); if(ret) { return (vtkMarcacionElipsoide*)ret; } // If the factory was unable to create the object, then create it here. return new vtkMarcacionElipsoide; } vtkMarcacionElipsoide::vtkMarcacionElipsoide() { this->NomFichMar=NULL; this->SetNomFichMar("PuntosMarcados.vtk"); this->BarraColor=vtkScalarBarActor::New(); } vtkMarcacionElipsoide::~vtkMarcacionElipsoide() { } //Genera un elipsoide a partir de sus ejes principales. vtkPolyData *vtkMarcacionElipsoide::GeneraElipsoide(vtkPoints *Ejes) { vtkPolyData *Poli=vtkPolyData::New(); Poli->SetPoints(Ejes); Poli->Update(); return Poli; } void vtkMarcacionElipsoide::GuardarMarcacionInicial(vtkPoints *Ej) { int j; char nombre[200]; vtkPolyDataWriter *Escritor=vtkPolyDataWriter::New(); vtkPolyData *Datos=vtkPolyData::New(); j=sprintf(nombre,"%s.Punt.vtk",this->NomFichMar); //j=sprintf(nombre,"%s",this->NomFichMar); Datos->SetPoints(Ej); Escritor->SetFileName(nombre); Escritor->SetFileTypeToASCII(); Escritor->SetInput(Datos); Escritor->Write(); } vtkPoints *vtkMarcacionElipsoide::CargarMarcacionInicial() { int j; char nombre[200]; vtkPoints *Ej=vtkPoints::New(); vtkPolyDataReader *Lector=vtkPolyDataReader::New(); vtkPolyData *Datos=vtkPolyData::New(); j=sprintf(nombre,"%s.Punt.vtk",this->NomFichMar); //j=sprintf(nombre,"%s",this->NomFichMar); Lector->SetFileName(nombre); Datos=Lector->GetOutput(); Datos->Update(); Ej=Datos->GetPoints(); return Ej; } vtkActor *vtkMarcacionElipsoide::DibujaModelo(vtkPolyData *poli,int tipo,int col) { int i; vtkPolyDataMapper *map_elip=vtkPolyDataMapper::New(); vtkActor *actor_elip=vtkActor::New(); vtkProperty *color=vtkProperty::New(); vtkLookupTable *mapeoescalar=vtkLookupTable::New(); mapeoescalar->SetTableRange(this->Min[col],this->Max[col]); if (col==0) { color->SetColor(1,0,0); i=poli->GetPointData()->SetActiveScalars("CurvGauss"); for (i=0;i<256;i++) mapeoescalar->SetTableValue(i,i/255.0,.25,.75,1); this->BarraColor->SetTitle("Curvat. gaussi."); } if (col==1) { color->SetColor(0,1,0); i=poli->GetPointData()->SetActiveScalars("CurvMedia"); for (i=0;i<256;i++) mapeoescalar->SetTableValue(i,i/255.0,.75,.25,1); this->BarraColor->SetTitle("Curvatura media"); } if (col==2) { color->SetColor(0,0,1); i=poli->GetPointData()->SetActiveScalars("IndForma"); for (i=0;i<256;i++) mapeoescalar->SetTableValue(i,i/255.0,0,1,1); this->BarraColor->SetTitle("Indice de forma"); } if (col==3) { color->SetColor(1,1,0); i=poli->GetPointData()->SetActiveScalars("IndCurva"); for (i=0;i<256;i++) mapeoescalar->SetTableValue(i,i/255.0,1,0,1); this->BarraColor->SetTitle("Indice de curv."); } if (col==4) color->SetColor(1,0,1); if (col==5) color->SetColor(0,1,1); map_elip->SetLookupTable(mapeoescalar); map_elip->SetScalarRange(this->Min[col],this->Max[col]); this->BarraColor->SetLabelFormat("%.2f "); this->BarraColor->SetLookupTable(mapeoescalar); map_elip->SetColorModeToMapScalars(); if (tipo==1) map_elip->ScalarVisibilityOn(); map_elip->SetInput(poli); map_elip->GlobalImmediateModeRenderingOn(); map_elip->Update(); actor_elip->SetMapper(map_elip); color->SetOpacity(0.5); color->SetDiffuse(0.0); color->SetSpecular(0.0); color->SetAmbient(0.9); actor_elip->SetProperty(color); mapeoescalar->Delete(); map_elip->Delete(); color->Delete(); return actor_elip; } vtkScalarBarActor *vtkMarcacionElipsoide::DevuelveBarra() { this->BarraColor->SetNumberOfLabels(5); return this->BarraColor; } void vtkMarcacionElipsoide::PrintSelf(ostream& os, vtkIndent indent) { }
[ "diodoledzeppelin@9de476db-11b3-a259-9df9-d52a56463d6f" ]
[ [ [ 1, 173 ] ] ]
a3ff23b5d74a9f507d61bcba2c135f0e96658942
5236606f2e6fb870fa7c41492327f3f8b0fa38dc
/nsrpc/include/nsrpc/detail/RpcNetworkForBroadcast.h
522234d12ddf576c8f8cdf6351d903ad2603121c
[]
no_license
jcloudpld/srpc
aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88
f2483c8177d03834552053e8ecbe788e15b92ac0
refs/heads/master
2021-01-10T08:54:57.140800
2010-02-08T07:03:00
2010-02-08T07:03:00
44,454,693
0
0
null
null
null
null
UTF-8
C++
false
false
2,241
h
#ifndef NSRPC_RPCNETWORKFORBROADCAST_H #define NSRPC_RPCNETWORKFORBROADCAST_H #ifdef _MSC_VER # pragma once #endif #include <nsrpc/detail/MessageBlockProvider.h> #include <nsrpc/nsrpc.h> #include <srpc/RpcNetwork.h> #include <srpc/RpcForwarder.h> #include <boost/scoped_ptr.hpp> class ACE_Message_Block; namespace srpc { class IStream; class OStream; } // namespace srpc namespace nsrpc { class PacketCoder; class PacketCoderFactory; class SynchMessageBlockManager; class MessageBlockStreamBuffer; /** @addtogroup session * @{ */ /** * @class RpcNetworkForBroadcast * * RpcNetwork for broadcasting */ class NSRPC_API RpcNetworkForBroadcast : public srpc::RpcNetwork, public srpc::RpcForwarder, private MessageBlockProvider { public: RpcNetworkForBroadcast(); virtual ~RpcNetworkForBroadcast(); void prepareBroadcast(); /// @return send block. void* acquireBlock(); protected: void initialize(bool useBitPacking, PacketCoderFactory& packetCoderFactory, bool shouldUseUtf8ForString); private: virtual void registerRpcReceiver(srpc::RpcReceiver* /*receiver*/) { assert(false && "DON'T CALL ME!"); } virtual void unregisterRpcReceiver(srpc::RpcReceiver* /*receiver*/) { assert(false && "DON'T CALL ME!"); } virtual void send(srpc::RpcCommand& command, srpc::RpcPacketType packetType, const void* rpcHint); // = MessageBlockProvider overriding virtual ACE_Message_Block& acquireSendBlock(); virtual ACE_Message_Block& acquireRecvBlock(); private: ACE_Message_Block* marshal(srpc::RpcCommand& command); ACE_Message_Block* initOutputStream(); void releaseSendBlock(); private: bool useBitPacking_; bool shouldUseUtf8ForString_; boost::scoped_ptr<PacketCoder> packetCoder_; boost::scoped_ptr<SynchMessageBlockManager> messageBlockManager_; boost::scoped_ptr<MessageBlockStreamBuffer> wstreamBuffer_; boost::scoped_ptr<srpc::OStream> ostream_; ACE_Message_Block* sendBlock_; }; /** @} */ // addtogroup session } // namespace nsrpc #endif // !defined(NSRPC_RPCNETWORKFORBROADCAST_H)
[ "kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4" ]
[ [ [ 1, 94 ] ] ]
292daff56aca2d5bd9b9bdc9f0bbc7833fb7fd53
b08e948c33317a0a67487e497a9afbaf17b0fc4c
/LuaPlus/Src/Modules/Misc/VirtualDrive.h
675cdf906d5fe8ad3e1d5ca0c7b5b68c1b444607
[ "MIT" ]
permissive
15831944/bastionlandscape
e1acc932f6b5a452a3bd94471748b0436a96de5d
c8008384cf4e790400f9979b5818a5a3806bd1af
refs/heads/master
2023-03-16T03:28:55.813938
2010-05-21T15:00:07
2010-05-21T15:00:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,253
h
/////////////////////////////////////////////////////////////////////////////// // $Workfile: VirtualDrive.h $ // $Archive: /WorkspaceWhiz/Src/Shared/VirtualDrive.h $ // $Date: 2003/01/05 $ $Revision: #8 $ $Author: Joshua $ /////////////////////////////////////////////////////////////////////////////// // This source file is part of the Workspace Whiz source distribution and // is Copyright 1997-2003 by Joshua C. Jensen. (http://workspacewhiz.com/) // // The code presented in this file may be freely used and modified for all // non-commercial and commercial purposes so long as due credit is given and // this header is left intact. /////////////////////////////////////////////////////////////////////////////// #ifndef VIRTUALDRIVE_H #define VIRTUALDRIVE_H #include "Misc.h" #include "zlib.h" #include <time.h> #include "Array.h" #include "AnsiString.h" #include "Map.h" #include <stdlib.h> #include <ctype.h> #include "aes/fileenc.h" #include "aes/prng.h" #include "File.h" namespace Misc { class VirtualDrive; class VirtualFileHandle { public: VirtualFileHandle(); ~VirtualFileHandle(); VirtualDrive* GetParentDrive() const { return parentDrive; } bool IsValid() const { return fileEntryIndex != size_t(-1) /*VirtualDrive::INVALID_FILE_ENTRY*/; } private: VirtualFileHandle* nextOpenFile; VirtualFileHandle* prevOpenFile; VirtualDrive* parentDrive; size_t fileEntryIndex; size_t headerSize; z_stream stream; BYTE* bufferedData; DWORD posInBufferedData; ULONGLONG curCompressedFilePosition; ULONGLONG curUncompressedFilePosition; fcrypt_ctx zcx[1]; friend class VirtualDrive; }; /** A virtual drive is housed within a physical disk file. The disk file contains one or more files, known as virtual files, and a directory describing all the files. Similar in concept to WAD files. @see VirtualFile **/ class VirtualDrive { public: enum { INVALID_FILE_ENTRY = (size_t)-1 }; enum { UNCOMPRESSED = 0, COMPRESSED = 8 }; /** Represents a file entry within the virtual drive's directory. **/ class FileEntry { public: time_t GetTimeStamp() const { return m_fileTime; } DWORD GetOffset() const { return m_offset; } DWORD GetCompressedSize() const { return m_compressedSize; } DWORD GetUncompressedSize() const { return m_uncompressedSize; } DWORD GetCRC() const { return m_crc; } DWORD GetCompressionMethod() const { return m_compressionMethod; } const char* GetFileName() const { return m_fileName; } void SetTimeStamp(time_t fileTime) { m_fileTime = fileTime; m_parentDrive->m_changed = true; } void SetCRC(DWORD crc) { m_crc = crc; m_parentDrive->m_changed = true; } protected: time_t m_fileTime; DWORD m_offset; DWORD m_compressedSize; DWORD m_uncompressedSize; DWORD m_crc; DWORD m_compressionMethod; VirtualDrive* m_parentDrive; char m_fileName[1]; friend class VirtualDrive; }; /////////////////////////////////////////////////////////////////////////// VirtualDrive(); ~VirtualDrive(); bool Create(const char* filename, const char* defaultPassword = NULL); bool Create(File& parentFile, const char* fileName, const char* defaultPassword = NULL); bool Open(const char* filename, bool readOnly = true, const char* defaultPassword = NULL); bool Open(File& parentFile, const char* fileName, bool readOnly = true, const char* defaultPassword = NULL); bool Close(void); bool Flush(); bool IsReadOnly() const { return m_readOnly; } bool IsOpened() const { return m_parentFile != NULL; } bool FileCreate(const char* filename, VirtualFileHandle& fileHandle, UINT compressionMethod = COMPRESSED, const time_t* fileTime = NULL); bool FileOpen(const char* filename, VirtualFileHandle& fileHandle); bool FileOpenIndex(size_t index, VirtualFileHandle& fileHandle); bool FileClose(VirtualFileHandle& fileHandle); void FileCloseAll(); const char* FileGetFileName(VirtualFileHandle& fileHandle); ULONGLONG FileGetPosition(VirtualFileHandle& fileHandle); void FileSetLength(VirtualFileHandle& fileHandle, ULONGLONG newLength); ULONGLONG FileGetLength(VirtualFileHandle& fileHandle); LONGLONG FileSeek(VirtualFileHandle& fileHandle, LONGLONG offset, File::SeekFlags seekFlags = File::SEEKFLAG_BEGIN); ULONGLONG FileRead(VirtualFileHandle& fileHandle, void* buffer, ULONGLONG count); ULONGLONG FileWrite(VirtualFileHandle& fileHandle, const void* buffer, ULONGLONG count); bool FileErase(const char* filename); bool FileRename(const char* oldName, const char* newName); bool FileCopy(VirtualFileHandle& srcFileHandle); bool FileCopy(File& srcFile, const char* destFilename, UINT compressionMethod = COMPRESSED, const time_t* fileTime = NULL); bool FileCopy(const char* srcFileName, const char* destFilename, UINT compressionMethod = COMPRESSED, const time_t* fileTime = NULL); struct FileOrderInfo { FileOrderInfo() : compressionMethod(COMPRESSED) { } FileOrderInfo(const AnsiString& _entryName, const AnsiString& _srcPath, UINT _compressionMethod = VirtualDrive::COMPRESSED) : entryName(_entryName) , srcPath(_srcPath) , compressionMethod(_compressionMethod) { } AnsiString entryName; AnsiString srcPath; UINT compressionMethod; protected: friend class VirtualDrive; time_t writeTime; bool needUpdate; DWORD crc; UINT size; bool operator<(const FileOrderInfo& info) const { return this->entryName < info.entryName; } }; typedef Array<FileOrderInfo> FileOrderInfoArray; bool Pack(FileOrderInfoArray* fileOrder = NULL); bool ProcessFileList(const char* fileListFileName); bool ProcessFileList(FileOrderInfoArray& fileOrder); File* GetParentFile() const; const char* GetFileName() const; size_t GetFileEntryCount(void) const; VirtualDrive::FileEntry* GetFileEntry(size_t entry); VirtualDrive::FileEntry* FindFileEntry(const char* filename); size_t FindFileEntryIndex(const char* filename); int GetNumberOfFilesOpen(void) const; static time_t AdjustTime_t(time_t timeToAdjust); AnsiString errorString; private: void FileCloseInternal(VirtualFileHandle& fileHandle); size_t m_fileEntryCount; size_t m_fileEntryMaxCount; ULONGLONG m_dirOffset; ULONGLONG m_dirSize; // Directory size in bytes. UINT m_needPack:1; UINT m_readOnly:1; UINT m_unused:30; char* m_fileName; size_t* m_fileEntryOffsets; BYTE* m_fileEntries; size_t m_fileEntriesSizeBytes; size_t m_fileEntriesMaxSizeBytes; File* m_parentFile; bool m_ownParentFile; bool m_changed; //!< Whether the file needs to be flushed. VirtualFileHandle* m_curWriteFile; //!< The current file being written to. VirtualFileHandle* m_headOpenFile; class SimpleString { public: SimpleString() : m_drive(NULL), m_index((size_t)-1), m_str(NULL) {} SimpleString(VirtualDrive* drive, size_t index) : m_drive(drive), m_index(index), m_str(NULL) {} SimpleString(const char* str) : m_drive(NULL), m_index((size_t)-1), m_str(str) {} VirtualDrive* m_drive; size_t m_index; const char* m_str; }; class SimpleStringTypeTraits : public DefaultTypeTraits<SimpleString> { public: static size_t Hash(const SimpleString& str) { const char* ptr = str.m_str ? str.m_str : str.m_drive->GetFileEntry(str.m_index)->GetFileName(); size_t l = strlen(ptr); size_t h = l; size_t step = (l >> 5) + 1; for (size_t l1 = l; l1 >= step; l1 -= step) h = h ^ ((h<<5)+(h>>2)+(unsigned char)(tolower(ptr[l1-1]))); return h; } static bool CompareElements(const SimpleString& str1, const SimpleString& str2) { const char* ptr1 = str1.m_str ? str1.m_str : str1.m_drive->GetFileEntry(str1.m_index)->GetFileName(); const char* ptr2 = str2.m_str ? str2.m_str : str2.m_drive->GetFileEntry(str2.m_index)->GetFileName(); #if defined(PLATFORM_WINDOWS) return _stricmp(ptr1, ptr2) == 0; #else return strcasecmp(ptr1, ptr2) == 0; #endif } }; typedef Map<SimpleString, size_t, SimpleStringTypeTraits> FileNameMap; FileNameMap fileNameMap; AnsiString defaultPassword; fcrypt_ctx defaultzcx[1]; friend class VirtualDriveManager; friend class VirtualFile; friend class FileEntry; }; /** @return Returns the pointer to the File-derived object used for all virtual drive file operations. **/ inline File* VirtualDrive::GetParentFile() const { return m_parentFile; } /** @return Retrieves the filename of the virtual drive. **/ inline const char* VirtualDrive::GetFileName() const { return m_fileName; } /** @return Returns the number of file entries in the virtual drive. **/ inline size_t VirtualDrive::GetFileEntryCount(void) const { return m_fileEntryCount; } } // namespace Misc #endif // VIRTUALDRIVE_H
[ "voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329" ]
[ [ [ 1, 293 ] ] ]
da71ef5b26f2f79d3d86526981e683e3cf70af89
2112057af069a78e75adfd244a3f5b224fbab321
/branches/refactor/src_root/src/common/OgreOde/OgreOdeBody.cpp
6cdeaa6de26fa312f134af3cc4f1b555cbb79d08
[]
no_license
blockspacer/ireon
120bde79e39fb107c961697985a1fe4cb309bd81
a89fa30b369a0b21661c992da2c4ec1087aac312
refs/heads/master
2023-04-15T00:22:02.905112
2010-01-07T20:31:07
2010-01-07T20:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,168
cpp
#include "OgreOdeWorld.h" #include "OgreOdeBody.h" #include "OgreOdeMass.h" #include "OgreOdeDebugObject.h" #include "OgreOdeGeometry.h" using namespace OgreOde; int Body::_body_count = 0; const String Body::MovableType = "OgreOde::Body"; Body::Body(const String& name) { _body_count++; _body = dBodyCreate(World::getSingleton().getWorldID()); _debug_node = 0; _mass = new Mass(); dBodySetData(_body,(void*)this); World::getSingleton().getBodyList().registerItem(this); if(name == StringUtil::BLANK) { _name = MovableType + StringConverter::toString(_body_count); } else _name = name; _linear_damping = World::getSingleton()._linear_damping; _angular_damping = World::getSingleton()._angular_damping; _user_data = 0; } void Body::_notifyAttached(Node* parent,bool isTagPoint) { MovableObject::_notifyAttached(parent,isTagPoint); if(parent) { Body* other_body = World::getSingleton().findBody(static_cast<SceneNode*>(parent)); if((other_body)&&(other_body != this)) { static_cast<SceneNode*>(parent)->detachObject(other_body); } setPosition(parent->getPosition()); setOrientation(parent->getOrientation()); } } void Body::_updateRenderQueue(RenderQueue* queue) { } void Body::_notifyCurrentCamera(Camera* camera) { } void Body::destroyDebugNode() { if(_debug_node) { World::getSingleton().notifyGeometry(this); SceneNode* sn = static_cast<SceneNode*>(_debug_node); static_cast<SceneNode*>(sn->getParent())->removeAndDestroyChild(sn->getName()); _debug_node = 0; } } void Body::addDebugNode(Node* node) { if(!_debug_node) { _debug_node = World::getSingleton()._manager->getRootSceneNode()->createChild(_name + String("_Debug")); } _debug_node->addChild(node); } void Body::setPosition(const Vector3& position) { dBodySetPosition(_body,(dReal)position.x,(dReal)position.y,(dReal)position.z); if(mParentNode) mParentNode->setPosition(position); } void Body::setOrientation(const Quaternion& orientation) { dQuaternion q; q[0] = (dReal)orientation.w; q[1] = (dReal)orientation.x; q[2] = (dReal)orientation.y; q[3] = (dReal)orientation.z; dBodySetQuaternion(_body,q); if(mParentNode) mParentNode->setOrientation(orientation); } void Body::setLinearVelocity(const Vector3& linear_velocity) { dBodySetLinearVel(_body,(dReal)linear_velocity.x,(dReal)linear_velocity.y,(dReal)linear_velocity.z); } void Body::setAngularVelocity(const Vector3& angular_velocity) { dBodySetAngularVel(_body,(dReal)angular_velocity.x,(dReal)angular_velocity.y,(dReal)angular_velocity.z); } void Body::setTorque(const Vector3& torque) { dBodySetTorque(_body,(dReal)torque.x,(dReal)torque.y,(dReal)torque.z); } const Vector3& Body::getPosition() { const dReal* position = dBodyGetPosition(_body); _position.x = (Real)position[0]; _position.y = (Real)position[1]; _position.z = (Real)position[2]; return _position; } const Quaternion& Body::getOrientation() { const dReal* orientation = dBodyGetQuaternion(_body); _orientation.w = (Real)orientation[0]; _orientation.x = (Real)orientation[1]; _orientation.y = (Real)orientation[2]; _orientation.z = (Real)orientation[3]; return _orientation; } const Vector3& Body::getLinearVelocity() { const dReal* linear_velocity = dBodyGetLinearVel(_body); _linear_vel.x = (Real)linear_velocity[0]; _linear_vel.y = (Real)linear_velocity[1]; _linear_vel.z = (Real)linear_velocity[2]; return _linear_vel; } const Vector3& Body::getAngularVelocity() { const dReal* angular_velocity = dBodyGetAngularVel(_body); _angular_vel.x = (Real)angular_velocity[0]; _angular_vel.y = (Real)angular_velocity[1]; _angular_vel.z = (Real)angular_velocity[2]; return _angular_vel; } const String& Body::getMovableType() const { return MovableType; } const AxisAlignedBox& Body::getBoundingBox(void) const { return _bounding_box; } Real Body::getBoundingRadius(void) const { return 0.0; } void Body::setMass(const Mass& mass) { dBodySetMass(_body,mass.getMassPtr()); } const Mass& Body::getMass() { dMass mass; dBodyGetMass(_body,&mass); *_mass = &mass; return *_mass; } void Body::addForce(const Vector3& force) { dBodyAddForce(_body,(dReal)force.x,(dReal)force.y,(dReal)force.z); } void Body::addTorque(const Vector3& torque) { dBodyAddTorque(_body,(dReal)torque.x,(dReal)torque.y,(dReal)torque.z); } void Body::addRelativeForce(const Vector3& force) { dBodyAddRelForce(_body,(dReal)force.x,(dReal)force.y,(dReal)force.z); } void Body::addRelativeTorque(const Vector3& torque) { dBodyAddRelTorque(_body,(dReal)torque.x,(dReal)torque.y,(dReal)torque.z); } void Body::addForceAt(const Vector3& force,const Vector3& position) { dBodyAddForceAtPos(_body,(dReal)force.x,(dReal)force.y,(dReal)force.z,(dReal)position.x,(dReal)position.y,(dReal)position.z); } void Body::addForceAtRelative(const Vector3& force,const Vector3& position) { dBodyAddForceAtRelPos(_body,(dReal)force.x,(dReal)force.y,(dReal)force.z,(dReal)position.x,(dReal)position.y,(dReal)position.z); } void Body::addRelativeForceAt(const Vector3& force,const Vector3& position) { dBodyAddRelForceAtPos(_body,(dReal)force.x,(dReal)force.y,(dReal)force.z,(dReal)position.x,(dReal)position.y,(dReal)position.z); } void Body::addRelativeForceAtRelative(const Vector3& force,const Vector3& position) { dBodyAddRelForceAtRelPos(_body,(dReal)force.x,(dReal)force.y,(dReal)force.z,(dReal)position.x,(dReal)position.y,(dReal)position.z); } const Vector3& Body::getForce() { const dReal* force = dBodyGetForce(_body); _force.x = force[0]; _force.y = force[1]; _force.z = force[2]; return _force; } const Vector3& Body::getTorque() { const dReal* torque = dBodyGetTorque(_body); _torque.x = torque[0]; _torque.y = torque[1]; _torque.z = torque[2]; return _torque; } /* Given a point on a body, get that point's position in the world */ Vector3 Body::getPointWorldPosition(const Vector3& position) { dVector3 result; dBodyGetRelPointPos(_body,(dReal)position.x,(dReal)position.y,(dReal)position.z,result); return Vector3(result[0],result[1],result[2]); } /* Given a point on a body, get that point's velocity in the world */ Vector3 Body::getPointWorldVelocity(const Vector3& position) { dVector3 result; dBodyGetRelPointVel(_body,(dReal)position.x,(dReal)position.y,(dReal)position.z,result); return Vector3(result[0],result[1],result[2]); } /* Given a point (in the world), get that point's velocity in the world with respect to the body i.e. convert the global point to a relative point on the body and compute the velocity of that point on the body */ Vector3 Body::getPointVelocity(const Vector3& position) { dVector3 result; dBodyGetPointVel(_body,(dReal)position.x,(dReal)position.y,(dReal)position.z,result); return Vector3(result[0],result[1],result[2]); } Vector3 Body::getPointBodyPosition(const Vector3& position) { dVector3 result; dBodyGetPosRelPoint(_body,(dReal)position.x,(dReal)position.y,(dReal)position.z,result); return Vector3(result[0],result[1],result[2]); } Vector3 Body::getVectorToWorld(const Vector3& vector) { dVector3 result; dBodyVectorToWorld(_body,(dReal)vector.x,(dReal)vector.y,(dReal)vector.z,result); return Vector3(result[0],result[1],result[2]); } Vector3 Body::getVectorFromWorld(const Vector3& vector) { dVector3 result; dBodyVectorFromWorld(_body,(dReal)vector.x,(dReal)vector.y,(dReal)vector.z,result); return Vector3(result[0],result[1],result[2]); } void Body::wake() { dBodyEnable(_body); } void Body::sleep() { dBodyDisable(_body); } bool Body::isAwake() { return ((dBodyIsEnabled(_body))?true:false); } void Body::setAutoSleep(bool auto_disable) { dBodySetAutoDisableFlag(_body,((auto_disable)?1:0)); } bool Body::getAutoSleep() { return ((dBodyGetAutoDisableFlag(_body))?true:false); } void Body::setAutoSleepLinearThreshold(Real linear_threshold) { dBodySetAutoDisableLinearThreshold(_body,(dReal)linear_threshold); } Real Body::getAutoSleepLinearThreshold() { return (Real)dBodyGetAutoDisableLinearThreshold(_body); } void Body::setAutoSleepAngularThreshold(Real angular_threshold) { dBodySetAutoDisableAngularThreshold(_body,(dReal)angular_threshold); } Real Body::getAutoSleepAngularThreshold() { return (Real)dBodyGetAutoDisableAngularThreshold(_body); } void Body::setAutoSleepSteps(int steps) { dBodySetAutoDisableSteps(_body,steps); } int Body::getAutoSleepSteps() { return dBodyGetAutoDisableSteps(_body); } void Body::setAutoSleepTime(Real time) { dBodySetAutoDisableTime(_body,(dReal)time); } Real Body::getAutoSleepTime() { return (Real)dBodyGetAutoDisableTime(_body); } void Body::setAutoSleepDefaults() { dBodySetAutoDisableDefaults(_body); } void Body::setFiniteRotationMode(bool on) { dBodySetFiniteRotationMode(_body,((on)?1:0)); } bool Body::getFiniteRotationMode() { return ((dBodyGetFiniteRotationMode(_body))?true:false); } void Body::setFiniteRotationAxis(const Vector3& axis) { dBodySetFiniteRotationAxis(_body,(dReal)axis.x,(dReal)axis.y,(dReal)axis.z); } const Vector3& Body::getFiniteRotationAxis() { dVector3 result; dBodyGetFiniteRotationAxis(_body,result); _finite_axis.x = result[0]; _finite_axis.x = result[1]; _finite_axis.x = result[2]; return _finite_axis; } int Body::getJointCount() { return dBodyGetNumJoints(_body); } Joint* Body::getJoint(int index) { return (Joint*)World::getSingleton().getJointList().findItem((unsigned int)dBodyGetJoint(_body,index)); } int Body::getGeometryCount() { std::map<unsigned long,MaintainedItem*>::iterator i = World::getSingleton()._geometry_list._map.begin(); std::map<unsigned long,MaintainedItem*>::iterator end = World::getSingleton()._geometry_list._map.end(); int rc = 0; for(;i != end;++i) { if(this == ((Geometry*)i->second)->getBody()) ++rc; } return rc; } Geometry* Body::getGeometry(int index) { std::map<unsigned long,MaintainedItem*>::iterator i = World::getSingleton()._geometry_list._map.begin(); std::map<unsigned long,MaintainedItem*>::iterator end = World::getSingleton()._geometry_list._map.end(); Geometry* rc = 0; int idx = 0; for(;i != end;++i) { if(this == ((Geometry*)i->second)->getBody()) { rc = (Geometry*)i->second; ++idx; if(idx > index) break; } } return rc; } void Body::setAffectedByGravity(bool on) { dBodySetGravityMode(_body,((on)?1:0)); } bool Body::getAffectedByGravity() { return ((dBodyGetGravityMode(_body))?true:false); } dBodyID Body::getBodyID() const { return _body; } const String& Body::getName(void) const { return _name; } void Body::updateParentNode() { if(mParentNode) { mParentNode->setPosition(getPosition()); mParentNode->setOrientation(getOrientation()); } if(_debug_node) { _debug_node->setPosition(getPosition()); _debug_node->setOrientation(getOrientation()); recursiveSetMode(static_cast<SceneNode*>(_debug_node)); } } void Body::deriveLocation() { if(mParentNode) { setPosition(mParentNode->getPosition()); setOrientation(mParentNode->getOrientation()); } } void Body::recursiveSetMode(SceneNode* node) { for(int i = 0;i < node->numChildren();i++) { recursiveSetMode(static_cast<SceneNode*>(node->getChild(i))); } for(int j = 0;j < node->numAttachedObjects();j++) { static_cast<DebugObject*>(node->getAttachedObject(j))->setMode((isAwake())?DebugObject::Mode_Enabled:DebugObject::Mode_Disabled); } } void Body::setDamping(Real linear_damping,Real angular_damping) { _linear_damping = -(dReal)linear_damping; _angular_damping = -(dReal)angular_damping; } Real Body::getLinearDamping() { return -(Real)_linear_damping; } Real Body::getAngularDamping() { return -(Real)_angular_damping; } void Body::applyDamping() { if(dBodyIsEnabled(_body)) { const dReal* v; if(_linear_damping < 0.0) { v = dBodyGetLinearVel(_body); dBodyAddForce(_body,v[0] * _linear_damping,v[1] * _linear_damping,v[2] * _linear_damping); } if(_angular_damping < 0.0) { v = dBodyGetAngularVel(_body); dBodyAddTorque(_body,v[0] * _angular_damping,v[1] * _angular_damping,v[2] * _angular_damping); } } } void Body::sync() { if((dBodyIsEnabled(_body))||(_debug_node)) { applyDamping(); updateParentNode(); } } void Body::setDebug(bool debug) { destroyDebugNode(); } void Body::setUserData(unsigned long user_data) { _user_data = user_data; } unsigned long Body::getUserData() { return _user_data; } unsigned long Body::getID() { return (unsigned long)_body; } Body::~Body() { destroyDebugNode(); delete _mass; World::getSingleton().getBodyList().unregisterItem((unsigned int)_body); dBodyDestroy(_body); }
[ [ [ 1, 566 ] ] ]
dee4231341b7b7b04fc8ff0a60aa39f70aa6f581
2ca3ad74c1b5416b2748353d23710eed63539bb0
/Src/Lokapala/Operator/ConnectedHostsDTO.cpp
f8f819580ace39de3f628d5576cd78a6c24b4505
[]
no_license
sjp38/lokapala
5ced19e534bd7067aeace0b38ee80b87dfc7faed
dfa51d28845815cfccd39941c802faaec9233a6e
refs/heads/master
2021-01-15T16:10:23.884841
2009-06-03T14:56:50
2009-06-03T14:56:50
32,124,140
0
0
null
null
null
null
UTF-8
C++
false
false
1,694
cpp
/**@file ConnectedHostsDTO.cpp * @brief CConnectedHostsDTO 클래스의 멤버함수를 구현한다. * @author siva */ #include "stdafx.h" #include "ConnectedHostsDTO.h" /**@brief 새로 연결된 유저의 정보를 등록한다. */ void CConnectedHostsDTO::RegistConnected(CConnectedHostDTO *a_connected) { RemoveConnected(&a_connected->m_hostAddress); RemoveConnected(&a_connected->m_userId); m_connected.Add(*a_connected); } /**@brief 연결된 목록에서 특정 데이터를 삭제한다. * @param a_key 삭제하고자 하는 데이터의 사용자 또는 좌석 id. */ void CConnectedHostsDTO::RemoveConnected(CString *a_key) { int cursor = FindConnected(a_key); if(cursor != -1) { m_connected.RemoveAt(cursor); } if(cursor = FindConnected(a_key) != -1) { m_connected.RemoveAt(cursor); } return; } /**@brief 연결된 목록에서 원하는 연결 사항을 얻는다. * @param a_key 찾고자 하는 연결 항목의 유저 id 또는 호스트 어드레스 * @return 찾은 경우, 해당 연결 사항의 포인터, 찾지 못한 경우, NULL */ void *CConnectedHostsDTO::GetConnected(CString *a_key) { int index = FindConnected(a_key); if(index == -1) { return NULL; } return &m_connected[index]; } /**@brief 연결된 목록에서 원하는 연결 사항을 찾는다. * @param a_key 찾고자 하는 연결 항목의 유저 id 또는 좌석 id. */ int CConnectedHostsDTO::FindConnected(CString *a_key) { for(int i=0; i<m_connected.GetCount(); i++) { if( m_connected[i].m_userId == *a_key || m_connected[i].m_hostAddress == *a_key ) { return i; } } return -1; }
[ "nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c" ]
[ [ [ 1, 62 ] ] ]
d2c0567f7e3295d59e1e31a0aed154bf0cf6acee
c034a6ffa81773a279c4cd25bdbd3b23a999d4b7
/GMFGUI/GMFGUI/GMFDec/decMaterialFunctions.cpp
77f8e2ae4e3215f000edb635ecb7232762cab6ff
[]
no_license
Shima33/gmftoolkit
08ee92bb5700af984286c71dd54dbfd1ffecd35a
0e602d27b9b8cce83942f9624cbb892b0fd44b6b
refs/heads/master
2021-01-10T15:45:10.838305
2010-06-20T19:09:19
2010-06-20T19:09:19
50,957,203
0
0
null
null
null
null
UTF-8
C++
false
false
7,346
cpp
// Open Source C GMF Compiler // Copyright (c) 2008 Sergiusz Bazanski // http://www.q3k.org/ // GPL License #include "stdafx.h" #include "../mystdio.h" #include <string.h> #include <memory.h> #include <stdlib.h> #include "byteFunctions.h" #include "helperFunctions.h" extern FILE *source; extern FILE *output; #ifdef _BIG_ENDIAN #define endian_swap32(x) ((((x) & 0xff000000) >> 24) | \ (((x) & 0x00ff0000) >> 8) | \ (((x) & 0x0000ff00) << 8) | \ (((x) & 0x000000ff) << 24)) #else #define endian_swap32(x) (x) #endif extern int isRA1; void readTexture(int preTabNum) { free(getBytes(8)); int totalLength = getInteger(); char* mapName = getString(); myprintf("Decompiling TEXTURE %s...\n", mapName); free(mapName); char* mapClass = getString(); char* mapBitmap = getString(); float mapAmount = getFloat(); char* mapStyle = (char*)malloc(15); switch (getInteger()) { case 1: strncpy_s(mapStyle, 15, "*MAP_DIFFUSE", 15); break; case 5: strncpy_s(mapStyle, 15, "*MAP_SELFILLUM", 15); break; case 6: strncpy_s(mapStyle, 15, "*MAP_OPACITY", 15); break; default: strncpy_s(mapStyle, 15, "*MAP_DIFFUSE", 15); break; } char* mapType = (char*)malloc(7); if (getInteger() == 4) strncpy_s(mapType, 7, "Screen", 7); else strncpy_s(mapType, 7, "Other", 7); float mapUO = getFloat(); float mapVO = getFloat(); float mapUT = getFloat(); float mapVT = getFloat(); float mapUVWAngle = getFloat(); float mapUVWBlur = getFloat(); float mapUVWBlurOffset = getFloat(); float mapUVWNoiseAmt = getFloat(); float mapUVWNoiseSize = getFloat(); int mapUVWNoiseLevel = getInteger(); float mapUVWNoisePhase = getFloat(); free(getBytes(8)); char* mapBitmapFilter = (char*)malloc(10); if (getInteger() == 0) strncpy_s(mapBitmapFilter, 10, "Pyramidal", 10); else strncpy_s(mapBitmapFilter, 10, "SAT", 10); int mapBitmapChannel; if (isRA1 == 0) { mapBitmapChannel = getInteger(); free(getBytes(4)); } tab(preTabNum); fprintf(output, "*TEXTURE\n"); tab(preTabNum); fprintf(output, "{\n"); tab(preTabNum+1); fprintf(output, "*MAP_NAME\t%s\n", mapName); tab(preTabNum+1); fprintf(output, "*MAP_CLASS\t%s\n", mapClass); tab(preTabNum+1); fprintf(output, "*BITMAP\t%s\n", mapBitmap); tab(preTabNum+1); fprintf(output, "*MAP_AMOUNT\t%f\n", mapAmount); tab(preTabNum+1); fprintf(output, "%s\n", mapStyle); tab(preTabNum+1); fprintf(output, "*MAP_TYPE\t%s\n", mapType); tab(preTabNum+1); fprintf(output, "*UVW_U_OFFSET\t%f\n", mapUO); tab(preTabNum+1); fprintf(output, "*UVW_V_OFFSET\t%f\n", mapVO); tab(preTabNum+1); fprintf(output, "*UVW_U_TILING\t%f\n", mapUT); tab(preTabNum+1); fprintf(output, "*UVW_V_TILING\t%f\n", mapVT); tab(preTabNum+1); fprintf(output, "*UVW_ANGLE\t%f\n", mapUVWAngle); tab(preTabNum+1); fprintf(output, "*UVW_BLUR\t%f\n", mapUVWBlur); tab(preTabNum+1); fprintf(output, "*UVW_BLUR_OFFSET\t%f\n", mapUVWBlurOffset); tab(preTabNum+1); fprintf(output, "*UVW_NOISE_AMT\t%f\n", mapUVWNoiseAmt); tab(preTabNum+1); fprintf(output, "*UVW_NOISE_SIZE\t%f\n", mapUVWNoiseSize); tab(preTabNum+1); fprintf(output, "*UVW_NOISE_LEVEL\t%i\n", mapUVWNoiseLevel); tab(preTabNum+1); fprintf(output, "*UVW_NOISE_PHASE\t%f\n", mapUVWNoisePhase); tab(preTabNum+1); fprintf(output, "*BITMAP_FILTER\t%s\n", mapBitmapFilter); if (isRA1 == 0) { tab(preTabNum+1); fprintf(output, "*BITMAP_MAP_CHANNEL\t%i\n", mapBitmapChannel); } tab(preTabNum); fprintf(output, "}\n"); free(mapStyle); free(mapType); free(mapBitmapFilter); free(mapClass); free(mapBitmap); } void readTextureList(int preTabNum) { free(getBytes(8)); int totalLength = getInteger(); int totalCount = getInteger(); //printf("Decompiling \t\tTEXTURE_LIST...\n"); tab(preTabNum); fprintf(output, "*TEXTURE_LIST\n"); tab(preTabNum); fprintf(output, "{\n"); tab(preTabNum+1); fprintf(output, "*TEXTURE_COUNT\t%i\n", totalCount); int i; for (i =0; i < totalCount; i++) { readTexture(preTabNum+1); } tab(preTabNum); fprintf(output, "}\n"); } void readMaterialList(int preTabNum); void readMaterial(int preTabNum) { free(getBytes(8)); int totalLength = getInteger(); int matRef = getInteger(); char* matName = getString(); myprintf("Decompiling MATERIAL %s...\n", matName); char* matClass = getString(); char* matAmbient = getRGB(); char* matDiffuse = getRGB(); char* matSpecular = getRGB(); float matShine = getFloat(); float matShineStrength = getFloat(); float matTransparency = getFloat(); float matWiresize = getFloat(); char* matShading = (char*) malloc(6); if (getInteger() == 12) strncpy_s(matShading, 6, "Blinn", 6); else strncpy_s(matShading, 6, "Other", 6); float matXPFallof = getFloat(); float matSelfillum = getFloat(); char* matFallof = (char*) malloc(6); if (getInteger() == 1) strncpy_s(matFallof, 6, "In", 6); else strncpy_s(matFallof, 6, "Other", 6); char* matXPType = (char*) malloc(7); if (getInteger() == 1) strncpy_s(matXPType, 7, "Filter", 7); else strncpy_s(matXPType, 7, "Other", 7); tab(preTabNum); fprintf(output, "*MATERIAL\n"); tab(preTabNum); fprintf(output, "{\n"); tab(preTabNum+1); fprintf(output, "*MATERIAL_REF_NO\t%i\n", matRef); tab(preTabNum+1); fprintf(output, "*MATERIAL_NAME\t%s\n", matName); tab(preTabNum+1); fprintf(output, "*MATERIAL_CLASS\t%s\n", matClass); tab(preTabNum+1); fprintf(output, "*MATERIAL_AMBIENT\t%s\n", matAmbient); tab(preTabNum+1); fprintf(output, "*MATERIAL_DIFFUSE\t%s\n", matDiffuse); tab(preTabNum+1); fprintf(output, "*MATERIAL_SPECULAR\t%s\n", matSpecular); tab(preTabNum+1); fprintf(output, "*MATERIAL_SHINE\t%f\n", matShine); tab(preTabNum+1); fprintf(output, "*MATERIAL_SHINESTRENGTH\t%f\n", matShineStrength); tab(preTabNum+1); fprintf(output, "*MATERIAL_TRANSPARENCY\t%f\n", matTransparency); tab(preTabNum+1); fprintf(output, "*MATERIAL_WIRESIZE\t%f\n", matWiresize); tab(preTabNum+1); fprintf(output, "*MATERIAL_SHADING\t%s\n", matShading); tab(preTabNum+1); fprintf(output, "*MATERIAL_XP_FALLOFF\t%f\n", matXPFallof); tab(preTabNum+1); fprintf(output, "*MATERIAL_SELFILLUM\t%f\n", matSelfillum); tab(preTabNum+1); fprintf(output, "*MATERIAL_FALLOFF\t%s\n", matFallof); tab(preTabNum+1); fprintf(output, "*MATERIAL_XP_TYPE\t%s\n", matXPType); int textNum = getInteger(); if (textNum > 0) readTextureList(preTabNum + 1); int matNum = getInteger(); if (matNum > 0) readMaterialList(preTabNum + 1); tab(preTabNum); fprintf(output, "}\n"); free(matShading); free(matFallof); free(matXPType); free(matName); free(matClass); free(matAmbient); free(matDiffuse); free(matSpecular); } void readMaterialList(int preTabNum) { free(getBytes(8)); int matLength = getInteger(); int matNumber = getInteger(); //printf("Decompiling MATERIAL_LIST...\n"); tab(preTabNum); fprintf(output, "*MATERIAL_LIST\n"); tab(preTabNum); fprintf(output, "{\n"); tab(preTabNum+1); fprintf(output, "*MATERIAL_COUNT\t%i\n", matNumber); int i; for(i = 0; i < matNumber; i++) { readMaterial(preTabNum+1); } tab(preTabNum); fprintf(output, "}\n"); myprintf("\n"); }
[ "Bazanski@1d10bff2-9961-11dd-bd51-a78b85c98fae" ]
[ [ [ 1, 239 ] ] ]
8da273812eb6d294587ce825eecdccd9ca05ab8b
b4d726a0321649f907923cc57323942a1e45915b
/CODE/SOUND/RTVOICE.CPP
ba3f03171204143dc1ab7e9aa1fbf3ec34481c7f
[]
no_license
chief1983/Imperial-Alliance
f1aa664d91f32c9e244867aaac43fffdf42199dc
6db0102a8897deac845a8bd2a7aa2e1b25086448
refs/heads/master
2016-09-06T02:40:39.069630
2010-10-06T22:06:24
2010-10-06T22:06:24
967,775
2
0
null
null
null
null
UTF-8
C++
false
false
19,075
cpp
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ /* * $Logfile: /Freespace2/code/Sound/rtvoice.cpp $ * $Revision: 1.1.1.1 $ * $Date: 2004/08/13 22:47:43 $ * $Author: Spearhawk $ * * C module file for real-time voice * * $Log: RTVOICE.CPP,v $ * Revision 1.1.1.1 2004/08/13 22:47:43 Spearhawk * no message * * Revision 1.1.1.1 2004/08/13 21:34:22 Darkhill * no message * * Revision 2.1 2002/08/01 01:41:10 penguin * The big include file move * * Revision 2.0 2002/06/03 04:02:29 penguin * Warpcore CVS sync * * Revision 1.1 2002/05/02 18:03:13 mharris * Initial checkin - converted filenames and includes to lower case * * * 2 10/07/98 10:54a Dave * Initial checkin. * * 1 10/07/98 10:51a Dave * * 24 4/24/98 2:17a Lawrance * Clear out record buffer when recording begins * * 23 4/21/98 4:44p Dave * Implement Vasudan ships in multiplayer. Added a debug function to bash * player rank. Fixed a few rtvoice buffer overrun problems. Fixed ui * problem in options screen. * * 22 4/21/98 10:30a Dave * allocate 8 second buffers for rtvoice * * 21 4/17/98 5:27p Dave * More work on the multi options screen. Fixed many minor ui todo bugs. * * 20 4/17/98 10:38a Lawrance * reduce num output streams to 1 * * 19 3/25/98 9:56a Dave * Increase buffer size to handle 8 seconds of voice data. * * 18 3/22/98 7:13p Lawrance * Get streaming of recording voice working * * 17 3/09/98 5:22p Dave * Fixed a rtvoice bug which caused bogus output when given size 0 input. * * 16 2/26/98 2:54p Lawrance * Don't recreate capture buffer each time recording starts... just use * one. * * 15 2/24/98 11:56p Lawrance * Change real-time voice code to provide the uncompressed size on decode. * * 14 2/24/98 10:13p Dave * Put in initial support for multiplayer voice streaming. * * 13 2/24/98 10:47a Lawrance * Play voice through normal channels * * 12 2/23/98 6:54p Lawrance * Make interface to real-time voice more generic and useful. * * 11 2/19/98 12:47a Lawrance * Use a global code_info * * 10 2/16/98 7:31p Lawrance * get compression/decompression of voice working * * 9 2/15/98 11:59p Lawrance * Change the order of some code when opening a stream * * 8 2/15/98 11:10p Lawrance * more work on real-time voice system * * 7 2/15/98 4:43p Lawrance * work on real-time voice * * 6 2/09/98 8:07p Lawrance * get buffer create working * * 5 2/04/98 6:08p Lawrance * Read function pointers from dsound.dll, further work on * DirectSoundCapture. * * 4 2/03/98 11:53p Lawrance * Adding support for DirectSoundCapture * * 3 2/03/98 4:07p Lawrance * check return codes from waveIn calls * * 2 1/31/98 5:48p Lawrance * Start on real-time voice recording * * $NoKeywords: $ */ #include "globalincs/pstypes.h" #include "sound/sound.h" #include "sound/ds.h" #include "sound/dscap.h" #include "vcodec/codec1.h" #include "sound/rtvoice.h" typedef struct rtv_format { int nchannels; int bits_per_sample; int frequency; } rtv_format; #define MAX_RTV_FORMATS 5 static rtv_format Rtv_formats[MAX_RTV_FORMATS] = { {1, 8, 11025}, {1, 16, 11025}, {1, 8, 22050}, {1, 16, 22050}, {1, 8, 44100}, }; static int Rtv_do_compression=1; // flag to indicate whether compression should be done static int Rtv_recording_format; // recording format, index into Rtv_formats[] static int Rtv_playback_format; // playback format, index into Rtv_formats[] #define RTV_BUFFER_TIME 8 // length of buffer in seconds static int Rtv_recording_inited=0; // The input stream has been inited static int Rtv_playback_inited=0; // The output stream has been inited static int Rtv_recording=0; // Voice is currently being recorded #define MAX_RTV_OUT_BUFFERS 1 #define RTV_OUT_FLAG_USED (1<<0) typedef struct rtv_out_buffer { int ds_handle; // handle to directsound buffer int flags; // see RTV_OUT_FLAG_ #defines above } rtv_out_buffer; static rtv_out_buffer Rtv_output_buffers[MAX_RTV_OUT_BUFFERS]; // data for output buffers static struct t_CodeInfo Rtv_code_info; // Parms will need to be transmitted with packets // recording timer data static int Rtv_record_timer_id; // unique id for callback timer static int Rtv_callback_time; // callback time in ms void (*Rtv_callback)(); // recording/encoding buffers static unsigned char *Rtv_capture_raw_buffer; static unsigned char *Rtv_capture_compressed_buffer; static int Rtv_capture_compressed_buffer_size; static int Rtv_capture_raw_buffer_size; static unsigned char *Encode_buffer1=NULL; static unsigned char *Encode_buffer2=NULL; // playback/decoding buffers static unsigned char *Rtv_playback_uncompressed_buffer; static int Rtv_playback_uncompressed_buffer_size; static unsigned char *Decode_buffer=NULL; static int Decode_buffer_size; ///////////////////////////////////////////////////////////////////////////////////////////////// // RECORD/ENCODE ///////////////////////////////////////////////////////////////////////////////////////////////// void CALLBACK TimeProc(unsigned int id, unsigned int msg, unsigned long userdata, unsigned long dw1, unsigned long dw2) { if ( !Rtv_callback ) { return; } nprintf(("Alan","In callback\n")); Rtv_callback(); } // Try to pick the most appropriate recording format // // exit: 0 => success // !0 => failure int rtvoice_pick_record_format() { int i; for (i=0; i<MAX_RTV_FORMATS; i++) { if ( dscap_create_buffer(Rtv_formats[i].frequency, Rtv_formats[i].bits_per_sample, 1, RTV_BUFFER_TIME) == 0 ) { dscap_release_buffer(); Rtv_recording_format=i; break; } } if ( i == MAX_RTV_FORMATS ) { return -1; } return 0; } // input: qos => new quality of service (1..10) void rtvoice_set_qos(int qos) { InitEncoder(e_cCodec1, qos, Encode_buffer1, Encode_buffer2); } // Init the recording portion of the real-time voice system // input: qos => quality of service (1..10) 1 is highest compression, 10 is highest quality // exit: 0 => success // !0 => failure, recording not possible int rtvoice_init_recording(int qos) { if ( !Rtv_recording_inited ) { if ( rtvoice_pick_record_format() ) { return -1; } Rtv_capture_raw_buffer_size = Rtv_formats[Rtv_recording_format].frequency * (RTV_BUFFER_TIME) * fl2i(Rtv_formats[Rtv_recording_format].bits_per_sample/8.0f); if ( Encode_buffer1 ) { free(Encode_buffer1); Encode_buffer1=NULL; } if ( dscap_create_buffer(Rtv_formats[Rtv_recording_format].frequency, Rtv_formats[Rtv_recording_format].bits_per_sample, 1, RTV_BUFFER_TIME) ) { return -1; } Encode_buffer1 = (unsigned char*)malloc(Rtv_capture_raw_buffer_size); Assert(Encode_buffer1); if ( Encode_buffer2 ) { free(Encode_buffer2); Encode_buffer2=NULL; } Encode_buffer2 = (unsigned char*)malloc(Rtv_capture_raw_buffer_size); Assert(Encode_buffer2); // malloc out the voice data buffer for raw (uncompressed) recorded sound if ( Rtv_capture_raw_buffer ) { free(Rtv_capture_raw_buffer); Rtv_capture_raw_buffer=NULL; } Rtv_capture_raw_buffer = (unsigned char*)malloc(Rtv_capture_raw_buffer_size); // malloc out voice data buffer for compressed recorded sound if ( Rtv_capture_compressed_buffer ) { free(Rtv_capture_compressed_buffer); Rtv_capture_compressed_buffer=NULL; } Rtv_capture_compressed_buffer_size=Rtv_capture_raw_buffer_size; // be safe and allocate same as uncompressed Rtv_capture_compressed_buffer = (unsigned char*)malloc(Rtv_capture_compressed_buffer_size); InitEncoder(e_cCodec1, qos, Encode_buffer1, Encode_buffer2); Rtv_recording_inited=1; } return 0; } // Stop a stream from recording void rtvoice_stop_recording() { if ( !Rtv_recording ) { return; } dscap_stop_record(); if ( Rtv_record_timer_id ) { timeKillEvent(Rtv_record_timer_id); Rtv_record_timer_id = 0; } Rtv_recording=0; } // Close down the real-time voice recording system void rtvoice_close_recording() { if ( Rtv_recording ) { rtvoice_stop_recording(); } if ( Encode_buffer1 ) { free(Encode_buffer1); Encode_buffer1=NULL; } if ( Encode_buffer2 ) { free(Encode_buffer2); Encode_buffer2=NULL; } if ( Rtv_capture_raw_buffer ) { free(Rtv_capture_raw_buffer); Rtv_capture_raw_buffer=NULL; } if ( Rtv_capture_compressed_buffer ) { free(Rtv_capture_compressed_buffer); Rtv_capture_compressed_buffer=NULL; } Rtv_recording_inited=0; } // Open a stream for recording (recording begins immediately) // exit: 0 => success // !0 => failure int rtvoice_start_recording( void (*user_callback)(), int callback_time ) { if ( !dscap_supported() ) { return -1; } Assert(Rtv_recording_inited); if ( Rtv_recording ) { return -1; } if ( dscap_start_record() ) { return -1; } if ( user_callback ) { Rtv_record_timer_id = timeSetEvent(callback_time, callback_time, TimeProc, 0, TIME_PERIODIC); if ( !Rtv_record_timer_id ) { dscap_stop_record(); return -1; } Rtv_callback = user_callback; Rtv_callback_time = callback_time; } else { Rtv_callback = NULL; Rtv_record_timer_id = 0; } Rtv_recording=1; return 0; } // compress voice data using specialized codec int rtvoice_compress(unsigned char *data_in, int size_in, unsigned char *data_out, int size_out) { int compressed_size; Rtv_code_info.Code = e_cCodec1; Rtv_code_info.Gain = 0; compressed_size = 0; if(size_in <= 0){ nprintf(("Network","RTVOICE => 0 bytes size in !\n")); } else { compressed_size = Encode(data_in, data_out, size_in, size_out, &Rtv_code_info); nprintf(("SOUND","RTVOICE => Sound compressed to %d bytes (%0.2f percent)\n", compressed_size, (compressed_size*100.0f)/size_in)); } return compressed_size; } // For 8-bit formats (unsigned, 0 to 255) // For 16-bit formats (signed, -32768 to 32767) int rtvoice_16to8(unsigned char *data, int size) { int i; unsigned short sample16; unsigned char sample8, *dest, *src; Assert(size%2 == 0); dest = data; src = data; for (i=0; i<size; i+=2) { sample16 = src[0]; sample16 |= src[1] << 8; sample16 += 32768; sample8 = (unsigned char)(sample16>>8); *dest++ = sample8; src += 2; } return (size>>1); } // Convert voice sample from 22KHz to 11KHz int rtvoice_22to11(unsigned char *data, int size) { int i, new_size=0; unsigned char *dest, *src; dest=data; src=data; for (i=0; i<size; i+=2) { *(dest+new_size) = *(src+i); new_size++; } return new_size; } // Convert voice data to 8bit, 11KHz if necessary int rtvoice_maybe_convert_data(unsigned char *data, int size) { int new_size=size; switch ( Rtv_recording_format ) { case 0: // do nothing break; case 1: // convert samples to 8 bit from 16 bit new_size = rtvoice_16to8(data,new_size); break; case 2: // convert to 11KHz new_size = rtvoice_22to11(data,new_size); break; case 3: // convert to 11Khz, 8 bit new_size = rtvoice_16to8(data,new_size); new_size = rtvoice_22to11(data,new_size); break; default: Int3(); // should never happen break; } return new_size; } // Retrieve the recorded voice data // input: outbuf => output parameter, recorded voice stored here // compressed_size => output parameter, size in bytes of recorded voice after compression // uncompressed_size => output parameter, size in bytes of recorded voice before compression // gain => output parameter, gain value which must be passed to decoder // outbuf_raw => output optional parameter, pointer to the raw sound data making up the compressed chunk // outbuf_size_raw => output optional parameter, size of the outbuf_raw buffer // // NOTE: function converts voice data into compressed format void rtvoice_get_data(unsigned char **outbuf, int *compressed_size, int *uncompressed_size, double *gain, unsigned char **outbuf_raw, int *outbuf_size_raw) { int max_size, raw_size, csize; max_size = dscap_max_buffersize(); *compressed_size=0; *uncompressed_size=0; *outbuf=NULL; if ( max_size < 0 ) { return; } raw_size = dscap_get_raw_data(Rtv_capture_raw_buffer, max_size); // convert data to 8bit, 11KHz if necessary raw_size = rtvoice_maybe_convert_data(Rtv_capture_raw_buffer, raw_size); *uncompressed_size=raw_size; // compress voice data if ( Rtv_do_compression ) { csize = rtvoice_compress(Rtv_capture_raw_buffer, raw_size, Rtv_capture_compressed_buffer, Rtv_capture_compressed_buffer_size); *gain = Rtv_code_info.Gain; *compressed_size = csize; *outbuf = Rtv_capture_compressed_buffer; } else { *gain = Rtv_code_info.Gain; *compressed_size = raw_size; *outbuf = Rtv_capture_raw_buffer; } // NOTE : if we are not doing compression, then the raw buffer and size are going to be the same as the compressed // buffer and size // assign the raw buffer and size if necessary if(outbuf_raw != NULL){ *outbuf_raw = Rtv_capture_raw_buffer; } if(outbuf_size_raw != NULL){ *outbuf_size_raw = raw_size; } } ///////////////////////////////////////////////////////////////////////////////////////////////// // DECODE/PLAYBACK ///////////////////////////////////////////////////////////////////////////////////////////////// // return the size that the decode buffer should be int rtvoice_get_decode_buffer_size() { return Decode_buffer_size; } // uncompress the data into PCM format void rtvoice_uncompress(unsigned char *data_in, int size_in, double gain, unsigned char *data_out, int size_out) { Rtv_code_info.Gain = gain; Decode(&Rtv_code_info, data_in, data_out, size_in, size_out); } // Close down the real-time voice playback system void rtvoice_close_playback() { if ( Decode_buffer ) { free(Decode_buffer); Decode_buffer=NULL; } if ( Rtv_playback_uncompressed_buffer ) { free(Rtv_playback_uncompressed_buffer); Rtv_playback_uncompressed_buffer=NULL; } Rtv_playback_inited=0; } // Clear out the Rtv_output_buffers[] array void rtvoice_reset_out_buffers() { int i; for ( i=0; i<MAX_RTV_OUT_BUFFERS; i++ ) { Rtv_output_buffers[i].flags=0; Rtv_output_buffers[i].ds_handle=-1; } } // Init the playback portion of the real-time voice system // exit: 0 => success // !0 => failure, playback not possible int rtvoice_init_playback() { rtv_format *rtvf=NULL; if ( !Rtv_playback_inited ) { rtvoice_reset_out_buffers(); Rtv_playback_format=0; rtvf = &Rtv_formats[Rtv_playback_format]; Decode_buffer_size = rtvf->frequency * (RTV_BUFFER_TIME) * fl2i(rtvf->bits_per_sample/8.0f); if ( Decode_buffer ) { free(Decode_buffer); Decode_buffer=NULL; } Decode_buffer = (unsigned char*)malloc(Decode_buffer_size); Assert(Decode_buffer); if ( Rtv_playback_uncompressed_buffer ) { free(Rtv_playback_uncompressed_buffer); Rtv_playback_uncompressed_buffer=NULL; } Rtv_playback_uncompressed_buffer_size=Decode_buffer_size; Rtv_playback_uncompressed_buffer = (unsigned char*)malloc(Rtv_playback_uncompressed_buffer_size); Assert(Rtv_playback_uncompressed_buffer); InitDecoder(1, Decode_buffer); Rtv_playback_inited=1; } return 0; } int rtvoice_find_free_output_buffer() { int i; for ( i=0; i<MAX_RTV_OUT_BUFFERS; i++ ) { if ( !(Rtv_output_buffers[i].flags & RTV_OUT_FLAG_USED) ) { break; } } if ( i == MAX_RTV_OUT_BUFFERS ) { return -1; } Rtv_output_buffers[i].flags |= RTV_OUT_FLAG_USED; return i; } // Open a stream for real-time voice output int rtvoice_create_playback_buffer() { int index; rtv_format *rtvf=NULL; rtvf = &Rtv_formats[Rtv_playback_format]; index = rtvoice_find_free_output_buffer(); if ( index == -1 ) { Int3(); return -1; } Rtv_output_buffers[index].ds_handle = ds_create_buffer(rtvf->frequency, rtvf->bits_per_sample, 1, RTV_BUFFER_TIME); if ( Rtv_output_buffers[index].ds_handle == -1 ) { return -1; } return 0; } void rtvoice_stop_playback(int index) { Assert(index >=0 && index < MAX_RTV_OUT_BUFFERS); if ( Rtv_output_buffers[index].flags & RTV_OUT_FLAG_USED ) { if ( Rtv_output_buffers[index].ds_handle != -1 ) { ds_stop_easy(Rtv_output_buffers[index].ds_handle); } } } void rtvoice_stop_playback_all() { int i; for ( i = 0; i < MAX_RTV_OUT_BUFFERS; i++ ) { rtvoice_stop_playback(i); } } // Close a stream that was opened for real-time voice output void rtvoice_free_playback_buffer(int index) { Assert(index >=0 && index < MAX_RTV_OUT_BUFFERS); if ( Rtv_output_buffers[index].flags & RTV_OUT_FLAG_USED ) { Rtv_output_buffers[index].flags=0; if ( Rtv_output_buffers[index].ds_handle != -1 ) { ds_stop_easy(Rtv_output_buffers[index].ds_handle); ds_unload_buffer(Rtv_output_buffers[index].ds_handle, -1); } Rtv_output_buffers[index].ds_handle=-1; } } // Play compressed sound data // exit: >=0 => handle to playing sound // -1 => error, voice not played int rtvoice_play_compressed(int index, unsigned char *data, int size, int uncompressed_size, double gain) { int ds_handle, rval; ds_handle = Rtv_output_buffers[index].ds_handle; // Stop any currently playing voice output ds_stop_easy(ds_handle); Assert(uncompressed_size <= Rtv_playback_uncompressed_buffer_size); // uncompress the data into PCM format if ( Rtv_do_compression ) { rtvoice_uncompress(data, size, gain, Rtv_playback_uncompressed_buffer, uncompressed_size); } // lock the data in if ( ds_lock_data(ds_handle, Rtv_playback_uncompressed_buffer, uncompressed_size) ) { return -1; } // play the voice rval = ds_play(ds_handle, -1, -100, DS_MUST_PLAY, ds_convert_volume(Master_voice_volume), 0, 0); return rval; } // Play uncompressed (raw) sound data // exit: >=0 => handle to playing sound // -1 => error, voice not played int rtvoice_play_uncompressed(int index, unsigned char *data, int size) { int ds_handle, rval; ds_handle = Rtv_output_buffers[index].ds_handle; // Stop any currently playing voice output ds_stop_easy(ds_handle); // lock the data in if ( ds_lock_data(ds_handle, data, size) ) { return -1; } // play the voice rval = ds_play(ds_handle, -1, -100, DS_MUST_PLAY, ds_convert_volume(Master_voice_volume), 0, 0); return rval; }
[ [ [ 1, 719 ] ] ]
f7b122e1cde01ab746e64a704ccb107b41fd7658
57574cc7192ea8564bd630dbc2a1f1c4806e4e69
/Poker/Servidor/OpNoIr.h
ccae65fafbf129a8676420f38512396bb106b03c
[]
no_license
natlehmann/taller-2010-2c-poker
3c6821faacccd5afa526b36026b2b153a2e471f9
d07384873b3705d1cd37448a65b04b4105060f19
refs/heads/master
2016-09-05T23:43:54.272182
2010-11-17T11:48:00
2010-11-17T11:48:00
32,321,142
0
0
null
null
null
null
UTF-8
C++
false
false
280
h
#ifndef _OP_NOIR_H_ #define _OP_NOIR_H_ #include "Operacion.h" using namespace std; class OpNoIr : public Operacion { protected: virtual bool ejecutarAccion(Socket* socket); public: OpNoIr(int idCliente); virtual ~OpNoIr(void); }; #endif //_OP_NOIR_H_
[ "[email protected]@a9434d28-8610-e991-b0d0-89a272e3a296" ]
[ [ [ 1, 19 ] ] ]
41543732d33d4c8ad9547d0df408fe0dc37298aa
f2cbdee1dfdcad7b77c597e1af5f40ad83bad4aa
/MyJava/JRex/src/native/JRexEmbeddingSiteWindow2Impl.cpp
efa291ae98ad104c700c5f4a734552588c3065ad
[]
no_license
jdouglas71/Examples
d03d9effc414965991ca5b46fbcf808a9dd6fe6d
b7829b131581ea3a62cebb2ae35571ec8263fd61
refs/heads/master
2021-01-18T14:23:56.900005
2011-04-07T19:34:04
2011-04-07T19:34:04
1,578,581
1
1
null
null
null
null
UTF-8
C++
false
false
5,305
cpp
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor(s): * C.N Medappa <[email protected]><> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the NPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the NPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "JRexWindow.h" #include "JRex_JNI_WindowEvent.h" using namespace JRex_JNI_WindowEvent; NS_IMETHODIMP JRexWindow::SetDimensions(PRUint32 flags, PRInt32 x, PRInt32 y, PRInt32 cx, PRInt32 cy){ JREX_LOGLN("nsIEmbeddingSiteWindow2Impl -->SetDimensions()-->**** flags<"<<flags<<"> x<"<<x<<"> y<"<<y<<"> cx<"<<cx<<"> cy<"<<cy<<">****") if(mBeingDisposed)return NS_OK; if (flags & nsIEmbeddingSiteWindow::DIM_FLAGS_POSITION && (flags & (nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_INNER | nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_OUTER))) { #if defined(MOZ_WIDGET_GTK) || defined(MOZ_WIDGET_GTK2) if(NOT_NULL(mMainWnd)){ gtk_widget_set_usize((GtkWidget*)mMainWnd, cx, cy); gdk_window_move_resize(((GtkWidget*)mMainWnd)->window,x, y, cx, cy); } #endif return mBaseWindow->SetPositionAndSize(x, y, cx, cy, PR_TRUE); } else if (flags & nsIEmbeddingSiteWindow::DIM_FLAGS_POSITION) { #if defined(MOZ_WIDGET_GTK) || defined(MOZ_WIDGET_GTK2) if(NOT_NULL(mMainWnd)) gdk_window_move(((GtkWidget*)mMainWnd)->window,x, y); #endif return mBaseWindow->SetPosition(x, y); } else if (flags & (nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_INNER | nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_OUTER)) { #if defined(MOZ_WIDGET_GTK) || defined(MOZ_WIDGET_GTK2) if(NOT_NULL(mMainWnd)){ gtk_widget_set_usize((GtkWidget*)mMainWnd, cx, cy); gdk_window_resize(((GtkWidget*)mMainWnd)->window, cx, cy); } #endif return mBaseWindow->SetSize(cx, cy, PR_TRUE); } return NS_ERROR_INVALID_ARG; } NS_IMETHODIMP JRexWindow::GetDimensions(PRUint32 flags, PRInt32 *x, PRInt32 *y, PRInt32 *cx, PRInt32 *cy){ if(mBeingDisposed)return NS_OK; JREX_LOGLN("nsIEmbeddingSiteWindow2Impl -->GetDimensions()") if (flags & nsIEmbeddingSiteWindow::DIM_FLAGS_POSITION && (flags & (nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_INNER | nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_OUTER))) { return mBaseWindow->GetPositionAndSize(x, y, cx, cy); } else if (flags & nsIEmbeddingSiteWindow::DIM_FLAGS_POSITION) { return mBaseWindow->GetPosition(x, y); } else if (flags & (nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_INNER | nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_OUTER)) { return mBaseWindow->GetSize(cx, cy); } return NS_ERROR_INVALID_ARG; } NS_IMETHODIMP JRexWindow::SetFocus(){ if(mBeingDisposed)return NS_OK; return mBaseWindow->SetFocus(); } NS_IMETHODIMP JRexWindow::GetVisibility(PRBool *aVisibility){ return IsVisible(aVisibility); } NS_IMETHODIMP JRexWindow::SetVisibility(PRBool aVisibility){ return SetVisible(aVisibility); } NS_IMETHODIMP JRexWindow::GetTitle(PRUnichar * *aTitle){ *aTitle = mTitle; return NS_OK; } NS_IMETHODIMP JRexWindow::SetTitle(const PRUnichar * aTitle){ JREX_LOGLN("SetTitle()--> **** Title <"<<aTitle<<">****") nsEmbedString titleStr(aTitle); mTitle = ToNewUnicode(titleStr); char* temp=ToNewUTF8String(titleStr); JREX_LOGLN("SetTitle()--> *** Title is <"<<temp<<"> ***") WindowTitleEventParam *wParm=new WindowTitleEventParam; if(IS_NULL(wParm))return NS_ERROR_OUT_OF_MEMORY; wParm->target=NS_PTR_TO_INT32(this); wParm->winEventType=WIN_SET_TITLE_EVENT; wParm->title=temp; nsresult rv=fireEvent(wParm,PR_FALSE,nsnull); JREX_LOGLN("SetTitle()--> *** fireEvent rv<"<<rv<<"> ***") return rv; } NS_IMETHODIMP JRexWindow::GetSiteWindow(void * *aSiteWindow){ *aSiteWindow = mMainWnd; return NS_OK; } NS_IMETHODIMP JRexWindow::Blur(){ JREX_LOGLN("Blur()--> **** @@@@@@@ nsIEmbeddingSiteWindow2Impl @@@@@ ****") return NS_OK; }
[ [ [ 1, 141 ] ] ]
52b86033ac5c63c17d1c69367de9462cabafce20
ce87282d8a4674b2c67bde4b7dbac165af73715b
/src/propgrid/xh_propgrid.cpp
5def2940b9a0c813209273626b5722e6278bf11c
[]
no_license
Bluehorn/wxPython
b07ffc08b99561d222940753ab5074c6a85ba962
7b04577e268c59f727d4aadea6ba8a78638e3c1b
refs/heads/master
2021-01-24T04:20:21.023240
2007-08-15T21:01:30
2016-01-23T00:46:02
8,418,914
0
1
null
null
null
null
UTF-8
C++
false
false
9,577
cpp
///////////////////////////////////////////////////////////////////////////// // Name: xh_propgrid.cpp // Purpose: XRC resource for wxPropertyGrid // Author: Jaakko Salli // Modified by: // Created: May-16-2007 // RCS-ID: $Id: // Copyright: (c) Jaakko Salli // Licence: wxWindows license ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif /* NOTE: This source file is *not* included in the wxPropertyGrid library (to prevent xrc-lib dependency). To use this code, you will need to separately add src/xh_propgrid.cpp to your application. */ #if wxUSE_XRC && wxCHECK_VERSION(2,8,0) #include <wx/propgrid/propgrid.h> #include <wx/propgrid/xh_propgrid.h> #ifndef WX_PRECOMP #include "wx/intl.h" #endif #if wxCHECK_VERSION(2,9,0) #define wxXML_GetAttribute(A,B,C) (A->GetAttribute(B,C)) #else #define wxXML_GetAttribute(A,B,C) (A->GetPropVal(B,C)) #endif IMPLEMENT_DYNAMIC_CLASS(wxPropertyGridXmlHandler, wxXmlResourceHandler) wxPropertyGridXmlHandler::wxPropertyGridXmlHandler() :wxXmlResourceHandler(), m_manager(NULL), m_populator(NULL) { XRC_ADD_STYLE(wxTAB_TRAVERSAL); XRC_ADD_STYLE(wxPG_AUTO_SORT); XRC_ADD_STYLE(wxPG_HIDE_CATEGORIES); XRC_ADD_STYLE(wxPG_BOLD_MODIFIED); XRC_ADD_STYLE(wxPG_SPLITTER_AUTO_CENTER); XRC_ADD_STYLE(wxPG_TOOLTIPS); XRC_ADD_STYLE(wxPG_HIDE_MARGIN); XRC_ADD_STYLE(wxPG_STATIC_SPLITTER); XRC_ADD_STYLE(wxPG_LIMITED_EDITING); XRC_ADD_STYLE(wxPG_TOOLBAR); XRC_ADD_STYLE(wxPG_DESCRIPTION); XRC_ADD_STYLE(wxPG_EX_INIT_NOCAT); XRC_ADD_STYLE(wxPG_EX_HELP_AS_TOOLTIPS); XRC_ADD_STYLE(wxPG_EX_AUTO_UNSPECIFIED_VALUES); XRC_ADD_STYLE(wxPG_EX_WRITEONLY_BUILTIN_ATTRIBUTES); XRC_ADD_STYLE(wxPG_EX_NO_FLAT_TOOLBAR); XRC_ADD_STYLE(wxPG_EX_MODE_BUTTONS); #if wxPG_COMPATIBILITY_1_2_0 XRC_ADD_STYLE(wxPG_EX_TRADITIONAL_VALIDATORS); #endif AddWindowStyles(); } class wxPropertyGridXrcPopulator : public wxPropertyGridPopulator { public: wxPropertyGridXrcPopulator( wxPropertyGridXmlHandler* handler ) : wxPropertyGridPopulator() { m_xrcHandler = handler; m_prevPopulator = m_xrcHandler->m_populator; } virtual ~wxPropertyGridXrcPopulator() { m_xrcHandler->m_populator = m_prevPopulator; } virtual void DoScanForChildren() { m_xrcHandler->CreateChildrenPrivately(m_pg, NULL); } protected: wxPropertyGridXmlHandler* m_xrcHandler; wxPropertyGridPopulator* m_prevPopulator; }; void wxPropertyGridXmlHandler::InitPopulator() { wxPropertyGridXrcPopulator* populator = new wxPropertyGridXrcPopulator(this); m_populator = populator; } void wxPropertyGridXmlHandler::PopulatePage( wxPropertyGridState* state ) { wxString sColumns(wxT("columns")); if ( HasParam(sColumns) ) state->SetColumnCount( GetLong(sColumns) ); m_populator->SetState( state ); m_populator->AddChildren( state->DoGetRoot() ); } void wxPropertyGridXmlHandler::DonePopulator() { delete m_populator; } void wxPropertyGridXmlHandler::HandlePropertyGridParams() { wxString sVW(wxT("virtualwidth")); if ( HasParam(sVW) ) { int vw = GetLong(sVW); m_pg->SetVirtualWidth(vw); } } wxObject *wxPropertyGridXmlHandler::DoCreateResource() { const wxXmlNode* node = m_node; wxString nodeName = node->GetName(); wxString emptyString; if ( nodeName == wxT("property") ) { // property wxString clas = wxXML_GetAttribute(node, wxT("class"), emptyString); wxString label; wxString sLabel(wxT("label")); if ( HasParam(sLabel) ) label = GetText(sLabel); wxString name; wxString sName(wxT("name")); if ( HasParam(sName) ) name = GetText(sName); else name = label; wxString sValue(wxT("value")); wxString value; wxString* pValue = NULL; if ( HasParam(sValue) ) { value = GetText(sValue); pValue = &value; } wxXmlNode* choicesNode = GetParamNode(wxT("choices")); wxPGChoices choices; if ( choicesNode ) { choices = m_populator->ParseChoices( choicesNode->GetNodeContent(), wxXML_GetAttribute(choicesNode, wxT("id"), emptyString)); } wxPGProperty* property = m_populator->Add( clas, label, name, pValue, &choices ); if ( !property ) return NULL; wxString sFlags(wxT("flags")); wxString flags; if ( HasParam(sFlags) ) property->SetFlagsFromString( GetText(sFlags) ); wxString sTip(wxT("tip")); if ( HasParam(sTip) ) property->SetHelpString(GetText(sTip)); if ( property->GetChildCount() ) { wxPGProperty* pwc = property; // FIXME wxString sExpanded(wxT("expanded")); if ( HasParam(sExpanded) ) pwc->SetExpanded(GetBool(sExpanded)); } // Need to call AddChildren even for non-parent properties for attributes and such m_populator->AddChildren(property); } else if ( nodeName == wxT("attribute") ) { // attribute wxString s1 = wxXML_GetAttribute(node, wxT("name"), emptyString); if ( s1.length() ) { m_populator->AddAttribute( s1, wxXML_GetAttribute(node, wxT("type"), emptyString), node->GetNodeContent() ); } } else if( m_class == wxT("wxPropertyGrid")) { XRC_MAKE_INSTANCE(control, wxPropertyGrid) control->Create(m_parentAsWindow, GetID(), GetPosition(), GetSize(), GetStyle(), GetName()); m_pg = control; HandlePropertyGridParams(); InitPopulator(); PopulatePage(control->GetState()); DonePopulator(); SetupWindow(control); return control; } else if ( nodeName == wxT("choices") ) { // choices // // Add choices list outside of a property m_populator->ParseChoices( node->GetNodeContent(), wxXML_GetAttribute(node, wxT("id"), emptyString)); } else if ( nodeName == wxT("splitterpos") ) { // splitterpos wxASSERT(m_populator); wxString sIndex = wxXML_GetAttribute(node, wxT("index"), emptyString); long index; if ( !sIndex.ToLong(&index, 10) ) index = 0; wxString s = node->GetNodeContent(); long pos; if ( wxPropertyGridPopulator::ToLongPCT(s, &pos, m_pg->GetClientSize().x) ) m_populator->GetState()->DoSetSplitterPosition( pos, index, false ); } #if wxPG_INCLUDE_MANAGER else if ( nodeName == wxT("page") ) { // page wxASSERT(m_manager); wxString label; wxString sLabel(wxT("label")); if ( HasParam(sLabel) ) label = GetText(sLabel); else label = wxString::Format(_("Page %i"),(int)(m_manager->GetPageCount()+1)); m_manager->AddPage(label); wxPropertyGridState* state = m_manager->GetPage(m_manager->GetPageCount()-1); PopulatePage(state); } else if( m_class == wxT("wxPropertyGridManager")) { XRC_MAKE_INSTANCE(control, wxPropertyGridManager) control->Create(m_parentAsWindow, GetID(), GetPosition(), GetSize(), GetStyle(), GetName()); wxPropertyGridManager* oldManager = m_manager; m_manager = control; m_pg = control->GetGrid(); HandlePropertyGridParams(); InitPopulator(); CreateChildrenPrivately(control, NULL); DonePopulator(); m_manager = oldManager; SetupWindow(control); return control; } #endif else { wxASSERT( false ); } return NULL; } bool wxPropertyGridXmlHandler::CanHandle(wxXmlNode *node) { #if wxCHECK_VERSION(2,7,0) #define fOurClass(A) IsOfClass(node, A) #else #define fOurClass(A) (wxXML_GetAttribute(node, wxT("class"), wxEmptyString) == A) #endif wxString name = node->GetName(); return ( ( m_populator && ( name == wxT("property") || name == wxT("attribute") || name == wxT("choices") || name == wxT("splitterpos") ) ) || (m_manager && name == wxT("page")) || (!m_populator && fOurClass(wxT("wxPropertyGrid"))) #if wxPG_INCLUDE_MANAGER || (!m_populator && fOurClass(wxT("wxPropertyGridManager"))) #endif ); } #endif // wxUSE_XRC && wxCHECK_VERSION(2,8,0)
[ [ [ 1, 333 ] ] ]
65b40da6069fa173c8312073b6da86e16fd2fc78
f2cbdee1dfdcad7b77c597e1af5f40ad83bad4aa
/MyJava/JRex/src/native/jni/JRexNavigation.h
b8d5da8d83823c9be8e884ef7c41fd4617a68819
[]
no_license
jdouglas71/Examples
d03d9effc414965991ca5b46fbcf808a9dd6fe6d
b7829b131581ea3a62cebb2ae35571ec8263fd61
refs/heads/master
2021-01-18T14:23:56.900005
2011-04-07T19:34:04
2011-04-07T19:34:04
1,578,581
1
1
null
null
null
null
UTF-8
C++
false
false
1,902
h
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor(s): * C.N Medappa <[email protected]><> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the NPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the NPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "JRex_JNI_Util.h" class JRexNavigationFields{ public : static jclass hisCls; static jclass hisEntryCls; static jmethodID arryListAddID; static jmethodID hisCID; static jmethodID hisEntryCID; static jfieldID hisListID; static jfieldID hisMaxLenID; };
[ [ [ 1, 43 ] ] ]
d747e87e30bb99999e8d8279b09e5236e310715f
60292928893c169892a3c2c8b50c8847755bcb5a
/scraps/Bayer.cpp
d183be111ba892a0ec4be24113483ebc1d4c74f1
[]
no_license
powderluv/libcvd-cl
bf041868fb5a1818fda0333e5a56cf39c2c15a69
601c74471d92ecd4b1627e12ff178280a4bbeece
refs/heads/master
2021-01-18T00:07:27.471443
2011-12-02T03:23:20
2011-12-02T03:23:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
58,323
cpp
/***************************************************************************** * * * PrimeSense Sensor 5.0 Alpha * * Copyright (C) 2010 PrimeSense Ltd. * * * * This file is part of PrimeSense Common. * * * * PrimeSense Sensor is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as published * * by the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * PrimeSense Sensor 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 Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with PrimeSense Sensor. If not, see <http://www.gnu.org/licenses/>. * * * *****************************************************************************/ /***************************************************************************** * Edited 12.04.2011 by Raphael Dumusc * * Incorporated ROS code for improved Bayer Pattern to RGB conversion. * *****************************************************************************/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include "Bayer.h" #include <math.h> //--------------------------------------------------------------------------- // Global Variables //--------------------------------------------------------------------------- XnUInt8 Gamma[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255}; //--------------------------------------------------------------------------- // Code //--------------------------------------------------------------------------- void BayerUpdateGamma(float fGammaCorr) { for(XnUInt32 iG = 0; iG < 256;++iG) Gamma[iG] = XnUInt32(255*pow(XnDouble(iG)/255.0,(XnDouble)fGammaCorr) + 0.5); } /* static inline void WriteRGB(XnUInt8 *pBuffer, XnUInt8 nRed, XnUInt8 nGreen, XnUInt8 nBlue) { pBuffer[BAYER_RED] = Gamma[nRed]; pBuffer[BAYER_GREEN] = Gamma[nGreen]; pBuffer[BAYER_BLUE] = Gamma[nBlue]; } void Bayer2RGB888(const XnUInt8* pBayerImage, XnUInt8* pRGBImage, XnUInt32 nXRes, XnUInt32 nYRes, XnUInt32 nDownSampleStep, XnUInt32 nBadPixels) { XnUInt8 nRed; XnUInt8 nGreen; XnUInt8 nBlue; const XnUInt8* pBayer; XnUInt8* pRGB; //if (nBadPixels > 1) //{ //nBadPixels = 1; //} XnInt32 BAYER_LINE_LENGTH = nXRes; XnInt32 BAYER_LINE_LENGTH2 = BAYER_LINE_LENGTH*2; XnInt32 BAYER_RGB_LINE_LENGTH = nXRes*BAYER_BPP; XnInt32 BAYER_RGB_LINE_LENGTH2 = BAYER_RGB_LINE_LENGTH*2; const XnUInt8* pCurrBayer; XnUInt8* pCurrRGB; XnUInt32 nColCount; XnUInt32 nTotalColsCount = (nXRes-2) / 2; XnUInt32 nTotalRowsCount = (nYRes-4) / 2; pBayer = pBayerImage + BAYER_LINE_LENGTH - nBadPixels; pRGB = pRGBImage + BAYER_RGB_LINE_LENGTH; do { pCurrBayer = pBayer+ 1; pCurrRGB = pRGB + BAYER_BPP; nColCount = nTotalColsCount; do { nRed = ((XnUInt32)pCurrBayer[-BAYER_LINE_LENGTH]+pCurrBayer[BAYER_LINE_LENGTH]) / 2; nBlue = ((XnUInt32)pCurrBayer[-1]+pCurrBayer[1]) / 2; WriteRGB(pCurrRGB+0, nRed, pCurrBayer[0], nBlue); nRed = ((XnUInt32)pCurrBayer[-BAYER_LINE_LENGTH+2]+pCurrBayer[BAYER_LINE_LENGTH+2]) / 2; nGreen = ((XnUInt32)pCurrBayer[0]+pCurrBayer[2]) / 2; WriteRGB(pCurrRGB+BAYER_BPP, nRed, nGreen, pCurrBayer[1]); nGreen = ((XnUInt32)pCurrBayer[BAYER_LINE_LENGTH-1]+pCurrBayer[BAYER_LINE_LENGTH+1]) / 2; nBlue = ((XnUInt32)pCurrBayer[BAYER_LINE_LENGTH2-1]+pCurrBayer[BAYER_LINE_LENGTH2+1]) / 2; WriteRGB(pCurrRGB+BAYER_RGB_LINE_LENGTH, pCurrBayer[BAYER_LINE_LENGTH], nGreen, nBlue); nRed = ((XnUInt32)pCurrBayer[BAYER_LINE_LENGTH]+pCurrBayer[BAYER_LINE_LENGTH+2]) / 2; nBlue = ((XnUInt32)pCurrBayer[1]+pCurrBayer[BAYER_LINE_LENGTH2+1]) / 2; WriteRGB(pCurrRGB+BAYER_RGB_LINE_LENGTH+BAYER_BPP, nRed, pCurrBayer[BAYER_LINE_LENGTH+1], nBlue); pCurrBayer += 2; pCurrRGB += 2*BAYER_BPP; } while (--nColCount); pBayer += BAYER_LINE_LENGTH2; pRGB += BAYER_RGB_LINE_LENGTH2; } while (--nTotalRowsCount); } */ /* The ROS bayer pattern to RGB conversion Modified to be used in Avin's mod of the Primesense driver. Original code available here: http://www.ros.org/doc/api/openni_camera/html/openni__image__bayer__grbg_8cpp_source.html */ /* * Software License Agreement (BSD License) * * Copyright (c) 2011 2011 Willow Garage, Inc. * Suat Gedikli <[email protected]> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include <sstream> #include <iostream> #define AVG(a,b) (((int)(a) + (int)(b)) >> 1) #define AVG3(a,b,c) (((int)(a) + (int)(b) + (int)(c)) / 3) #define AVG4(a,b,c,d) (((int)(a) + (int)(b) + (int)(c) + (int)(d)) >> 2) #define WAVG4(a,b,c,d,x,y) ( ( ((int)(a) + (int)(b)) * (int)(x) + ((int)(c) + (int)(d)) * (int)(y) ) / ( 2 * ((int)(x) + (int(y))) ) ) using namespace std; typedef enum { Bilinear = 0, EdgeAware, EdgeAwareWeighted } DebayeringMethod; void fillRGB(unsigned width, unsigned height, const XnUInt8* bayer_pixel, unsigned char* rgb_buffer, DebayeringMethod debayering_method, XnUInt32 nDownSampleStep) { unsigned rgb_line_step = width * 3; // padding skip for destination image unsigned rgb_line_skip = rgb_line_step - width * 3; if (nDownSampleStep == 1) { //register const XnUInt8 *bayer_pixel = image_md_->Data (); register unsigned yIdx, xIdx; int bayer_line_step = width; int bayer_line_step2 = width << 1; if (debayering_method == Bilinear) { // first two pixel values for first two lines // Bayer 0 1 2 // 0 G r g // line_step b g b // line_step2 g r g rgb_buffer[3] = rgb_buffer[0] = bayer_pixel[1]; // red pixel rgb_buffer[1] = bayer_pixel[0]; // green pixel rgb_buffer[rgb_line_step + 2] = rgb_buffer[2] = bayer_pixel[bayer_line_step]; // blue; // Bayer 0 1 2 // 0 g R g // line_step b g b // line_step2 g r g //rgb_pixel[3] = bayer_pixel[1]; rgb_buffer[4] = AVG3 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 5] = rgb_buffer[5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); // BGBG line // Bayer 0 1 2 // 0 g r g // line_step B g b // line_step2 g r g rgb_buffer[rgb_line_step + 3] = rgb_buffer[rgb_line_step ] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 1] = AVG3 (bayer_pixel[0], bayer_pixel[bayer_line_step + 1], bayer_pixel[bayer_line_step2]); //rgb_pixel[rgb_line_step + 2] = bayer_pixel[line_step]; // pixel (1, 1) 0 1 2 // 0 g r g // line_step b G b // line_step2 g r g //rgb_pixel[rgb_line_step + 3] = AVG( bayer_pixel[1] , bayer_pixel[line_step2+1] ); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; //rgb_pixel[rgb_line_step + 5] = AVG( bayer_pixel[line_step] , bayer_pixel[line_step+2] ); rgb_buffer += 6; bayer_pixel += 2; // rest of the first two lines for (xIdx = 2; xIdx < width - 2; xIdx += 2, rgb_buffer += 6, bayer_pixel += 2) { // GRGR line // Bayer -1 0 1 2 // 0 r G r g // line_step g b g b // line_step2 r g r g rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[2] = bayer_pixel[bayer_line_step + 1]; // Bayer -1 0 1 2 // 0 r g R g // line_step g b g b // line_step2 r g r g rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG3 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 5] = rgb_buffer[5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); // BGBG line // Bayer -1 0 1 2 // 0 r g r g // line_step g B g b // line_step2 r g r g rgb_buffer[rgb_line_step ] = AVG4 (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1], bayer_pixel[-1], bayer_pixel[bayer_line_step2 - 1]); rgb_buffer[rgb_line_step + 1] = AVG4 (bayer_pixel[0], bayer_pixel[bayer_line_step2], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 2 // 0 r g r g // line_step g b G b // line_step2 r g r g rgb_buffer[rgb_line_step + 3] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; //rgb_pixel[rgb_line_step + 5] = AVG( bayer_pixel[line_step] , bayer_pixel[line_step+2] ); } // last two pixel values for first two lines // GRGR line // Bayer -1 0 1 // 0 r G r // line_step g b g // line_step2 r g r rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[rgb_line_step + 5] = rgb_buffer[rgb_line_step + 2] = rgb_buffer[5] = rgb_buffer[2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 // 0 r g R // line_step g b g // line_step2 r g r rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG (bayer_pixel[0], bayer_pixel[bayer_line_step + 1]); //rgb_pixel[5] = bayer_pixel[line_step]; // BGBG line // Bayer -1 0 1 // 0 r g r // line_step g B g // line_step2 r g r rgb_buffer[rgb_line_step ] = AVG4 (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1], bayer_pixel[-1], bayer_pixel[bayer_line_step2 - 1]); rgb_buffer[rgb_line_step + 1] = AVG4 (bayer_pixel[0], bayer_pixel[bayer_line_step2], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); //rgb_pixel[rgb_line_step + 2] = bayer_pixel[line_step]; // Bayer -1 0 1 // 0 r g r // line_step g b G // line_step2 r g r rgb_buffer[rgb_line_step + 3] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; //rgb_pixel[rgb_line_step + 5] = bayer_pixel[line_step]; bayer_pixel += bayer_line_step + 2; rgb_buffer += rgb_line_step + 6 + rgb_line_skip; // main processing for (yIdx = 2; yIdx < height - 2; yIdx += 2) { // first two pixel values // Bayer 0 1 2 // -1 b g b // 0 G r g // line_step b g b // line_step2 g r g rgb_buffer[3] = rgb_buffer[0] = bayer_pixel[1]; // red pixel rgb_buffer[1] = bayer_pixel[0]; // green pixel rgb_buffer[2] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[-bayer_line_step]); // blue; // Bayer 0 1 2 // -1 b g b // 0 g R g // line_step b g b // line_step2 g r g //rgb_pixel[3] = bayer_pixel[1]; rgb_buffer[4] = AVG4 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1], bayer_pixel[1 - bayer_line_step]); rgb_buffer[5] = AVG4 (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2], bayer_pixel[-bayer_line_step], bayer_pixel[2 - bayer_line_step]); // BGBG line // Bayer 0 1 2 // 0 g r g // line_step B g b // line_step2 g r g rgb_buffer[rgb_line_step + 3] = rgb_buffer[rgb_line_step ] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 1] = AVG3 (bayer_pixel[0], bayer_pixel[bayer_line_step + 1], bayer_pixel[bayer_line_step2]); rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // pixel (1, 1) 0 1 2 // 0 g r g // line_step b G b // line_step2 g r g //rgb_pixel[rgb_line_step + 3] = AVG( bayer_pixel[1] , bayer_pixel[line_step2+1] ); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; rgb_buffer[rgb_line_step + 5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); rgb_buffer += 6; bayer_pixel += 2; // continue with rest of the line for (xIdx = 2; xIdx < width - 2; xIdx += 2, rgb_buffer += 6, bayer_pixel += 2) { // GRGR line // Bayer -1 0 1 2 // -1 g b g b // 0 r G r g // line_step g b g b // line_step2 r g r g rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[2] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[-bayer_line_step]); // Bayer -1 0 1 2 // -1 g b g b // 0 r g R g // line_step g b g b // line_step2 r g r g rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG4 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1], bayer_pixel[1 - bayer_line_step]); rgb_buffer[5] = AVG4 (bayer_pixel[-bayer_line_step], bayer_pixel[2 - bayer_line_step], bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); // BGBG line // Bayer -1 0 1 2 // -1 g b g b // 0 r g r g // line_step g B g b // line_step2 r g r g rgb_buffer[rgb_line_step ] = AVG4 (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1], bayer_pixel[-1], bayer_pixel[bayer_line_step2 - 1]); rgb_buffer[rgb_line_step + 1] = AVG4 (bayer_pixel[0], bayer_pixel[bayer_line_step2], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 2 // -1 g b g b // 0 r g r g // line_step g b G b // line_step2 r g r g rgb_buffer[rgb_line_step + 3] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; rgb_buffer[rgb_line_step + 5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); } // last two pixels of the line // last two pixel values for first two lines // GRGR line // Bayer -1 0 1 // 0 r G r // line_step g b g // line_step2 r g r rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[rgb_line_step + 5] = rgb_buffer[rgb_line_step + 2] = rgb_buffer[5] = rgb_buffer[2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 // 0 r g R // line_step g b g // line_step2 r g r rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG (bayer_pixel[0], bayer_pixel[bayer_line_step + 1]); //rgb_pixel[5] = bayer_pixel[line_step]; // BGBG line // Bayer -1 0 1 // 0 r g r // line_step g B g // line_step2 r g r rgb_buffer[rgb_line_step ] = AVG4 (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1], bayer_pixel[-1], bayer_pixel[bayer_line_step2 - 1]); rgb_buffer[rgb_line_step + 1] = AVG4 (bayer_pixel[0], bayer_pixel[bayer_line_step2], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); //rgb_pixel[rgb_line_step + 2] = bayer_pixel[line_step]; // Bayer -1 0 1 // 0 r g r // line_step g b G // line_step2 r g r rgb_buffer[rgb_line_step + 3] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; //rgb_pixel[rgb_line_step + 5] = bayer_pixel[line_step]; bayer_pixel += bayer_line_step + 2; rgb_buffer += rgb_line_step + 6 + rgb_line_skip; } //last two lines // Bayer 0 1 2 // -1 b g b // 0 G r g // line_step b g b rgb_buffer[rgb_line_step + 3] = rgb_buffer[rgb_line_step ] = rgb_buffer[3] = rgb_buffer[0] = bayer_pixel[1]; // red pixel rgb_buffer[1] = bayer_pixel[0]; // green pixel rgb_buffer[rgb_line_step + 2] = rgb_buffer[2] = bayer_pixel[bayer_line_step]; // blue; // Bayer 0 1 2 // -1 b g b // 0 g R g // line_step b g b //rgb_pixel[3] = bayer_pixel[1]; rgb_buffer[4] = AVG4 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1], bayer_pixel[1 - bayer_line_step]); rgb_buffer[5] = AVG4 (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2], bayer_pixel[-bayer_line_step], bayer_pixel[2 - bayer_line_step]); // BGBG line // Bayer 0 1 2 // -1 b g b // 0 g r g // line_step B g b //rgb_pixel[rgb_line_step ] = bayer_pixel[1]; rgb_buffer[rgb_line_step + 1] = AVG (bayer_pixel[0], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // Bayer 0 1 2 // -1 b g b // 0 g r g // line_step b G b //rgb_pixel[rgb_line_step + 3] = AVG( bayer_pixel[1] , bayer_pixel[line_step2+1] ); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; rgb_buffer[rgb_line_step + 5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); rgb_buffer += 6; bayer_pixel += 2; // rest of the last two lines for (xIdx = 2; xIdx < width - 2; xIdx += 2, rgb_buffer += 6, bayer_pixel += 2) { // GRGR line // Bayer -1 0 1 2 // -1 g b g b // 0 r G r g // line_step g b g b rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[2] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[-bayer_line_step]); // Bayer -1 0 1 2 // -1 g b g b // 0 r g R g // line_step g b g b rgb_buffer[rgb_line_step + 3] = rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG4 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1], bayer_pixel[1 - bayer_line_step]); rgb_buffer[5] = AVG4 (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2], bayer_pixel[-bayer_line_step], bayer_pixel[-bayer_line_step + 2]); // BGBG line // Bayer -1 0 1 2 // -1 g b g b // 0 r g r g // line_step g B g b rgb_buffer[rgb_line_step ] = AVG (bayer_pixel[-1], bayer_pixel[1]); rgb_buffer[rgb_line_step + 1] = AVG3 (bayer_pixel[0], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 2 // -1 g b g b // 0 r g r g // line_step g b G b //rgb_pixel[rgb_line_step + 3] = bayer_pixel[1]; rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; rgb_buffer[rgb_line_step + 5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); } // last two pixel values for first two lines // GRGR line // Bayer -1 0 1 // -1 g b g // 0 r G r // line_step g b g rgb_buffer[rgb_line_step ] = rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[5] = rgb_buffer[2] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[-bayer_line_step]); // Bayer -1 0 1 // -1 g b g // 0 r g R // line_step g b g rgb_buffer[rgb_line_step + 3] = rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG3 (bayer_pixel[0], bayer_pixel[bayer_line_step + 1], bayer_pixel[-bayer_line_step + 1]); //rgb_pixel[5] = AVG( bayer_pixel[line_step], bayer_pixel[-line_step] ); // BGBG line // Bayer -1 0 1 // -1 g b g // 0 r g r // line_step g B g //rgb_pixel[rgb_line_step ] = AVG2( bayer_pixel[-1], bayer_pixel[1] ); rgb_buffer[rgb_line_step + 1] = AVG3 (bayer_pixel[0], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 5] = rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 // -1 g b g // 0 r g r // line_step g b G //rgb_pixel[rgb_line_step + 3] = bayer_pixel[1]; rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; //rgb_pixel[rgb_line_step + 5] = bayer_pixel[line_step]; } else if (debayering_method == EdgeAware) { int dh, dv; // first two pixel values for first two lines // Bayer 0 1 2 // 0 G r g // line_step b g b // line_step2 g r g rgb_buffer[3] = rgb_buffer[0] = bayer_pixel[1]; // red pixel rgb_buffer[1] = bayer_pixel[0]; // green pixel rgb_buffer[rgb_line_step + 2] = rgb_buffer[2] = bayer_pixel[bayer_line_step]; // blue; // Bayer 0 1 2 // 0 g R g // line_step b g b // line_step2 g r g //rgb_pixel[3] = bayer_pixel[1]; rgb_buffer[4] = AVG3 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 5] = rgb_buffer[5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); // BGBG line // Bayer 0 1 2 // 0 g r g // line_step B g b // line_step2 g r g rgb_buffer[rgb_line_step + 3] = rgb_buffer[rgb_line_step ] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 1] = AVG3 (bayer_pixel[0], bayer_pixel[bayer_line_step + 1], bayer_pixel[bayer_line_step2]); //rgb_pixel[rgb_line_step + 2] = bayer_pixel[line_step]; // pixel (1, 1) 0 1 2 // 0 g r g // line_step b G b // line_step2 g r g //rgb_pixel[rgb_line_step + 3] = AVG( bayer_pixel[1] , bayer_pixel[line_step2+1] ); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; //rgb_pixel[rgb_line_step + 5] = AVG( bayer_pixel[line_step] , bayer_pixel[line_step+2] ); rgb_buffer += 6; bayer_pixel += 2; // rest of the first two lines for (xIdx = 2; xIdx < width - 2; xIdx += 2, rgb_buffer += 6, bayer_pixel += 2) { // GRGR line // Bayer -1 0 1 2 // 0 r G r g // line_step g b g b // line_step2 r g r g rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[2] = bayer_pixel[bayer_line_step + 1]; // Bayer -1 0 1 2 // 0 r g R g // line_step g b g b // line_step2 r g r g rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG3 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 5] = rgb_buffer[5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); // BGBG line // Bayer -1 0 1 2 // 0 r g r g // line_step g B g b // line_step2 r g r g rgb_buffer[rgb_line_step ] = AVG4 (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1], bayer_pixel[-1], bayer_pixel[bayer_line_step2 - 1]); rgb_buffer[rgb_line_step + 1] = AVG4 (bayer_pixel[0], bayer_pixel[bayer_line_step2], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 2 // 0 r g r g // line_step g b G b // line_step2 r g r g rgb_buffer[rgb_line_step + 3] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; //rgb_pixel[rgb_line_step + 5] = AVG( bayer_pixel[line_step] , bayer_pixel[line_step+2] ); } // last two pixel values for first two lines // GRGR line // Bayer -1 0 1 // 0 r G r // line_step g b g // line_step2 r g r rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[rgb_line_step + 5] = rgb_buffer[rgb_line_step + 2] = rgb_buffer[5] = rgb_buffer[2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 // 0 r g R // line_step g b g // line_step2 r g r rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG (bayer_pixel[0], bayer_pixel[bayer_line_step + 1]); //rgb_pixel[5] = bayer_pixel[line_step]; // BGBG line // Bayer -1 0 1 // 0 r g r // line_step g B g // line_step2 r g r rgb_buffer[rgb_line_step ] = AVG4 (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1], bayer_pixel[-1], bayer_pixel[bayer_line_step2 - 1]); rgb_buffer[rgb_line_step + 1] = AVG4 (bayer_pixel[0], bayer_pixel[bayer_line_step2], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); //rgb_pixel[rgb_line_step + 2] = bayer_pixel[line_step]; // Bayer -1 0 1 // 0 r g r // line_step g b G // line_step2 r g r rgb_buffer[rgb_line_step + 3] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; //rgb_pixel[rgb_line_step + 5] = bayer_pixel[line_step]; bayer_pixel += bayer_line_step + 2; rgb_buffer += rgb_line_step + 6 + rgb_line_skip; // main processing for (yIdx = 2; yIdx < height - 2; yIdx += 2) { // first two pixel values // Bayer 0 1 2 // -1 b g b // 0 G r g // line_step b g b // line_step2 g r g rgb_buffer[3] = rgb_buffer[0] = bayer_pixel[1]; // red pixel rgb_buffer[1] = bayer_pixel[0]; // green pixel rgb_buffer[2] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[-bayer_line_step]); // blue; // Bayer 0 1 2 // -1 b g b // 0 g R g // line_step b g b // line_step2 g r g //rgb_pixel[3] = bayer_pixel[1]; rgb_buffer[4] = AVG4 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1], bayer_pixel[1 - bayer_line_step]); rgb_buffer[5] = AVG4 (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2], bayer_pixel[-bayer_line_step], bayer_pixel[2 - bayer_line_step]); // BGBG line // Bayer 0 1 2 // 0 g r g // line_step B g b // line_step2 g r g rgb_buffer[rgb_line_step + 3] = rgb_buffer[rgb_line_step ] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 1] = AVG3 (bayer_pixel[0], bayer_pixel[bayer_line_step + 1], bayer_pixel[bayer_line_step2]); rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // pixel (1, 1) 0 1 2 // 0 g r g // line_step b G b // line_step2 g r g //rgb_pixel[rgb_line_step + 3] = AVG( bayer_pixel[1] , bayer_pixel[line_step2+1] ); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; rgb_buffer[rgb_line_step + 5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); rgb_buffer += 6; bayer_pixel += 2; // continue with rest of the line for (xIdx = 2; xIdx < width - 2; xIdx += 2, rgb_buffer += 6, bayer_pixel += 2) { // GRGR line // Bayer -1 0 1 2 // -1 g b g b // 0 r G r g // line_step g b g b // line_step2 r g r g rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[2] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[-bayer_line_step]); // Bayer -1 0 1 2 // -1 g b g b // 0 r g R g // line_step g b g b // line_step2 r g r g dh = abs (bayer_pixel[0] - bayer_pixel[2]); dv = abs (bayer_pixel[-bayer_line_step + 1] - bayer_pixel[bayer_line_step + 1]); if (dh > dv) rgb_buffer[4] = AVG (bayer_pixel[-bayer_line_step + 1], bayer_pixel[bayer_line_step + 1]); else if (dv > dh) rgb_buffer[4] = AVG (bayer_pixel[0], bayer_pixel[2]); else rgb_buffer[4] = AVG4 (bayer_pixel[-bayer_line_step + 1], bayer_pixel[bayer_line_step + 1], bayer_pixel[0], bayer_pixel[2]); rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[5] = AVG4 (bayer_pixel[-bayer_line_step], bayer_pixel[2 - bayer_line_step], bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); // BGBG line // Bayer -1 0 1 2 // -1 g b g b // 0 r g r g // line_step g B g b // line_step2 r g r g rgb_buffer[rgb_line_step ] = AVG4 (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1], bayer_pixel[-1], bayer_pixel[bayer_line_step2 - 1]); rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; dv = abs (bayer_pixel[0] - bayer_pixel[bayer_line_step2]); dh = abs (bayer_pixel[bayer_line_step - 1] - bayer_pixel[bayer_line_step + 1]); if (dv > dh) rgb_buffer[rgb_line_step + 1] = AVG (bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); else if (dh > dv) rgb_buffer[rgb_line_step + 1] = AVG (bayer_pixel[0], bayer_pixel[bayer_line_step2]); else rgb_buffer[rgb_line_step + 1] = AVG4 (bayer_pixel[0], bayer_pixel[bayer_line_step2], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); // Bayer -1 0 1 2 // -1 g b g b // 0 r g r g // line_step g b G b // line_step2 r g r g rgb_buffer[rgb_line_step + 3] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; rgb_buffer[rgb_line_step + 5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); } // last two pixels of the line // last two pixel values for first two lines // GRGR line // Bayer -1 0 1 // 0 r G r // line_step g b g // line_step2 r g r rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[rgb_line_step + 5] = rgb_buffer[rgb_line_step + 2] = rgb_buffer[5] = rgb_buffer[2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 // 0 r g R // line_step g b g // line_step2 r g r rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG (bayer_pixel[0], bayer_pixel[bayer_line_step + 1]); //rgb_pixel[5] = bayer_pixel[line_step]; // BGBG line // Bayer -1 0 1 // 0 r g r // line_step g B g // line_step2 r g r rgb_buffer[rgb_line_step ] = AVG4 (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1], bayer_pixel[-1], bayer_pixel[bayer_line_step2 - 1]); rgb_buffer[rgb_line_step + 1] = AVG4 (bayer_pixel[0], bayer_pixel[bayer_line_step2], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); //rgb_pixel[rgb_line_step + 2] = bayer_pixel[line_step]; // Bayer -1 0 1 // 0 r g r // line_step g b G // line_step2 r g r rgb_buffer[rgb_line_step + 3] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; //rgb_pixel[rgb_line_step + 5] = bayer_pixel[line_step]; bayer_pixel += bayer_line_step + 2; rgb_buffer += rgb_line_step + 6 + rgb_line_skip; } //last two lines // Bayer 0 1 2 // -1 b g b // 0 G r g // line_step b g b rgb_buffer[rgb_line_step + 3] = rgb_buffer[rgb_line_step ] = rgb_buffer[3] = rgb_buffer[0] = bayer_pixel[1]; // red pixel rgb_buffer[1] = bayer_pixel[0]; // green pixel rgb_buffer[rgb_line_step + 2] = rgb_buffer[2] = bayer_pixel[bayer_line_step]; // blue; // Bayer 0 1 2 // -1 b g b // 0 g R g // line_step b g b //rgb_pixel[3] = bayer_pixel[1]; rgb_buffer[4] = AVG4 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1], bayer_pixel[1 - bayer_line_step]); rgb_buffer[5] = AVG4 (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2], bayer_pixel[-bayer_line_step], bayer_pixel[2 - bayer_line_step]); // BGBG line // Bayer 0 1 2 // -1 b g b // 0 g r g // line_step B g b //rgb_pixel[rgb_line_step ] = bayer_pixel[1]; rgb_buffer[rgb_line_step + 1] = AVG (bayer_pixel[0], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // Bayer 0 1 2 // -1 b g b // 0 g r g // line_step b G b //rgb_pixel[rgb_line_step + 3] = AVG( bayer_pixel[1] , bayer_pixel[line_step2+1] ); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; rgb_buffer[rgb_line_step + 5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); rgb_buffer += 6; bayer_pixel += 2; // rest of the last two lines for (xIdx = 2; xIdx < width - 2; xIdx += 2, rgb_buffer += 6, bayer_pixel += 2) { // GRGR line // Bayer -1 0 1 2 // -1 g b g b // 0 r G r g // line_step g b g b rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[2] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[-bayer_line_step]); // Bayer -1 0 1 2 // -1 g b g b // 0 r g R g // line_step g b g b rgb_buffer[rgb_line_step + 3] = rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG4 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1], bayer_pixel[1 - bayer_line_step]); rgb_buffer[5] = AVG4 (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2], bayer_pixel[-bayer_line_step], bayer_pixel[-bayer_line_step + 2]); // BGBG line // Bayer -1 0 1 2 // -1 g b g b // 0 r g r g // line_step g B g b rgb_buffer[rgb_line_step ] = AVG (bayer_pixel[-1], bayer_pixel[1]); rgb_buffer[rgb_line_step + 1] = AVG3 (bayer_pixel[0], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 2 // -1 g b g b // 0 r g r g // line_step g b G b //rgb_pixel[rgb_line_step + 3] = bayer_pixel[1]; rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; rgb_buffer[rgb_line_step + 5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); } // last two pixel values for first two lines // GRGR line // Bayer -1 0 1 // -1 g b g // 0 r G r // line_step g b g rgb_buffer[rgb_line_step ] = rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[5] = rgb_buffer[2] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[-bayer_line_step]); // Bayer -1 0 1 // -1 g b g // 0 r g R // line_step g b g rgb_buffer[rgb_line_step + 3] = rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG3 (bayer_pixel[0], bayer_pixel[bayer_line_step + 1], bayer_pixel[-bayer_line_step + 1]); //rgb_pixel[5] = AVG( bayer_pixel[line_step], bayer_pixel[-line_step] ); // BGBG line // Bayer -1 0 1 // -1 g b g // 0 r g r // line_step g B g //rgb_pixel[rgb_line_step ] = AVG2( bayer_pixel[-1], bayer_pixel[1] ); rgb_buffer[rgb_line_step + 1] = AVG3 (bayer_pixel[0], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 5] = rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 // -1 g b g // 0 r g r // line_step g b G //rgb_pixel[rgb_line_step + 3] = bayer_pixel[1]; rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; //rgb_pixel[rgb_line_step + 5] = bayer_pixel[line_step]; } else if (debayering_method == EdgeAwareWeighted) { int dh, dv; // first two pixel values for first two lines // Bayer 0 1 2 // 0 G r g // line_step b g b // line_step2 g r g rgb_buffer[3] = rgb_buffer[0] = bayer_pixel[1]; // red pixel rgb_buffer[1] = bayer_pixel[0]; // green pixel rgb_buffer[rgb_line_step + 2] = rgb_buffer[2] = bayer_pixel[bayer_line_step]; // blue; // Bayer 0 1 2 // 0 g R g // line_step b g b // line_step2 g r g //rgb_pixel[3] = bayer_pixel[1]; rgb_buffer[4] = AVG3 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 5] = rgb_buffer[5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); // BGBG line // Bayer 0 1 2 // 0 g r g // line_step B g b // line_step2 g r g rgb_buffer[rgb_line_step + 3] = rgb_buffer[rgb_line_step ] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 1] = AVG3 (bayer_pixel[0], bayer_pixel[bayer_line_step + 1], bayer_pixel[bayer_line_step2]); //rgb_pixel[rgb_line_step + 2] = bayer_pixel[line_step]; // pixel (1, 1) 0 1 2 // 0 g r g // line_step b G b // line_step2 g r g //rgb_pixel[rgb_line_step + 3] = AVG( bayer_pixel[1] , bayer_pixel[line_step2+1] ); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; //rgb_pixel[rgb_line_step + 5] = AVG( bayer_pixel[line_step] , bayer_pixel[line_step+2] ); rgb_buffer += 6; bayer_pixel += 2; // rest of the first two lines for (xIdx = 2; xIdx < width - 2; xIdx += 2, rgb_buffer += 6, bayer_pixel += 2) { // GRGR line // Bayer -1 0 1 2 // 0 r G r g // line_step g b g b // line_step2 r g r g rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[2] = bayer_pixel[bayer_line_step + 1]; // Bayer -1 0 1 2 // 0 r g R g // line_step g b g b // line_step2 r g r g rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG3 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 5] = rgb_buffer[5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); // BGBG line // Bayer -1 0 1 2 // 0 r g r g // line_step g B g b // line_step2 r g r g rgb_buffer[rgb_line_step ] = AVG4 (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1], bayer_pixel[-1], bayer_pixel[bayer_line_step2 - 1]); rgb_buffer[rgb_line_step + 1] = AVG4 (bayer_pixel[0], bayer_pixel[bayer_line_step2], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 2 // 0 r g r g // line_step g b G b // line_step2 r g r g rgb_buffer[rgb_line_step + 3] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; //rgb_pixel[rgb_line_step + 5] = AVG( bayer_pixel[line_step] , bayer_pixel[line_step+2] ); } // last two pixel values for first two lines // GRGR line // Bayer -1 0 1 // 0 r G r // line_step g b g // line_step2 r g r rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[rgb_line_step + 5] = rgb_buffer[rgb_line_step + 2] = rgb_buffer[5] = rgb_buffer[2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 // 0 r g R // line_step g b g // line_step2 r g r rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG (bayer_pixel[0], bayer_pixel[bayer_line_step + 1]); //rgb_pixel[5] = bayer_pixel[line_step]; // BGBG line // Bayer -1 0 1 // 0 r g r // line_step g B g // line_step2 r g r rgb_buffer[rgb_line_step ] = AVG4 (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1], bayer_pixel[-1], bayer_pixel[bayer_line_step2 - 1]); rgb_buffer[rgb_line_step + 1] = AVG4 (bayer_pixel[0], bayer_pixel[bayer_line_step2], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); //rgb_pixel[rgb_line_step + 2] = bayer_pixel[line_step]; // Bayer -1 0 1 // 0 r g r // line_step g b G // line_step2 r g r rgb_buffer[rgb_line_step + 3] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; //rgb_pixel[rgb_line_step + 5] = bayer_pixel[line_step]; bayer_pixel += bayer_line_step + 2; rgb_buffer += rgb_line_step + 6 + rgb_line_skip; // main processing for (yIdx = 2; yIdx < height - 2; yIdx += 2) { // first two pixel values // Bayer 0 1 2 // -1 b g b // 0 G r g // line_step b g b // line_step2 g r g rgb_buffer[3] = rgb_buffer[0] = bayer_pixel[1]; // red pixel rgb_buffer[1] = bayer_pixel[0]; // green pixel rgb_buffer[2] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[-bayer_line_step]); // blue; // Bayer 0 1 2 // -1 b g b // 0 g R g // line_step b g b // line_step2 g r g //rgb_pixel[3] = bayer_pixel[1]; rgb_buffer[4] = AVG4 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1], bayer_pixel[1 - bayer_line_step]); rgb_buffer[5] = AVG4 (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2], bayer_pixel[-bayer_line_step], bayer_pixel[2 - bayer_line_step]); // BGBG line // Bayer 0 1 2 // 0 g r g // line_step B g b // line_step2 g r g rgb_buffer[rgb_line_step + 3] = rgb_buffer[rgb_line_step ] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 1] = AVG3 (bayer_pixel[0], bayer_pixel[bayer_line_step + 1], bayer_pixel[bayer_line_step2]); rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // pixel (1, 1) 0 1 2 // 0 g r g // line_step b G b // line_step2 g r g //rgb_pixel[rgb_line_step + 3] = AVG( bayer_pixel[1] , bayer_pixel[line_step2+1] ); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; rgb_buffer[rgb_line_step + 5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); rgb_buffer += 6; bayer_pixel += 2; // continue with rest of the line for (xIdx = 2; xIdx < width - 2; xIdx += 2, rgb_buffer += 6, bayer_pixel += 2) { // GRGR line // Bayer -1 0 1 2 // -1 g b g b // 0 r G r g // line_step g b g b // line_step2 r g r g rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[2] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[-bayer_line_step]); // Bayer -1 0 1 2 // -1 g b g b // 0 r g R g // line_step g b g b // line_step2 r g r g dh = abs (bayer_pixel[0] - bayer_pixel[2]); dv = abs (bayer_pixel[-bayer_line_step + 1] - bayer_pixel[bayer_line_step + 1]); if (dv == 0 && dh == 0) rgb_buffer[4] = AVG4 (bayer_pixel[1 - bayer_line_step], bayer_pixel[1 + bayer_line_step], bayer_pixel[0], bayer_pixel[2]); else rgb_buffer[4] = WAVG4 (bayer_pixel[1 - bayer_line_step], bayer_pixel[1 + bayer_line_step], bayer_pixel[0], bayer_pixel[2], dh, dv); rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[5] = AVG4 (bayer_pixel[-bayer_line_step], bayer_pixel[2 - bayer_line_step], bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); // BGBG line // Bayer -1 0 1 2 // -1 g b g b // 0 r g r g // line_step g B g b // line_step2 r g r g rgb_buffer[rgb_line_step ] = AVG4 (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1], bayer_pixel[-1], bayer_pixel[bayer_line_step2 - 1]); rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; dv = abs (bayer_pixel[0] - bayer_pixel[bayer_line_step2]); dh = abs (bayer_pixel[bayer_line_step - 1] - bayer_pixel[bayer_line_step + 1]); if (dv == 0 && dh == 0) rgb_buffer[rgb_line_step + 1] = AVG4 (bayer_pixel[0], bayer_pixel[bayer_line_step2], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); else rgb_buffer[rgb_line_step + 1] = WAVG4 (bayer_pixel[0], bayer_pixel[bayer_line_step2], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1], dh, dv); // Bayer -1 0 1 2 // -1 g b g b // 0 r g r g // line_step g b G b // line_step2 r g r g rgb_buffer[rgb_line_step + 3] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; rgb_buffer[rgb_line_step + 5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); } // last two pixels of the line // last two pixel values for first two lines // GRGR line // Bayer -1 0 1 // 0 r G r // line_step g b g // line_step2 r g r rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[rgb_line_step + 5] = rgb_buffer[rgb_line_step + 2] = rgb_buffer[5] = rgb_buffer[2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 // 0 r g R // line_step g b g // line_step2 r g r rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG (bayer_pixel[0], bayer_pixel[bayer_line_step + 1]); //rgb_pixel[5] = bayer_pixel[line_step]; // BGBG line // Bayer -1 0 1 // 0 r g r // line_step g B g // line_step2 r g r rgb_buffer[rgb_line_step ] = AVG4 (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1], bayer_pixel[-1], bayer_pixel[bayer_line_step2 - 1]); rgb_buffer[rgb_line_step + 1] = AVG4 (bayer_pixel[0], bayer_pixel[bayer_line_step2], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); //rgb_pixel[rgb_line_step + 2] = bayer_pixel[line_step]; // Bayer -1 0 1 // 0 r g r // line_step g b G // line_step2 r g r rgb_buffer[rgb_line_step + 3] = AVG (bayer_pixel[1], bayer_pixel[bayer_line_step2 + 1]); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; //rgb_pixel[rgb_line_step + 5] = bayer_pixel[line_step]; bayer_pixel += bayer_line_step + 2; rgb_buffer += rgb_line_step + 6 + rgb_line_skip; } //last two lines // Bayer 0 1 2 // -1 b g b // 0 G r g // line_step b g b rgb_buffer[rgb_line_step + 3] = rgb_buffer[rgb_line_step ] = rgb_buffer[3] = rgb_buffer[0] = bayer_pixel[1]; // red pixel rgb_buffer[1] = bayer_pixel[0]; // green pixel rgb_buffer[rgb_line_step + 2] = rgb_buffer[2] = bayer_pixel[bayer_line_step]; // blue; // Bayer 0 1 2 // -1 b g b // 0 g R g // line_step b g b //rgb_pixel[3] = bayer_pixel[1]; rgb_buffer[4] = AVG4 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1], bayer_pixel[1 - bayer_line_step]); rgb_buffer[5] = AVG4 (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2], bayer_pixel[-bayer_line_step], bayer_pixel[2 - bayer_line_step]); // BGBG line // Bayer 0 1 2 // -1 b g b // 0 g r g // line_step B g b //rgb_pixel[rgb_line_step ] = bayer_pixel[1]; rgb_buffer[rgb_line_step + 1] = AVG (bayer_pixel[0], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // Bayer 0 1 2 // -1 b g b // 0 g r g // line_step b G b //rgb_pixel[rgb_line_step + 3] = AVG( bayer_pixel[1] , bayer_pixel[line_step2+1] ); rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; rgb_buffer[rgb_line_step + 5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); rgb_buffer += 6; bayer_pixel += 2; // rest of the last two lines for (xIdx = 2; xIdx < width - 2; xIdx += 2, rgb_buffer += 6, bayer_pixel += 2) { // GRGR line // Bayer -1 0 1 2 // -1 g b g b // 0 r G r g // line_step g b g b rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[2] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[-bayer_line_step]); // Bayer -1 0 1 2 // -1 g b g b // 0 r g R g // line_step g b g b rgb_buffer[rgb_line_step + 3] = rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG4 (bayer_pixel[0], bayer_pixel[2], bayer_pixel[bayer_line_step + 1], bayer_pixel[1 - bayer_line_step]); rgb_buffer[5] = AVG4 (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2], bayer_pixel[-bayer_line_step], bayer_pixel[-bayer_line_step + 2]); // BGBG line // Bayer -1 0 1 2 // -1 g b g b // 0 r g r g // line_step g B g b rgb_buffer[rgb_line_step ] = AVG (bayer_pixel[-1], bayer_pixel[1]); rgb_buffer[rgb_line_step + 1] = AVG3 (bayer_pixel[0], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 2 // -1 g b g b // 0 r g r g // line_step g b G b //rgb_pixel[rgb_line_step + 3] = bayer_pixel[1]; rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; rgb_buffer[rgb_line_step + 5] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[bayer_line_step + 2]); } // last two pixel values for first two lines // GRGR line // Bayer -1 0 1 // -1 g b g // 0 r G r // line_step g b g rgb_buffer[rgb_line_step ] = rgb_buffer[0] = AVG (bayer_pixel[1], bayer_pixel[-1]); rgb_buffer[1] = bayer_pixel[0]; rgb_buffer[5] = rgb_buffer[2] = AVG (bayer_pixel[bayer_line_step], bayer_pixel[-bayer_line_step]); // Bayer -1 0 1 // -1 g b g // 0 r g R // line_step g b g rgb_buffer[rgb_line_step + 3] = rgb_buffer[3] = bayer_pixel[1]; rgb_buffer[4] = AVG3 (bayer_pixel[0], bayer_pixel[bayer_line_step + 1], bayer_pixel[-bayer_line_step + 1]); //rgb_pixel[5] = AVG( bayer_pixel[line_step], bayer_pixel[-line_step] ); // BGBG line // Bayer -1 0 1 // -1 g b g // 0 r g r // line_step g B g //rgb_pixel[rgb_line_step ] = AVG2( bayer_pixel[-1], bayer_pixel[1] ); rgb_buffer[rgb_line_step + 1] = AVG3 (bayer_pixel[0], bayer_pixel[bayer_line_step - 1], bayer_pixel[bayer_line_step + 1]); rgb_buffer[rgb_line_step + 5] = rgb_buffer[rgb_line_step + 2] = bayer_pixel[bayer_line_step]; // Bayer -1 0 1 // -1 g b g // 0 r g r // line_step g b G //rgb_pixel[rgb_line_step + 3] = bayer_pixel[1]; rgb_buffer[rgb_line_step + 4] = bayer_pixel[bayer_line_step + 1]; //rgb_pixel[rgb_line_step + 5] = bayer_pixel[line_step]; } //else // THROW_OPENNI_EXCEPTION ("Unknwon debayering method: %d", (int)debayering_method); } //Warning: Downsampling mod is untested else if (nDownSampleStep > 1) { // get each or each 2nd pixel group to find rgb values! register unsigned bayerXStep = nDownSampleStep; register unsigned bayerYSkip = (nDownSampleStep - 1) * width; // Downsampling and debayering at once register const XnUInt8* bayer_buffer = bayer_pixel; for (register unsigned yIdx = 0; yIdx < height; ++yIdx, bayer_buffer += bayerYSkip, rgb_buffer += rgb_line_skip) // skip a line { for (register unsigned xIdx = 0; xIdx < width; ++xIdx, rgb_buffer += 3, bayer_buffer += bayerXStep) { rgb_buffer[ 2 ] = bayer_buffer[ width ]; rgb_buffer[ 1 ] = AVG (bayer_buffer[0], bayer_buffer[ width + 1]); rgb_buffer[ 0 ] = bayer_buffer[ 1 ]; } } } } void Bayer2RGB888(const XnUInt8* pBayerImage, XnUInt8* pRGBImage, XnUInt32 nXRes, XnUInt32 nYRes, XnUInt32 nDownSampleStep, XnUInt32 nBadPixels) { fillRGB(nXRes, nYRes, pBayerImage, pRGBImage, DebayeringMethod(2), nDownSampleStep); // DebayeringMethod(0) == bilinear, (1) == edge aware, (2) == edge aware weighted }
[ [ [ 1, 1335 ] ] ]
2c9741867fa7008cf4edd9e2eaa2febea258904f
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Integration_WAH_&_Extraction/SMDataExtraction/TestAlgorithm/TestHolderOperations.h
a5c6556d70d0607cf5994ceaa5afb5843701145b
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
461
h
#pragma once #include "BitStreamHolder.h" #include "testalgoutil.h" #include <vector> //using namespace Algorithm; class TestHolderOperations { public: TestHolderOperations(void); ~TestHolderOperations(void); BitStreamHolder * CreateHolder(vector<int> & _attribute_array,vector<int> & _index_array); void TestHash(); void TestDifferenceOperator(); void TestHolderSuite(); void PrintBitInfoVector(vector<BitStreamHolder * > & _holder); };
[ "jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 16 ] ] ]
8d610582b719f7738cdc3b619f552387678123fb
a3d70ef949478e1957e3a548d8db0fddb9efc125
/各分块设定示例/渲染器/datafile.cpp
66b8bc77f6d0190bd80523261268936e5b0e3390
[]
no_license
SakuraSinojun/ling
fc58afea7c4dfe536cbafa93c0c6e3a7612e5281
46907e5548008d7216543bdd5b9cc058421f4eb8
refs/heads/master
2021-01-23T06:54:30.049039
2011-01-16T12:23:24
2011-01-16T12:23:24
32,323,103
0
0
null
null
null
null
GB18030
C++
false
false
5,097
cpp
#include "common.h" #include <stdio.h> #include <malloc.h> typedef enum { PIC_BMP, PIC_TGA, PIC_PNG, PIC_JPG, PIC_GIF, }PIC_TYPE; static void _parse_file(const char * filename, BYTE ** buffer, unsigned int len); static void _parse_to_bmp(const char * filename, PIC_TYPE type, BYTE ** buffer, unsigned int len); BYTE * _read_data_file(const char * filename, unsigned int & len) { FILE * fp; BYTE * buffer; if(filename == NULL) { len = -1; return NULL; } fp = fopen(filename, "rb"); if( fp == NULL ) { len = -1; return NULL; } fseek(fp, 0, SEEK_END); len = ftell(fp); if(len == 0) { fclose(fp); return NULL; } buffer = (BYTE *)malloc(len); fseek(fp, 0, SEEK_SET); if( fread(buffer, len, 1, fp) != 1 ) { common::Error("读取文件失败:[ %s ]", filename); fclose(fp); return NULL; } fclose(fp); _parse_file(filename, &buffer, len); return buffer; } static void _parse_file(const char * filename, BYTE ** buffer, unsigned int len) { int i; unsigned int l; char ext[100]; l = strlen(filename); for(i=l-1; i>=0; i--) { if( filename[i] == '.' ) { strcpy(ext, filename + i + 1); break; } } if(i == -1) { return; } //转化成小写 for(i=0; i<(int)strlen(ext); i++) { ext[i] = ext[i] | 0x20; } if(strcmp(ext, "bmp") == 0) { _parse_to_bmp(filename, PIC_BMP, buffer, len); } else if(strcmp(ext, "tga") == 0) { _parse_to_bmp(filename, PIC_BMP, buffer, len); }else if(strcmp(ext, "png") == 0) { _parse_to_bmp(filename, PIC_PNG, buffer, len); } } static void _parse_to_bmp(const char * filename, PIC_TYPE type, BYTE ** buffer, unsigned int len) { BMPHEADER bmpHeader; BMPINFOHEADER biHeader; int i; int j; int l; unsigned char * newBuffer; int offset; int r, g, b, a; int depth; int width; int height; //int bytes_per_line; switch(type) { case PIC_BMP: memcpy(&bmpHeader, *buffer, sizeof(BMPHEADER)); memcpy(&biHeader, *buffer+sizeof(BMPHEADER), sizeof(BMPINFOHEADER)); switch(biHeader.biBitCount) { case 32: case 24: depth = biHeader.biBitCount / 8; width = biHeader.biWidth; height = (int)biHeader.biHeight; offset = sizeof(BMPHEADER) + biHeader.biSize; newBuffer = (unsigned char *)malloc(offset + width * abs(height) * 4); if(height < 0) { biHeader.biHeight = (DWORD)(-height); for(j=0; j>height; j--) { for(i=0, l=0; i<width*depth; i+=depth, l+=4) { b = (*buffer)[offset - j*width*depth + i + 0]; g = (*buffer)[offset - j*width*depth + i + 1]; r = (*buffer)[offset - j*width*depth + i + 2]; a = (r + g + b)/3; newBuffer[offset - j*width*4 + l + 0] = b; newBuffer[offset - j*width*4 + l + 1] = g; newBuffer[offset - j*width*4 + l + 2] = r; newBuffer[offset - j*width*4 + l + 3] = a; } } }else{ for(j=0; j<height; j++) { for(i=0, l=0; i<width*depth; i+=depth, l+=4) { b = (*buffer)[offset + j*width*depth + i + 0]; g = (*buffer)[offset + j*width*depth + i + 1]; r = (*buffer)[offset + j*width*depth + i + 2]; a = (r + g + b)/3; newBuffer[offset + (height-j-1)*width*4 + l + 0] = b; newBuffer[offset + (height-j-1)*width*4 + l + 1] = g; newBuffer[offset + (height-j-1)*width*4 + l + 2] = r; newBuffer[offset + (height-j-1)*width*4 + l + 3] = a; } } } l = width * height * 4; bmpHeader.bfSize = offset + l; biHeader.biBitCount = 32; biHeader.biSizeImage = l; memcpy(newBuffer, &bmpHeader, sizeof(BMPHEADER)); memcpy(newBuffer+sizeof(BMPHEADER), &biHeader, sizeof(BMPINFOHEADER)); if(biHeader.biSize-sizeof(BMPINFOHEADER) != 0) { memcpy( newBuffer, buffer+sizeof(BMPHEADER)+sizeof(BMPINFOHEADER), biHeader.biSize-sizeof(BMPINFOHEADER) ); } free(*buffer); (*buffer) = newBuffer; break; default: common::Error("未处理的位图位数: [ %d ] [ %s ]", biHeader.biBitCount, filename); } break; case PIC_PNG: case PIC_TGA: case PIC_GIF: case PIC_JPG: default: common::Error("无法识别的图象类型:[ %s ].", filename); } return; } namespace res { void * loadimg(const char * filename, BMPINFOHEADER * info) { unsigned char * buffer; unsigned int len; int l; //short int depth; //int i; BMPINFOHEADER biHeader; buffer = (unsigned char *)pl::load(filename, len); if(buffer == NULL) { return NULL; } l = sizeof(BMPHEADER); memcpy(&biHeader, buffer+l, sizeof(BMPINFOHEADER)); l = sizeof(BMPHEADER) + biHeader.biSize; if(biHeader.biBitCount != 32) { return NULL; } if(info != NULL) { memcpy(info, &biHeader, sizeof(BMPINFOHEADER)); } return buffer + l; } }
[ "SakuraSinojun@f09d58f5-735d-f1c9-472e-e8791f25bd30" ]
[ [ [ 1, 275 ] ] ]
e7cee3a96203bb29195dd1f813522f42b3052bb8
d759495e105e00e35c61a91df5b56bb28f1a817d
/main.cpp
42ddf84c82688238a0b3ed41ba73cac233e56c96
[]
no_license
maxwellrocker/Luajit
3f92f5d2f47cc5ca19a4446b76f328d2da2a4709
3fc4eafdf0235c4b7b5539f103ad8c4e0f197d3a
refs/heads/master
2021-01-25T03:54:17.742507
2011-12-23T07:03:49
2011-12-23T07:03:49
3,038,888
1
0
null
null
null
null
UTF-8
C++
false
false
1,243
cpp
#include <iostream> #include "include/airplane.h" #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) #define APIEXPORT __declspec(dllexport) #else #define APIEXPORT #endif extern "C"{ #include "lua.h" #include "lualib.h" #include "lauxlib.h" } using namespace std; extern "C"{ __declspec(dllexport) const char* testfun() { return "This is a test function"; } __declspec(dllexport) airplane* new_airplane(){ return new airplane; } __declspec(dllexport) void del_airplane(airplane* air){ delete air; } __declspec(dllexport) void air_setSeat(airplane* air, int _seat){ air->setSeat(_seat); } __declspec(dllexport) int air_getSeat(airplane* air){ return air->getSeat(); } __declspec(dllexport) void air_setType(airplane* air, const char* _type){ air->setType(_type); } __declspec(dllexport) const char* air_getType(airplane* air){ return air->getType(); } } int main() { cout << "Luajit test Strat!\n" << endl; lua_State* L = luaL_newstate(); luaL_openlibs(L); luaL_dofile(L, "script.lua"); lua_close(L); return 0; }
[ [ [ 1, 59 ] ] ]
8cb5e11cdb11beeb0ddb211a96e68f95008c65ef
b22c254d7670522ec2caa61c998f8741b1da9388
/dependencies/OpenSceneGraph/include/osgGA/TrackballManipulator
8a0a771dde7edbde56879cd8e2a73a33ca221dc1
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
7,283
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library 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 * OpenSceneGraph Public License for more details. */ #ifndef OSGGA_TRACKBALLMANIPULATOR #define OSGGA_TRACKBALLMANIPULATOR 1 #include <osgGA/MatrixManipulator> #include <osg/Quat> namespace osgGA{ class OSGGA_EXPORT TrackballManipulator : public MatrixManipulator { public: TrackballManipulator(); virtual const char* className() const { return "Trackball"; } /** set the position of the matrix manipulator using a 4x4 Matrix.*/ virtual void setByMatrix(const osg::Matrixd& matrix); /** set the position of the matrix manipulator using a 4x4 Matrix.*/ virtual void setByInverseMatrix(const osg::Matrixd& matrix) { setByMatrix(osg::Matrixd::inverse(matrix)); } /** get the position of the manipulator as 4x4 Matrix.*/ virtual osg::Matrixd getMatrix() const; /** get the position of the manipulator as a inverse matrix of the manipulator, typically used as a model view matrix.*/ virtual osg::Matrixd getInverseMatrix() const; /** Get the FusionDistanceMode. Used by SceneView for setting up stereo convergence.*/ virtual osgUtil::SceneView::FusionDistanceMode getFusionDistanceMode() const { return osgUtil::SceneView::USE_FUSION_DISTANCE_VALUE; } /** Get the FusionDistanceValue. Used by SceneView for setting up stereo convergence.*/ virtual float getFusionDistanceValue() const { return _distance; } /** Attach a node to the manipulator. Automatically detaches previously attached node. setNode(NULL) detaches previously nodes. Is ignored by manipulators which do not require a reference model.*/ virtual void setNode(osg::Node*); /** Return node if attached.*/ virtual const osg::Node* getNode() const; /** Return node if attached.*/ virtual osg::Node* getNode(); /** Move the camera to the default position. May be ignored by manipulators if home functionality is not appropriate.*/ virtual void home(const GUIEventAdapter& ea,GUIActionAdapter& us); virtual void home(double); /** Start/restart the manipulator.*/ virtual void init(const GUIEventAdapter& ea,GUIActionAdapter& us); /** handle events, return true if handled, false otherwise.*/ virtual bool handle(const GUIEventAdapter& ea,GUIActionAdapter& us); /** Get the keyboard and mouse usage of this manipulator.*/ virtual void getUsage(osg::ApplicationUsage& usage) const; /** set the minimum distance (as ratio) the eye point can be zoomed in towards the center before the center is pushed forward.*/ void setMinimumZoomScale(double minimumZoomScale) { _minimumZoomScale=minimumZoomScale; } /** get the minimum distance (as ratio) the eye point can be zoomed in */ double getMinimumZoomScale() const { return _minimumZoomScale; } /** set the mouse scroll wheel zoom delta. * Range -1.0 to +1.0, -ve value inverts wheel direction and zero switches off scroll wheel. */ void setScroolWheelZoomDelta(double zoomDelta) { _zoomDelta = zoomDelta; } /** get the mouse scroll wheel zoom delta. */ double getScroolWheelZoomDelta() const { return _zoomDelta; } /** Set the center of the trackball. */ void setCenter(const osg::Vec3d& center) { _center = center; } /** Get the center of the trackball. */ const osg::Vec3d& getCenter() const { return _center; } /** Set the rotation of the trackball. */ void setRotation(const osg::Quat& rotation) { _rotation = rotation; } /** Get the rotation of the trackball. */ const osg::Quat& getRotation() const { return _rotation; } /** Set the distance of the trackball. */ void setDistance(double distance) { _distance = distance; } /** Get the distance of the trackball. */ double getDistance() const { return _distance; } /** Set the size of the trackball. */ void setTrackballSize(float size); /** Get the size of the trackball. */ float getTrackballSize() const { return _trackballSize; } /** Set the 'allow throw' flag. Releasing the mouse button while moving the camera results in a throw. */ void setAllowThrow(bool allowThrow) { _allowThrow = allowThrow; } /** Returns true if the camera can be thrown, false otherwise. This defaults to true. */ bool getAllowThrow() const { return _allowThrow; } protected: virtual ~TrackballManipulator(); /** Reset the internal GUIEvent stack.*/ void flushMouseEventStack(); /** Add the current mouse GUIEvent to internal stack.*/ void addMouseEvent(const GUIEventAdapter& ea); void computePosition(const osg::Vec3& eye,const osg::Vec3& lv,const osg::Vec3& up); /** For the give mouse movement calculate the movement of the camera. Return true is camera has moved and a redraw is required.*/ bool calcMovement(); void trackball(osg::Vec3& axis,float& angle, float p1x, float p1y, float p2x, float p2y); float tb_project_to_sphere(float r, float x, float y); /** Check the speed at which the mouse is moving. If speed is below a threshold then return false, otherwise return true.*/ bool isMouseMoving(); // Internal event stack comprising last two mouse events. osg::ref_ptr<const GUIEventAdapter> _ga_t1; osg::ref_ptr<const GUIEventAdapter> _ga_t0; osg::observer_ptr<osg::Node> _node; double _modelScale; double _minimumZoomScale; bool _allowThrow; bool _thrown; /** The approximate amount of time it is currently taking to draw a frame. * This is used to compute the delta in translation/rotation during a thrown display update. * It allows us to match an delta in position/rotation independent of the rendering frame rate. */ double _delta_frame_time; /** The time the last frame started. * Used when _rate_sensitive is true so that we can match display update rate to rotation/translation rate. */ double _last_frame_time; osg::Vec3d _center; osg::Quat _rotation; double _distance; float _trackballSize; float _zoomDelta; }; } #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 174 ] ] ]
98c899e69dccb8226bc41e2e8f20cd4040f9a4fe
65dee2b7ed8a91f952831525d78bfced5abd713f
/winmob/XfMobile_WM6/Gamepe/Gamepe.h
bc6bab890db5eb675beed41ac1326922a840d9da
[]
no_license
felixnicitin1968/XFMobile
0249f90f111f0920a423228691bcbef0ecb0ce23
4a442d0127366afa9f80bdcdaaa4569569604dac
refs/heads/master
2016-09-06T05:02:18.589338
2011-07-05T17:25:39
2011-07-05T17:25:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
531
h
// Gamepe.h : main header file for the PROJECT_NAME application // #pragma once #ifndef __AFXWIN_H__ #error "include 'stdafx.h' before including this file for PCH" #endif #ifdef POCKETPC2003_UI_MODEL #include "resourceppc.h" #endif // CGamepeApp: // See Gamepe.cpp for the implementation of this class // class CGamepeApp : public CWinApp { public: CGamepeApp(); // Overrides public: virtual BOOL InitInstance(); // Implementation DECLARE_MESSAGE_MAP() }; extern CGamepeApp theApp;
[ [ [ 1, 32 ] ] ]
59218fa3ed258dac38f78e5d59eef949518c63d5
35ca696ba88c3208722f00d9ba799b8f2e718ee3
/prog4/prog4.cpp
3dc69930211f7bc78a668be5094e5401639d110f
[]
no_license
johntalton/cs325
2f01da61f04a3cc92b1978b6becdc21827bc3094
f42763f9234e745375dad8cdba1e63224ec37ebc
refs/heads/master
2021-01-22T17:48:55.903616
1998-11-12T00:34:00
2017-08-18T17:20:08
100,732,803
0
0
null
null
null
null
ISO-8859-1
C++
false
false
587
cpp
#include "queen.h" /************************************************************************** * Main * Makes a new 8 queens prog and runs it * @version 1.0 * @author YNOP,[email protected] **************************************************************************/ void main(){ Queen q; cout << "\t \t" << "1 2 3 4 5 6 7 8\n"; cout << "\t\t" << "------------------\n"; q.placeQueen(1);// 1 is the position we want to start at. it is a // good idea to start at one cout << "\nThanks for using EightQ by ¥NöP\n"; }
[ [ [ 1, 16 ] ] ]
dfff86633475c5ab23742c9636af91258bea352b
00b979f12f13ace4e98e75a9528033636dab021d
/branches/ziis/test/cgi-bin/src/main_simple.cc
c68d018694ff40879602af1a9103cac210a6cd2a
[]
no_license
BackupTheBerlios/ziahttpd-svn
812e4278555fdd346b643534d175546bef32afd5
8c0b930d3f4a86f0622987776b5220564e89b7c8
refs/heads/master
2016-09-09T20:39:16.760554
2006-04-13T08:44:28
2006-04-13T08:44:28
40,819,288
0
0
null
null
null
null
UTF-8
C++
false
false
967
cc
// // main_simple.cc for in // // Made by texane // Login <[email protected]> // // Started on Sat Feb 18 14:51:00 2006 texane // Last update Tue Feb 21 19:21:54 2006 // #include <iostream> using namespace std; class cgi { public: cgi(); ~cgi(); void nl(); }; cgi::cgi() { cout << "<html><body>" << endl; } cgi::~cgi() { cout << "</body></html>" << endl; } void cgi::nl() { cout << "<br/>" << endl; } extern char** environ; int main(int ac, char** av) { cgi c; int n; cout << "hello from the cgi" << endl; // display argv c.nl(); cout << "** argv **" << endl; c.nl(); for (n = 0; n < ac; ++n) { cout << "[" << n << "]" << av[n] << endl; c.nl(); } // display environ c.nl(); cout << "** envn **" << endl; for (n = 0; environ[n]; ++n) { cout << "[" << n << "]" << environ[n] << endl; c.nl(); } }
[ "texane@754ce95b-6e01-0410-81d0-8774ba66fe44" ]
[ [ [ 1, 72 ] ] ]
892dab8a70f76b0697c4ad23f01dc9afb09487c3
b38ab5dcfb913569fc1e41e8deedc2487b2db491
/libraries/DX8FX/header/Rectangle.hpp
86d24d6b648e5a41a24c22db6c7b7bb9459fe33d
[]
no_license
santosh90n/Fury2
dacec86ab3972952e4cf6442b38e66b7a67edade
740a095c2daa32d33fdc24cc47145a1c13431889
refs/heads/master
2020-03-21T00:44:27.908074
2008-10-16T07:09:17
2008-10-16T07:09:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,143
hpp
/* SoftFX (Software graphics manipulation library) Copyright (C) 2003 Kevin Gadd This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace FX { class Rectangle { public: int Left, Top; int Width, Height; Rectangle() { Left = Top = 0; Width = Height = 0; } Rectangle(int X, int Y, int X2, int Y2) { Left = X; Top = Y; Width = X2 - X; Height = Y2 - Y; } Rectangle(Rectangle *Source) { if (Source) { this->Left = Source->Left; this->Top = Source->Top; this->Width = Source->Width; this->Height = Source->Height; } } inline bool empty() { return !((Width > 0) && (Height > 0)); } inline int right() { return Width + Left; } inline int right_exclusive() { if (Width > 0) { return Left + (Width - 1); } else if (Width < 0) { return Left + (Width + 1); } else { return Left; } } inline void setRight(int value) { Width = value - Left; } inline int bottom() { return Height + Top; } inline int bottom_exclusive() { if (Height > 0) { return Top + (Height - 1); } else if (Height < 0) { return Top + (Height + 1); } else { return Top; } } inline void setBottom(int value) { Height = value - Top; } inline void setValues(int x, int y, int w, int h) { Left = x; Top = y; Width = w; Height = h; } inline void setValuesAbsolute(int x, int y, int x2, int y2) { Left = x; Top = y; Width = x2 - x; Height = y2 - y; } inline void translate(int x, int y) { Left += x; Top += y; } inline void normalize() { if (Width < 0) { Left += Width; Width = -Width; } if (Height < 0) { Top += Height; Height = -Height; } } inline bool intersect(Rectangle& Rect) { if (this->Left > Rect.right()) return false; if (this->Top > Rect.bottom()) return false; if (this->right() < Rect.Left) return false; if (this->bottom() < Rect.Top) return false; return true; } }; }
[ "kevin@1af785eb-1c5d-444a-bf89-8f912f329d98" ]
[ [ [ 1, 125 ] ] ]
af9fb3ff77ec70d9c5ccced3fee01fd6234973c1
49935c0e711e0f9fda45bf9f397059fceb2b616a
/DispozPropoz/src/Form1.cpp
d37a04d48c0ccaadce4e02544a1f8afa4a5f17b7
[]
no_license
Arkezis/dispozpropoz
d8262055b64c06d4b4e0253f717abf2c99fb1e92
2db2a20e8de43f15547440f610197d87560a7213
refs/heads/master
2021-01-13T02:36:10.790311
2011-10-16T15:25:15
2011-10-16T15:25:15
32,145,788
0
0
null
null
null
null
UTF-8
C++
false
false
980
cpp
#include "Form1.h" using namespace Osp::Base; using namespace Osp::Ui; using namespace Osp::Ui::Controls; Form1::Form1(void) { } Form1::~Form1(void) { } bool Form1::Initialize() { // Construct an XML form Construct(L"IDF_FORM1"); return true; } result Form1::OnInitializing(void) { result r = E_SUCCESS; // TODO: Add your initialization code here // Get a button via resource ID __pButtonOk = static_cast<Button *>(GetControl(L"IDC_BUTTON_OK")); if (__pButtonOk != null) { __pButtonOk->SetActionId(ID_BUTTON_OK); __pButtonOk->AddActionEventListener(*this); } return r; } result Form1::OnTerminating(void) { result r = E_SUCCESS; // TODO: Add your termination code here return r; } void Form1::OnActionPerformed(const Osp::Ui::Control& source, int actionId) { switch(actionId) { case ID_BUTTON_OK: { AppLog("OK Button is clicked! \n"); } break; default: break; } }
[ "[email protected]@5a97ccac-b474-ded1-4a52-e8af14ae9110" ]
[ [ [ 1, 67 ] ] ]
6a0308452c0c9428337a306394d19112865b85ef
fb71c08b1c1e7ea4d7abc82e65b36272069993e1
/src/CBalance.cpp
a8b1b3a5f9f675d4e725a4bdcfb5d06e2599acd3
[]
no_license
cezarygerard/fpteacher
1bb4ea61bc86cbadcf47a810c8bb441f598d278a
7bdfcf7c047caa9382e22a9d26a2d381ce2d9166
refs/heads/master
2021-01-23T03:47:54.994165
2010-03-25T01:12:04
2010-03-25T01:12:04
39,897,391
0
0
null
null
null
null
UTF-8
C++
false
false
1,657
cpp
/** @file CBalance.cpp * @author Rafal Malinowski * @date 2010.03.16 * @version 0.1 * @brief * * */ #include "CBalance.hpp" CBalance::CBalance() { CLog::getInstance()->sss << "CBalance::CBalance(): Konstruktor CBalance" << endl; logs(CLog::getInstance()->sss.str(), TEMP); CInput::getInstance()->addKeyObserver(*this); x_=400; y_=650; a_=0.05f; v_=0.01f; pressedLeft_=false; pressedRight_=false; ball_ = boost::shared_ptr<CStaticObject>( new CStaticObject(x_, y_, 310.f, utils::PATH_SPRITES_MINIGAMES_BALANCE+"ball.png", 0, 0)); table_ = boost::shared_ptr<CStaticObject>( new CStaticObject(294, 660, 310.f, utils::PATH_SPRITES_MINIGAMES_BALANCE+"table.png", 0, 0)); } CBalance::~CBalance() { CLog::getInstance()->sss << "CBalance::~CBalance(): Destruktor CBalance" << endl; logs(CLog::getInstance()->sss.str(), TEMP); } void CBalance::KeyPressed(SDLKey key, bool pressed) { if(pressed && key == KEY_LEFT) { pressedLeft_=true; } else if (!pressed && key == KEY_LEFT) { pressedLeft_=false; } else if (pressed && key == KEY_RIGHT) { pressedRight_=true; } else if (!pressed && key == KEY_RIGHT) { pressedRight_=false; } else {}; } void CBalance::moveBall() { if (pressedLeft_) { a_=a_-0.005f; if ( a_>= -0.01f && a_<= 0.01f) a_=a_-0.015f; } if (pressedRight_) { a_=a_+0.005f; if ( a_>= -0.01f && a_<= 0.01f) a_=a_+0.015f; } v_=v_+a_; x_=x_+v_; y_=650+0.002f*(x_-400)*(x_-400); ball_->updatePosition(x_, y_); } bool CBalance::drawIt() { moveBall(); table_->drawIt(); ball_->drawIt(); return true; }
[ "r.malinowski88@8e29c490-c8d6-11de-b6dc-25c59a28ecba" ]
[ [ [ 1, 83 ] ] ]
edb982155a335308687d32f5494c7d50c383bc0f
c86f787916e295d20607cbffc13c524018888a0f
/tp1/codigo/ejercicio2/benchmark/poda_cant_operaciones/CmergeSort.cpp
f26b7d6bab0cae8133ef62124ec7753478680fb4
[]
no_license
federicoemartinez/algo3-2008
0039a4bc6d83ab8005fa2169b919e6c03524bad5
3b04cbea4583d76d7a97f2aee72493b4b571a77b
refs/heads/master
2020-06-05T05:56:20.127248
2008-08-04T04:59:32
2008-08-04T04:59:32
32,117,945
0
0
null
null
null
null
UTF-8
C++
false
false
1,769
cpp
#include "CmergeSort.h" CMergeSort::CMergeSort(Cosa* cos, int cantEle, int* inds){ opers = 0L; opers = opers + 2; cosas = cos; cantElem = cantEle; opers = opers + 3; for(int i = 0; i < cantEle; i++){ opers = opers + 3; inds[i] = i; } opers++; indices = inds; mergeSort(0,cantElem-1); } void CMergeSort::mergeSort(int pri, int ult) { opers++; if(pri < ult) { opers = opers + 3; int pmedio = (pri + ult)/2; mergeSort(pri, pmedio); opers++; mergeSort(pmedio+1, ult); merge(pri,ult); } } void CMergeSort::merge(int pri, int ult) { opers = opers + 7; int i,j, cont = 0; int tamano = ult - pri + 1; int pmedio = (pri + ult)/2; opers = opers + tamano; Cosa *tmp=new Cosa[tamano]; int * indicesAux = new int[tamano]; opers = opers + 3; for(i = pri; i <= pmedio; i++) { opers = opers + 4; tmp[cont] = cosas[i]; indicesAux[cont] = indices[i]; cont++; } for(i = ult; i > pmedio; i--) { opers = opers + 4; tmp[cont] = cosas[i]; indicesAux[cont] = indices[i]; cont++; } opers = opers + 5; cont = pri; for(i = 0, j = tamano - 1; i <= j;) { opers++; if(tmp[i].peso <= tmp[j].peso) { opers = opers + 2; cosas[cont]=tmp[i]; indices[cont] = indicesAux[i]; i++; } else { opers = opers + 2; cosas[cont] = tmp[j]; indices[cont] = indicesAux[j]; j--; } opers = opers + 2; cont++; } opers = opers + 2; delete[] indicesAux; delete[] tmp; }
[ "seges.ar@bfd18afd-6e49-0410-abef-09437ef2666c" ]
[ [ [ 1, 85 ] ] ]
2b431ba4c81d6ecaa895c4510d2b59a214c97864
dcff0f39e83ecab2ddcd482f3952ba317ee98f6c
/class-c++/binary-tree/legit.cpp
fc1fd0dd096b8a6e6e50b70353389b65e59155c1
[]
no_license
omgmovieslol/Code
f64048bc173e56538bb5f6164cce5d447cd7bd64
d5083b416469507b685a81d07a78fec1868644b1
refs/heads/master
2021-01-01T18:49:25.480158
2010-03-08T09:25:01
2010-03-08T09:25:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,551
cpp
#include <iostream> #include <cstdlib> #include <fstream> #define INPUT_READ 20 using namespace std; class BinarySearchTree { private: struct tree_node { tree_node* left; tree_node* right; int data; // SSN float age; // age char name[20]; // name }; tree_node* root; public: BinarySearchTree() { root = NULL; } bool isEmpty() const { return root==NULL; } void print_inorder(); void inorder(tree_node*); void print_preorder(); void preorder(tree_node*); void print_postorder(); void postorder(tree_node*); void insert(int, float, char[20]); void insert2(int, float, char[20]); void insert3(int, float, char[20]); void remove(int); }; // Smaller elements go left // larger elements go right void BinarySearchTree::insert(int d, float age, char name[20]) { tree_node* t = new tree_node; tree_node* parent; t->data = d; t->age = age; for(int i=0; i<20; i++) { t->name[i] = name[i]; } t->left = NULL; t->right = NULL; parent = NULL; // is this a new tree? if(isEmpty()) root = t; else { //Note: ALL insertions are as leaf nodes tree_node* curr; curr = root; // Find the Node's parent while(curr) { parent = curr; if(t->data > curr->data) curr = curr->right; else curr = curr->left; } if(t->data < parent->data) parent->left = t; else parent->right = t; } } void BinarySearchTree::insert2(int d, float age, char name[20]) { tree_node* t = new tree_node; tree_node* parent; t->data = d; t->age = age; for(int i=0; i<20; i++) { t->name[i] = name[i]; } t->left = NULL; t->right = NULL; parent = NULL; // is this a new tree? if(isEmpty()) root = t; else { //Note: ALL insertions are as leaf nodes tree_node* curr; curr = root; // Find the Node's parent while(curr) { parent = curr; if(t->age > curr->age) curr = curr->right; else curr = curr->left; } if(t->age < parent->age) parent->left = t; else parent->right = t; } } void BinarySearchTree::insert3(int d, float age, char name[20]) { tree_node* t = new tree_node; tree_node* parent; t->data = d; t->age = age; for(int i=0; i<20; i++) { t->name[i] = name[i]; } t->left = NULL; t->right = NULL; parent = NULL; // is this a new tree? if(isEmpty()) root = t; else { //Note: ALL insertions are as leaf nodes tree_node* curr; curr = root; // Find the Node's parent while(curr) { parent = curr; if(t->name[0] > curr->name[0]) curr = curr->right; else curr = curr->left; } if(t->name[0] < parent->name[0]) parent->left = t; else parent->right = t; } } void BinarySearchTree::remove(int d) { //Locate the element bool found = false; if(isEmpty()) { cout<<" This Tree is empty! "<<endl; return; } tree_node* curr; tree_node* parent; curr = root; while(curr != NULL) { if(curr->data == d) { found = true; break; } else { parent = curr; if(d>curr->data) curr = curr->right; else curr = curr->left; } } if(!found) { cout<<" Data not found! "<<endl; return; } // 3 cases : // 1. We're removing a leaf node // 2. We're removing a node with a single child // 3. we're removing a node with 2 children // Node with single child if((curr->left == NULL && curr->right != NULL)|| (curr->left != NULL && curr->right == NULL)) { if(curr->left == NULL && curr->right != NULL) { if(parent->left == curr) { parent->left = curr->right; delete curr; } else { parent->right = curr->right; delete curr; } } else // left child present, no right child { if(parent->left == curr) { parent->left = curr->left; delete curr; } else { parent->right = curr->left; delete curr; } } return; } //We're looking at a leaf node if( curr->left == NULL && curr->right == NULL) { if(parent->left == curr) parent->left = NULL; else parent->right = NULL; delete curr; return; } //Node with 2 children // replace node with smallest value in right subtree if (curr->left != NULL && curr->right != NULL) { tree_node* chkr; chkr = curr->right; if((chkr->left == NULL) && (chkr->right == NULL)) { curr = chkr; delete chkr; curr->right = NULL; } else // right child has children { //if the node's right child has a left child // Move all the way down left to locate smallest element if((curr->right)->left != NULL) { tree_node* lcurr; tree_node* lcurrp; lcurrp = curr->right; lcurr = (curr->right)->left; while(lcurr->left != NULL) { lcurrp = lcurr; lcurr = lcurr->left; } curr->data = lcurr->data; delete lcurr; lcurrp->left = NULL; } else { tree_node* tmp; tmp = curr->right; curr->data = tmp->data; curr->right = tmp->right; delete tmp; } } return; } } void BinarySearchTree::print_inorder() { inorder(root); } void BinarySearchTree::inorder(tree_node* p) { if(p != NULL) { if(p->left) inorder(p->left); //cout<<" "<<p->data<<" "; cout << "\nName: " << p->name << "\nSSN: " << p->data << "\nAge: " << p->age; if(p->right) inorder(p->right); } else return; } void BinarySearchTree::print_preorder() { preorder(root); } void BinarySearchTree::preorder(tree_node* p) { if(p != NULL) { //cout<<" "<<p->data<<" "; cout << "\nName: " << p->name << "\nSSN: " << p->data << "\nAge: " << p->age; if(p->left) preorder(p->left); if(p->right) preorder(p->right); } else return; } void BinarySearchTree::print_postorder() { postorder(root); } void BinarySearchTree::postorder(tree_node* p) { if(p != NULL) { if(p->left) postorder(p->left); if(p->right) postorder(p->right); //cout<<" "<<p->data<<" "; cout << "\nName: " << p->name << "\nSSN: " << p->data << "\nAge: " << p->age; } else return; } void read_file(BinarySearchTree &t, int g) { char file1[INPUT_READ]; char nametemp[20]; int temp; float agetemp; cout << "Enter the filename" << endl; cin >> file1; ifstream input1(file1); if (input1.fail()) { cout << "Error: Could not find file" << endl; system("PAUSE"); exit(1); } for(int rows=0; rows<9; rows++) { input1 >> nametemp; input1 >> temp; input1 >> agetemp; switch(g) { case 0: t.insert(temp, agetemp, nametemp); break; case 1: t.insert2(temp, agetemp, nametemp); break; case 2: t.insert3(temp, agetemp, nametemp); break; } } } int main() { BinarySearchTree b, c, d; int ch,tmp,tmp1; int g=0; read_file(b,0); read_file(c,1); read_file(d,2); while(1) { cout<<endl<<endl; cout<<" Binary Search Tree Operations "<<endl; cout<<" ----------------------------- "<<endl; cout<<" 1. In-Order Traversal - SSN "<<endl; cout<<" 2. In-Order Traversal - Age "<<endl; cout<<" 3. In-Order Traversal - Name "<<endl; //cout<<" 4. Post-Order Traversal "<<endl; //cout<<" 5. Removal "<<endl; cout<<" 6. Exit "<<endl; cout<<" Enter your choice : "; cin>>ch; switch(ch) { case 1 : cout<<" In-Order Traversal - SSN "<<endl; cout<<" -------------------"<<endl; b.print_inorder(); //cin>>tmp; //g++; //read_file(b,g); //b.read_file; //b.insert(tmp); //b.read_file; break; case 2 : cout<<endl; cout<<" In-Order Traversal - Age "<<endl; cout<<" -------------------"<<endl; c.print_inorder(); break; case 3 : cout<<endl; cout<<" In-Order Traversal - Name "<<endl; cout<<" -------------------"<<endl; d.print_inorder(); break; case 4 : cout<<endl; cout<<" Post-Order Traversal "<<endl; cout<<" --------------------"<<endl; b.print_postorder(); break; case 5 : cout<<" Enter data to be deleted : "; cin>>tmp1; b.remove(tmp1); break; case 6 : system("pause"); return 0; break; } } }
[ [ [ 1, 415 ] ] ]
8be81f973c4b18aa4481c34f548b8cd7c1b749b8
3de9e77565881674bf6b785326e85ab6e702715f
/src/math/Matrix.cpp
d0bd97a00ccb6b8274dd93108433001409b528f5
[]
no_license
adbrown85/gloop-old
1b7f6deccf16eb4326603a7558660d8875b0b745
8857b528c97cfc1fd57c02f055b94cbde6781aa1
refs/heads/master
2021-01-19T18:07:39.112088
2011-02-27T07:17:14
2011-02-27T07:17:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,663
cpp
/* * Matrix.hpp * * Author * Andrew Brown <[email protected]> */ #include "Matrix.hpp" /** Creates the identity matrix. */ Matrix::Matrix() { // Initialize size = 4; for (int i=0; i<size; i++) for (int j=0; j<size; j++) arr[i][j] = 0.0; // Set ones on diagonal for (int i=0; i<size; i++) arr[i][i] = 1.0; } /** Creates a matrix from explicit values. */ Matrix::Matrix(float a0, float a1, float a2, float a3, float b0, float b1, float b2, float b3, float c0, float c1, float c2, float c3, float d0, float d1, float d2, float d3) { // Set size size = 4; // Set positions arr[0][0] = a0; arr[0][1] = a1; arr[0][2] = a2; arr[0][3] = a3; arr[1][0] = b0; arr[1][1] = b1; arr[1][2] = b2; arr[1][3] = b3; arr[2][0] = c0; arr[2][1] = c1; arr[2][2] = c2; arr[2][3] = c3; arr[3][0] = d0; arr[3][1] = d1; arr[3][2] = d2; arr[3][3] = d3; } /** Creates an uninitialized matrix */ Matrix::Matrix(int size) { this->size = size; } /** Calculate the determinant of a part of the matrix. */ float Matrix::det(int n) const { float po, rec, ret=0; int i=0, j=0; // Ending condition if (n == 2) ret = arr[0][0]*arr[1][1] - arr[0][1]*arr[1][0]; // Recursion else { for (i=0; i<n; i++) { po = pow(-1, i+j); rec = getSubmatrix(i,j).getDeterminant(); ret += po * arr[i][j] * rec; } } // Return return ret; } /** Get the inverse of this matrix. */ Matrix Matrix::getInverse() const { float dmInv, ds, po; Matrix b; // Get determinant of entire matrix dmInv = 1 / getDeterminant(); // Calculate for (int i=0; i<size; ++i) { for (int j=0; j<size; ++j) { po = pow(-1, i+j); ds = getSubmatrix(j,i).getDeterminant(); b.arr[i][j] = po * ds * dmInv; } } // Finish b.size = size; return b; } /** @return a new matrix with row i and column j deleted. */ Matrix Matrix::getSubmatrix(int i, int j) const { int bi=0, bj=0; Matrix b; // Copy everything but row i and j for (int ai=0; ai<size; ++ai) { if (ai == i) continue; bj = 0; for (int aj=0; aj<size; ++aj) { if (aj == j) continue; b(bi,bj) = arr[ai][aj]; ++bj; } ++bi; } // Finish b.size = this->size - 1; return b; } /** @return matrix with rows and columns switched. */ Matrix Matrix::getTranspose() const { Matrix B(3); for (int i=0; i<3; ++i) { for (int j=0; j<3; ++j) { B.arr[i][j] = arr[j][i]; } } return B; } /** Returns one of the elements in the matrix. */ float& Matrix::operator()(int i, int j) { if (i < 0 || i >= size) throw BasicException("[Matrix] Index out of bounds."); if (j < 0 || j >= size) throw BasicException("[Matrix] Index out of bounds."); return arr[i][j]; } /** Returns one of the elements in the matrix. */ float Matrix::operator()(int i, int j) const { if (i < 0 || i >= size) throw BasicException("[Matrix] Index out of bounds."); if (j < 0 || j >= size) throw BasicException("[Matrix] Index out of bounds."); return arr[i][j]; } /** Multiplies two matrices together. */ Matrix operator*(const Matrix &A, const Matrix &B) { Matrix C(4); // Multiply rows of A with columns in B for (int i=0; i<C.size; ++i) { for (int j=0; j<C.size; ++j) { C.arr[i][j] = 0.0; for (int k=0; k<A.size; ++k) C.arr[i][j] += A.arr[i][k] * B.arr[k][j]; } } return C; } /** Multiplies a matrix with a vector.*/ Vec4 operator*(const Matrix &A, const Vec4 &B) { Vec4 C; // Multiply rows of A with columns in B for (int i=0; i<C.size; ++i) { C[i] = 0.0; for (int k=0; k<C.size; ++k) C[i] += A.arr[i][k] * B[k]; } return C; } /** Pretty prints the matrix to standard out. */ void Matrix::print() { // Print all entries cout << fixed << setprecision(3) << right; for (int i=0; i<size; i++) { int j=0; cout << " "; cout << "[" << setw(7) << arr[i][j]; for (j=1; j<size; j++) cout << ", " << setw(7) << arr[i][j]; cout << "]" << endl; } // Reset cout << resetiosflags(ios_base::floatfield) << setprecision(6); } /** Sets the Matrix from values in the array (column-major order). */ void Matrix::set(float array[16]) { for (int j=0; j<4; j++) for (int i=0; i<4; i++) arr[i][j] = array[j*4+i]; } /** Puts the matrix into a single-subscript array (column-major order). */ void Matrix::toArray(float *array) { for (int j=0; j<size; ++j) for (int i=0; i<size; ++i) array[j*size+i] = (*this)(i,j); }
[ [ [ 1, 2 ], [ 4, 4 ], [ 6, 9 ], [ 11, 24 ], [ 26, 30 ], [ 32, 34 ], [ 39, 41 ], [ 50, 52 ], [ 54, 72 ], [ 74, 75 ], [ 77, 79 ], [ 81, 86 ], [ 88, 96 ], [ 139, 140 ], [ 142, 142 ], [ 144, 147 ], [ 161, 161 ], [ 163, 164 ], [ 170, 171 ], [ 173, 175 ], [ 178, 178 ], [ 180, 182 ], [ 186, 190 ], [ 192, 197 ], [ 199, 209 ], [ 211, 217 ] ], [ [ 3, 3 ], [ 5, 5 ], [ 53, 53 ], [ 99, 122 ], [ 124, 125 ], [ 127, 129 ], [ 131, 136 ], [ 150, 151 ], [ 153, 153 ], [ 155, 158 ], [ 172, 172 ], [ 183, 184 ], [ 198, 198 ], [ 218, 218 ], [ 220, 223 ], [ 225, 227 ] ], [ [ 10, 10 ], [ 25, 25 ], [ 31, 31 ], [ 35, 38 ], [ 42, 49 ], [ 73, 73 ], [ 76, 76 ], [ 80, 80 ], [ 87, 87 ], [ 97, 98 ], [ 123, 123 ], [ 126, 126 ], [ 130, 130 ], [ 137, 138 ], [ 141, 141 ], [ 143, 143 ], [ 148, 149 ], [ 152, 152 ], [ 154, 154 ], [ 159, 160 ], [ 162, 162 ], [ 165, 169 ], [ 176, 177 ], [ 179, 179 ], [ 185, 185 ], [ 191, 191 ], [ 210, 210 ], [ 219, 219 ], [ 224, 224 ] ] ]
3d919dd5c0fbea8ae5592d4de2be2e36f6b136be
4758b780dad736c20ec46e3e901ecdf5a0921c04
/vm/int/SourceCode/vmConsole.h
77f190f9b8afc5731255e6610cf7e801bb13035f
[]
no_license
arbv/kronos
8f165515e77851d98b0e60b04d4b64d5bc40f3ea
4974f865161b78161011cb92223bef45930261d9
refs/heads/master
2023-08-19T18:56:36.980449
2008-08-23T19:44:08
2008-08-23T19:44:08
97,011,574
1
1
null
2017-07-12T13:31:54
2017-07-12T13:31:54
null
UTF-8
C++
false
false
689
h
#pragma once #include "SIO.h" class Console : public SIO { public: Console(int addr, int ipt); // Local machine console ctor Console(); virtual ~Console(); // SIOInbound implementation: virtual int addr(); virtual int ipt(); virtual int inpIpt(); virtual int outIpt(); virtual int inp(int addr); virtual void out(int addr, int data); // SIOOutbound implementation: virtual int busyRead(); virtual void write(char *ptr, int bytes); virtual void writeChar(char ch); virtual void onKey(bool bDown, int nVirtKey, int lKeyData, int ch); private: SIOInbound *i; SIOOutbound *o; };
[ "leo.kuznetsov@4e16752f-1752-0410-94d0-8bc3fbd73b2e" ]
[ [ [ 1, 30 ] ] ]
bda4059a32d33667389b34084e9e4f9000da02e8
9176b0fd29516d34cfd0b143e1c5c0f9e665c0ed
/CS_153_Data_Structures/assignment4/node.h
b7819b23efce6d0241e59f887dca3ec3b06031d1
[]
no_license
Mr-Anderson/james_mst_hw
70dbde80838e299f9fa9c5fcc16f4a41eec8263a
83db5f100c56e5bb72fe34d994c83a669218c962
refs/heads/master
2020-05-04T13:15:25.694979
2011-11-30T20:10:15
2011-11-30T20:10:15
2,639,602
2
0
null
null
null
null
UTF-8
C++
false
false
983
h
#ifndef NODE_H #define NODE_H ////////////////////////////////////////////////////////////////////// /// @file node.h /// @author James Anderson CS 153 Section A /// @brief Heder file for node class for assignment 4 ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @class Node /// @brief creats a struct containing data and two pointers ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @fn SNode<generic>::SNode /// @brief creates a new node /// @post node contains a variable and two pointers /// @param generic holds the type of variable the node will hold ////////////////////////////////////////////////////////////////////// template <class generic> struct Node { Node<generic> * forward; Node<generic> * back; generic data; }; #endif
[ [ [ 1, 28 ] ] ]
3f4cc6b53f64ffee4bf57fa5c5fcf5742523091b
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/TO2/TO2ClientWeaponAllocator.h
b8d25cebdbc3c3b77ad2c041f1b65c4683961cb1
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
796
h
#ifndef _TO2ClientWeaponAllocator_h_INCLUDED_ #define _TO2ClientWeaponAllocator_h_INCLUDED_ #include "ClientWeaponAllocator.h" // // This class's sole purpose is to create each // instance of the ClientWeapon. It will // take a type and match it to a class. // // See the ClientWeapon stuff for an example of its // implementation. Specifically, CCreator, // CStandardCreator, the derived classes of ClientWeaponAllocator // (CTRONClientWeaponAllocator and CTO2ClientWeaponAllocator), // and CPlayerMgr (as well as derived classes // CTRONPlayerMgr or CTO2PlayerMgr). // class CTO2ClientWeaponAllocator : public CClientWeaponAllocator { public: virtual IClientWeaponBase *New( int nClientWeaponType ) const; }; #endif //_TO2ClientWeaponAllocator_h_INCLUDED_
[ [ [ 1, 26 ] ] ]
dc8779af295011ccaa532294f80295de3d055221
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/conjurer/conjurer/src/conjurer/ninguiterraintoolgrass_cmds.cc
711c4388edad1704947b49dba2e71d76258f67fb
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
869
cc
#include "precompiled/pchconjurerapp.h" //------------------------------------------------------------------------------ // ninguiterraintoolgrass_cmds.cc // (C) 2005 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "conjurer/ninguiterraintoolgrass.h" #include "kernel/npersistserver.h" //------------------------------------------------------------------------------ /** Nebula class scripting initialization */ NSCRIPT_INITCMDS_BEGIN( nInguiTerrainToolGrass ) NSCRIPT_ADDCMD('JSGI', void, SetGrassId, 1, (int), 0, ()); NSCRIPT_ADDCMD('JGGI', int, GetGrassId, 0, (), 0, ()); NSCRIPT_INITCMDS_END() //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 20 ] ] ]
1e71f354be65f33e5b6222d7e46246bac0f27e27
21da454a8f032d6ad63ca9460656c1e04440310e
/src/net/worldscale/pimap/server/wscPsWorkingThread.h
2bc3c0ce53193a53fee8ea30ef8bc5a1d8338a75
[]
no_license
merezhang/wcpp
d9879ffb103513a6b58560102ec565b9dc5855dd
e22eb48ea2dd9eda5cd437960dd95074774b70b0
refs/heads/master
2021-01-10T06:29:42.908096
2009-08-31T09:20:31
2009-08-31T09:20:31
46,339,619
0
0
null
null
null
null
UTF-8
C++
false
false
361
h
#pragma once #include <wcpp/lang/wscThread.h> #include "wsiPsWorkingContext.h" class wscPsWorkingThread : public wscThread { private: ws_safe_ptr<wsiPsWorkingContext> m_WorkingContext; protected: wscPsWorkingThread(wsiPsWorkingContext * pWorkingContext); ~wscPsWorkingThread(void); WS_METHOD( ws_result , Run )(void); };
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 18 ] ] ]
87cd7d167f66232987222a59609d68db6ad63e4b
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2005-10-27/gerbview/files.cpp
6978d4a1743c5cca0ea05954feeff70482f23311
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
UTF-8
C++
false
false
5,481
cpp
/******************************************************/ /* Files.cp: Lecture / Sauvegarde des fichiers gerber */ /******************************************************/ #include "fctsys.h" #include "common.h" #include "gerbview.h" #include "pcbplot.h" #include "protos.h" #include "id.h" /* Routines locales */ static void LoadDCodeFile(WinEDA_GerberFrame * frame, const wxString & FullFileName, wxDC * DC); /********************************************************/ void WinEDA_GerberFrame::Files_io(wxCommandEvent& event) /********************************************************/ /* Gestion generale des commandes de lecture de fichiers */ { int id = event.GetId(); wxClientDC dc(DrawPanel); switch (id) { case ID_MENU_LOAD_FILE: case ID_LOAD_FILE: if ( ! Clear_Pcb(&dc, TRUE) ) return; LoadOneGerberFile("", &dc, 0); break; case ID_MENU_INC_LAYER_AND_APPEND_FILE: case ID_INC_LAYER_AND_APPEND_FILE: { int layer = GetScreen()->m_Active_Layer; GetScreen()->m_Active_Layer++; if( ! LoadOneGerberFile("", &dc, 0) ) GetScreen()->m_Active_Layer = layer; SetToolbars(); } break; case ID_MENU_APPEND_FILE: case ID_APPEND_FILE: LoadOneGerberFile("", &dc, 0); break; case ID_MENU_NEW_BOARD: case ID_NEW_BOARD: Clear_Pcb(&dc, TRUE); break; case ID_LOAD_FILE_1: case ID_LOAD_FILE_2: case ID_LOAD_FILE_3: case ID_LOAD_FILE_4: case ID_LOAD_FILE_5: case ID_LOAD_FILE_6: case ID_LOAD_FILE_7: case ID_LOAD_FILE_8: case ID_LOAD_FILE_9: case ID_LOAD_FILE_10: if ( ! Clear_Pcb(&dc, TRUE) ) return; LoadOneGerberFile( GetLastProject(id - ID_LOAD_FILE_1).GetData(), &dc, FALSE); break; case ID_GERBVIEW_LOAD_DRILL_FILE: DisplayError(this, _("Not yet available...")); break; case ID_GERBVIEW_LOAD_DCODE_FILE: LoadDCodeFile(this, "", &dc); break; case ID_SAVE_BOARD: case ID_MENU_SAVE_BOARD: SaveGerberFile(GetScreen()->m_FileName, &dc); break; case ID_MENU_SAVE_BOARD_AS: SaveGerberFile("", &dc); break; default: DisplayError(this, "File_io Internal Error"); break; } } /*******************************************************************************************/ int WinEDA_GerberFrame::LoadOneGerberFile(const wxString & FullFileName, wxDC * DC, int mode) /*******************************************************************************************/ /* Lecture d'un fichier PCB, le nom etant dans PcbNameBuffer.s retourne: 0 si fichier non lu ( annulation de commande ... ) 1 si OK */ { wxString filename = FullFileName; wxString path = wxPathOnly(FullFileName); ActiveScreen = GetScreen(); if( filename == "") { wxString mask = "*" + g_PhotoFilenameExt; filename = EDA_FileSelector(_("GERBER PLOT files:"), path, /* Chemin par defaut */ "", /* nom fichier par defaut */ g_PhotoFilenameExt, /* extension par defaut */ mask, /* Masque d'affichage */ this, 0, FALSE ); if ( filename == "" ) return FALSE; } GetScreen()->m_FileName = filename; wxSetWorkingDirectory(path); ChangeFileNameExt(filename,g_PenFilenameExt); if ( Read_GERBER_File(DC, GetScreen()->m_FileName, filename) ) SetLastProject(GetScreen()->m_FileName); Zoom_Automatique(FALSE); GetScreen()->SetRefreshReq(); g_SaveTime = time(NULL); return(1); } /**********************************************************************************************/ static void LoadDCodeFile(WinEDA_GerberFrame * frame, const wxString & FullFileName, wxDC * DC) /**********************************************************************************************/ /* Lecture d'un fichier PCB, le nom etant dans PcbNameBuffer.s retourne: 0 si fichier non lu ( annulation de commande ... ) 1 si OK */ { wxString filename = FullFileName; ActiveScreen = frame->GetScreen(); if( filename == "") { wxString penfilesmask("*"); penfilesmask += g_PenFilenameExt; filename = frame->GetScreen()->m_FileName; ChangeFileNameExt(filename,g_PenFilenameExt); filename = EDA_FileSelector(_("D CODES files:"), "", /* Chemin par defaut */ filename, /* nom fichier par defaut */ g_PenFilenameExt, /* extension par defaut */ penfilesmask, /* Masque d'affichage */ frame, 0, TRUE ); if ( filename == "" ) return; } frame->Read_D_Code_File(filename); frame->CopyDCodesSizeToItems(); frame->GetScreen()->SetRefreshReq(); } /*******************************************************************************/ bool WinEDA_GerberFrame::SaveGerberFile(const wxString & FullFileName, wxDC * DC) /*******************************************************************************/ /* Sauvegarde du fichier PCB en format ASCII */ { wxString filename = FullFileName; if( filename == "" ) { wxString mask("*"); mask += g_PhotoFilenameExt; filename = EDA_FileSelector(_("Gerber files:"), "", /* Chemin par defaut */ GetScreen()->m_FileName, /* nom fichier par defaut */ g_PhotoFilenameExt, /* extension par defaut */ mask, /* Masque d'affichage */ this, wxSAVE, FALSE ); if ( filename == "" ) return FALSE; } GetScreen()->m_FileName = filename; // TODO return TRUE; }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 213 ] ] ]
c7767423487b2b43898fe0b0932b35ef0ef9060b
be2e23022d2eadb59a3ac3932180a1d9c9dee9c2
/NpcServer/NpcKernel/Team.h
4b87fcb3f0bccd9616a57d1de59cd11a16054e14
[]
no_license
cronoszeu/revresyksgpr
78fa60d375718ef789042c452cca1c77c8fa098e
5a8f637e78f7d9e3e52acdd7abee63404de27e78
refs/heads/master
2020-04-16T17:33:10.793895
2010-06-16T12:52:45
2010-06-16T12:52:45
35,539,807
0
2
null
null
null
null
UTF-8
C++
false
false
1,391
h
#pragma once #include "define.h" #include <windows.h> #include "Myheap.h" #include <vector> #include <algorithm> #include "Msg.h" using namespace std; #define _MAX_TEAMAMOUNT 5 class Msg; class IRole; class CTeam { public: CTeam(); virtual ~CTeam(); public: // constuction static CTeam* CreateNew (); void Release () { delete this; } BOOL Create (CAgent* pAgent); protected: void Destroy (); public: // const bool IsValid () { return GetMemberAmount() > 0; } OBJID GetLeaderID (); public: // application bool AddMember (int nAmount, const TeamMemberInfo* setInfo); BOOL DelMember (OBJID idMember); void Dismiss (OBJID idLeader) { Init(); } BOOL Apply (OBJID idUser); protected: BOOL AddMember (OBJID idMember); void Open (); void Close (); BOOL IsClosed (); TeamMemberInfo* GetMemberByIndex (int nIndex); int GetMemberAmount (); BOOL IsTeamMember (OBJID idMember); BOOL IsTeamWithNewbie (OBJID idKiller, IRole* pTarget); protected: void AddMemberOnly (TeamMemberInfo* pMember); void DelMemberOnly (OBJID idMember); void Init (); protected: typedef vector<TeamMemberInfo> USERIDSET; USERIDSET m_setMember; CAgent* m_pOwner; private: BOOL m_fClosed; protected: // ctrl MYHEAP_DECLARATION(s_heap) };
[ "rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1" ]
[ [ [ 1, 71 ] ] ]
d26defb0c1ce6eae8d7af9bb5f387083a810dd01
d7040d1802ff8d69100c8d90b0191b8f7087eed8
/刘晋德_短信集成/Phone/Phone/UpdatePage.h
a6d4d5c48b51c85a5cca714ba2d69ddd48a47c93
[]
no_license
radtek/scu-phone
689fa50e785c01e2154959f46d1edad3926f3efb
4cbe8f803858ded7a92238af91b8fecfe58f348f
refs/heads/master
2020-12-31T07:44:04.107424
2011-05-08T10:35:40
2011-05-08T10:35:40
58,142,165
0
0
null
null
null
null
GB18030
C++
false
false
810
h
#pragma once // UpdatePage 对话框 #include "ListTable.h" class UpdatePage : public CPropertyPage { DECLARE_DYNAMIC(UpdatePage) public: UpdatePage(); virtual ~UpdatePage(); CComboBox m_comboxType; CListCtrl m_listCtr; CComboBox m_combox; private: ListTable *table; DataAccess da; CStringArray m_list; // 对话框数据 enum { IDD = IDD_Address_update }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 afx_msg void OnBquery(); afx_msg void OnClear(); afx_msg void OnSave(); virtual BOOL OnInitDialog(); afx_msg void OnCancelMode(); afx_msg void OnDblclkResult(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnRclickResult(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnMenuitemedit(); DECLARE_MESSAGE_MAP() };
[ [ [ 1, 34 ] ] ]
ecdd9935ee9ec9d5f6e678f9c80a2811b3478b9e
c497f6d85bdbcbb21e93ae701c5570f16370f0ae
/Sync/Lets_try_all_engine/backup/Clear/SatRf.hpp
9b560762d7255f7299194e81dac6c5140e7b6889
[]
no_license
mfkiwl/gpsgyan_fork
91b380cf3cfedb5d1aac569c6284bbf34c047573
f7c850216c16b49e01a0653b70c1905b5b6c2587
refs/heads/master
2021-10-15T08:32:53.606124
2011-01-19T16:24:18
2011-01-19T16:24:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,375
hpp
/* * File name : satRF.hpp * * Abstract : This file contains definitions of structures and Global classes * Struchers used in the Gpsgyan project. * * Compiler : Visual C++ Version 9.0 * * Compiler options : Default * * Pragmas : None used * * H/W Platform : IBM PC * * Portability : No Operating system call used. * No machine specific instruction used. * No compiler specific routines used. * Hence Portable. * * Authors : Priyank Kumar * * * Version history : Base version * Priyank Kumar November 2009 * * References : None * * Functions called : None * Library Used : GPStk * Copyright 2009, The University of Texas at Austin * */ /* GPSTk Library*/ #include "SatRfTypes.hpp" #include "DayTime.hpp" #include "SatID.hpp" #include "Position.hpp" #include "SatRfMac.hpp" #include "MSCData.hpp" #include "MSCStream.hpp" #include "FFIdentifier.hpp" //#include "TropModel.hpp" #include "IonoModel.hpp" //#include "IonoModelStore.hpp" #include "Geodetic.hpp" #include "SunPosition.hpp" /*C++ Systems Include files*/ #include <iostream> #include <string> #include <map> #include <vector> #include <math.h> /*GPSGyan Include files*/ #include "EngineFramework.hpp" using namespace gpstk; class SatRF: public EngineFramework { public: NEW_EXCEPTION_CLASS(ExcSatRF , gpstk::Exception); SatRF(const string& applName) throw() : EngineFramework( applName, "this computes satellite Position , Velocity and time for the specified receiever position and time") {}; // bool initialize(int argc, char *argv[]) throw(); // virtual void process(); void GetPassiveInput(satRF_psvIstruct &ref_psv); void GetActiveInput(satRF_actIstruct &ref_act); void GetPassiveParam(); void GetActiveParam(); void InputInfToEngine(Kind kind); // think of argv and argc implementation //virtual void runEngine(); void InputParamToEngine(Kind kind);// throw(InvalidParameter); //bool runEngine() throw(); //void outputInfFromEngine(std::ostream & s ,const std::string & data); void outputInfFromEngine(std::ostream & s ); //void OutputDumpOfEngine(); // Public Data memebers engineHealthMonitor satRF_probe; std::vector<satRF_ostruct> satRF_oData; std::vector<SatID> visibleSV; bool visiblityComputed; satRF_actIstruct ref_act; satRF_psvIstruct ref_psv; double alpha[4],beta[4],iono_freq; DayTime inp_time ; double usr_elev; std::vector<int> error_number; //std::string op_inf; protected : void EngineControl(Kind kind); void VerifyIpToEngine() throw(ExcSatRF); // void prepareIpToEngine() ; void MethodOfEngine() throw(ExcSatRF); void SetInitialStateofEngine(); void SetActiveStateofEngine (); void SatMDE_ExpHandler(ExcSatRF &e); // Fromatted File Printing std::string print_content(satRF_ostruct &ostruct); std::string print_header(); void CodeSwitcher(int code_num,boost::circular_buffer<int> *code_buffer); void GlonassCodeGen(int *ptr_to_code); void CodeGenCA_L1(boost::circular_buffer<int> *ptr_to_code,int tap1,int tap2); satRF_caCodeArray& GenerateCAcodeArray(int satID, double initCodePhase); satRF_carrierArray& GenerateBaseCarrier(double initCarrPhase); void GetGeneratedCode(satRF_caCodeArray &tempCodeBuffer, double codeFrequency,satRF_ostruct & ); void GetGeneratedCarrier(satRF_carrierArray &tempCarrBuffer, double carrierFrequency, satRF_ostruct &op_struct); // void validateOpOfEngine(); // void PrepareOpOfEngine() ; //virtual void dump(std::ostream &s); private : satRF_caCodeArray prnCodeBuffer; satRF_carrierArray prnCarrBuffer; SatID currSatid; map<SatID, codeAndCarrierDB> codeAndCarrierDictionary; map<SatID, satRF_carrierArray> instantCarrierDictionary; std::vector<satRF_caCodeArray> bigCodeArray; std::vector<satRF_carrierArray> bigCarrArray; //boost::circular_buffer<bool>::iterator it = cb.begin(); satRF_actIstruct satRF_ai; satRF_psvIstruct satRF_pi; unsigned int visSV; std::vector<satRF_ostruct> satRF_pData; };
[ "priyankguddu@6c0848c6-feae-43ef-b685-015bb26c21a7" ]
[ [ [ 1, 177 ] ] ]
047fada769b4f0943bc1f56609ec46993f19988d
4f89f1c71575c7a5871b2a00de68ebd61f443dac
/src/algorithms/features/SimpleFeaturesMatcher.cpp
565327a1c77f3f2e9eac206547828929187f352a
[]
no_license
inayatkh/uniclop
1386494231276c63eb6cdbe83296cdfd0692a47c
487a5aa50987f9406b3efb6cdc656d76f15957cb
refs/heads/master
2021-01-10T09:43:09.416338
2009-09-03T16:26:15
2009-09-03T16:26:15
50,645,836
0
0
null
null
null
null
UTF-8
C++
false
false
6,223
cpp
// Features detection and (noisy) matching // ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~= // Headers #include "SimpleFeaturesMatcher.hpp" #include "fast/FASTFeature.hpp" // for the definition of FASTFeature // implementation specific headers #include <iostream> // cout definition #include <limits> // to use numeric_limits<float>::max() and similars namespace uniclop { using namespace std; // ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~= // ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~= // Class SimpleFeaturesMatcher methods implementations template<typename T> args::options_description SimpleFeaturesMatcher<T>::get_options_description() { args::options_description desc("SimpleFeaturesMatcher options"); desc.add_options() ( "simple_features_matcher.max_distance", args::value<float>()->default_value(1e10), "maximum sum of squared difference between two features to do a match (16 uint8_t pixels)") ( "simple_features_matcher.num_near_features", args::value<int>()->default_value(3), "for each feature the nearest num_near_features will be proposed as putative matches") ; return desc; } template<typename T> SimpleFeaturesMatcher<T>::SimpleFeaturesMatcher(args::variables_map &options) { _max_distance = 40000.0f; _num_near_features = 5; if ( options.count("simple_features_matcher.max_distance") ) { _max_distance = options["simple_features_matcher.max_distance"].as<float>(); } if ( options.count("simple_features_matcher.num_near_features") ) { _num_near_features = options["simple_features_matcher.num_near_features"].as<int>(); } return; } template<typename T> SimpleFeaturesMatcher<T>::~SimpleFeaturesMatcher() { return; } template<typename T> vector< ScoredMatch >& SimpleFeaturesMatcher<T>::match( const vector<T>& features_list_a, const vector<T>& features_list_b) { matchings.clear(); const float &max_distance = _max_distance; const int &num_near_features = _num_near_features; typename vector<T>::const_iterator features_it_a, features_it_b; for (features_it_a = features_list_a.begin(); features_it_a != features_list_a.end(); ++features_it_a) { // for each feature in list a // search for the num_near_features nearest features vector< ScoredMatch > candidate_matches(num_near_features); // keep the list of candidates for the current feature typename vector< ScoredMatch >::iterator candidate_matches_it; typename vector< ScoredMatch >::iterator worst_candidate_it = candidate_matches.begin(); for (features_it_b = features_list_b.begin(); features_it_b != features_list_b.end(); ++features_it_b) { // for each feature in list b float t_distance = features_it_a->distance( *features_it_b ); if (t_distance > max_distance) break; // distance is out of the range of interest, so we skip this one // we suppose that num_near_features is small so a direct iteration // over the candidates list is the fastest option for (candidate_matches_it = candidate_matches.begin(); candidate_matches_it != candidate_matches.end(); ++candidate_matches_it) { // search for the worst candidate if ( candidate_matches_it->feature_a != &(*features_it_a) ) { // candidate slot has not been initialized // by default this is the worst one worst_candidate_it = candidate_matches_it; // we set some members (the others will be done later) worst_candidate_it->feature_a = &(*features_it_a); worst_candidate_it->distance = numeric_limits<float>::max(); break; // stop searching for worst } else { // if candidate has been initialized if ( (worst_candidate_it->distance) < (candidate_matches_it->distance) ) { // this one is the worst found up to now worst_candidate_it = candidate_matches_it; } } } // end of 'search for the worst candidate' if ( (worst_candidate_it->distance) > t_distance) { // current candidate is better than the worst of the previous ones // thus we replace it worst_candidate_it->feature_b = &(*features_it_b); worst_candidate_it->distance = t_distance; } } // end of 'for each feature in list b' typename vector< ScoredMatch >::const_iterator const_candidate_matches_it; // now candidate_matches has the list of putative matches for feature_a for (const_candidate_matches_it = candidate_matches.begin(); const_candidate_matches_it != candidate_matches.end(); ++const_candidate_matches_it) { // add the putative matches to the result list if ( const_candidate_matches_it->feature_a == &(*features_it_a) ) // sanity check { matchings.push_back(*const_candidate_matches_it); // copy the content } } } // end of 'for each feature in list a' return matchings; } // ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~= // Force the compilation of the following types // for some strange reason, in linux, this hast to be at the end of the defitions (?!) template class SimpleFeaturesMatcher<FASTFeature>; //class SIFTFeature; // forward declaration //template class SimpleFeaturesMatcher<SIFTFeature>; // ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~= }
[ "rodrigo.benenson@gmailcom" ]
[ [ [ 1, 179 ] ] ]
8185bc621171895ae76ed5c2fb15eca7e46844d0
27c6eed99799f8398fe4c30df2088f30ae317aff
/rtt-tool/qdoc3/quoter.h
eb6bd506c00468419b0ec7b28b7e75cc25bf5fd8
[]
no_license
lit-uriy/ysoft
ae67cd174861e610f7e1519236e94ffb4d350249
6c3f077ff00c8332b162b4e82229879475fc8f97
refs/heads/master
2021-01-10T08:16:45.115964
2009-07-16T00:27:01
2009-07-16T00:27:01
51,699,806
0
0
null
null
null
null
UTF-8
C++
false
false
3,205
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ /* quoter.h */ #ifndef QUOTER_H #define QUOTER_H #include <qhash.h> #include <qstringlist.h> #include "location.h" QT_BEGIN_NAMESPACE class Quoter { public: Quoter(); void reset(); void quoteFromFile( const QString& userFriendlyFileName, const QString& plainCode, const QString& markedCode ); QString quoteLine( const Location& docLocation, const QString& command, const QString& pattern ); QString quoteTo( const Location& docLocation, const QString& command, const QString& pattern ); QString quoteUntil( const Location& docLocation, const QString& command, const QString& pattern ); QString quoteSnippet(const Location &docLocation, const QString &identifier); private: QString getLine(); void failedAtEnd( const Location& docLocation, const QString& command ); bool match( const Location& docLocation, const QString& pattern, const QString& line ); QString commentForCode() const; bool silent; bool validRegExp; QStringList plainLines; QStringList markedLines; Location codeLocation; QHash<QString,QString> commentHash; }; QT_END_NAMESPACE #endif
[ "lit-uriy@d7ba3245-3e7b-42d0-9cd4-356c8b94b330" ]
[ [ [ 1, 89 ] ] ]
9e96f0ff073f2c1eb3a004efd41fcd7550a7ca89
8f0a611f6fe69b8d32eafac5d8ff01224759fff5
/code/winproc.cpp
6bb78c02befc90aacc548ba5b43bfc269d2a20e2
[]
no_license
yann-achard/interactive-stories
dbad9e86f457645c379034e282d1cb61eacd4f5e
cdd5c5a6bb52554e7cc289fd5c1c4e9450eece4a
refs/heads/master
2016-09-06T13:02:57.296097
2008-10-22T03:23:46
2008-10-22T03:23:46
32,113,161
0
0
null
null
null
null
UTF-8
C++
false
false
1,228
cpp
#include "main.h" #include "sidefunctions.h" #include "Game.h" //--------------------------------------------------------- LRESULT CALLBACK WindowProcedure(HWND hWindow,UINT uMessage,WPARAM wparam,LPARAM lparam){ switch (uMessage){ case WM_PAINT: g_game.Render(); ValidateRect(hWindow, NULL); return 0; case WM_MOUSEMOVE: g_game.MouseMove(wparam, LOWORD(lparam), HIWORD(lparam)); return 0; case WM_LBUTTONDOWN: g_game.LeftButtonDown(wparam, lparam); return 0; case WM_LBUTTONUP: g_game.LeftButtonUp(wparam, lparam); return 0; case WM_RBUTTONDOWN: g_game.RightButtonDown(wparam, lparam); return 0; case WM_RBUTTONUP: g_game.RightButtonUp(wparam, lparam); return 0; case WM_MBUTTONDOWN: g_game.MidButtonDown(wparam); return 0; case WM_MBUTTONUP: g_game.MidButtonUp(wparam); return 0; case WM_MOUSEWHEEL: g_game.MouseWheel(wparam); return 0; case WM_KEYUP: g_game.KeyUp(wparam); return 0; case WM_KEYDOWN: { if (wparam == VK_ESCAPE){ Log("escape key pressed\n"); DestroyWindow(hWindow); } else { g_game.KeyDown(wparam); } return 0; } case WM_DESTROY: { g_game.run = false; break; } } return DefWindowProc(hWindow,uMessage,wparam,lparam); }
[ "achard.y@b606e15d-ce52-0410-8a58-a3a25ff26d38" ]
[ [ [ 1, 32 ] ] ]
ebe694c3ea1b4c979a1c49d97e3ee4509f4c80b7
c5d917f40e7f420f2053ce443e663b2332efd49b
/Cambio.h
9b734d0d714cfa0080427c690cea7097ee8ea2e4
[]
no_license
lagenar/diffalgo
c3c6075abd569315818d5de6b952d084350cce40
bba8e0cf2c14e11177369a01d3a74491ba80d7ca
refs/heads/master
2021-01-11T04:24:18.588181
2009-07-13T18:24:25
2009-07-13T18:24:25
71,199,398
0
0
null
null
null
null
UTF-8
C++
false
false
1,901
h
#ifndef CAMBIO_H #define CAMBIO_H #include "Archivo.h" #include "Lista.h" #include <string> #include <sstream> using namespace std; enum TipoCambio {AGREGAR, ELIMINAR}; class Cambio { public: virtual ~Cambio() { } virtual string getDiff() = 0; virtual void aplicarCambio(Archivo&, int) = 0; //Utilizado para reflexión de tipos de cambio virtual TipoCambio tipoCambio() = 0; //retorna la cantidad de líneas que edita virtual int getCantLineas() = 0; virtual int getIndiceOrigen() = 0; virtual bool editaAPartirDe(int) = 0; protected: Lista<string> lineas; }; class CambioAgregar: public Cambio { public: CambioAgregar(const Archivo &, int); CambioAgregar(const Archivo &, int, int, int); ~CambioAgregar() { } string getDiff(); TipoCambio tipoCambio() { return AGREGAR; } int getCantLineas() { return lineaDestinoFinal - lineaDestinoComienzo + 1; } void aplicarCambio(Archivo &, int); int getIndiceOrigen() { return lineaOrigen; } bool editaAPartirDe(int); private: int lineaOrigen; int lineaDestinoComienzo; int lineaDestinoFinal; }; class CambioEliminar: public Cambio { public: CambioEliminar(const Archivo &, int); CambioEliminar(const Archivo &, int, int, int); ~CambioEliminar() { } string getDiff(); TipoCambio tipoCambio() { return ELIMINAR; } int getCantLineas() { return lineaOrigenFinal - lineaOrigenComienzo + 1; } void aplicarCambio(Archivo &, int); int getIndiceOrigen() { return lineaOrigenComienzo; } bool editaAPartirDe(int); private: int lineaDestino; int lineaOrigenComienzo; int lineaOrigenFinal; }; #endif // CAMBIO_H
[ "lucas@lucas-desktop", "lucas@localhost" ]
[ [ [ 1, 14 ], [ 16, 31 ], [ 33, 49 ], [ 51, 63 ] ], [ [ 15, 15 ], [ 32, 32 ], [ 50, 50 ] ] ]
054a2fd048730f9493b464a84ac28e8c7cd6cb87
252e638cde99ab2aa84922a2e230511f8f0c84be
/tripformlib/src/TripAddForm.cpp
ee20c64c4b30431f6ec45b96738cb55c811680c1
[]
no_license
openlab-vn-ua/tour
abbd8be4f3f2fe4d787e9054385dea2f926f2287
d467a300bb31a0e82c54004e26e47f7139bd728d
refs/heads/master
2022-10-02T20:03:43.778821
2011-11-10T12:58:15
2011-11-10T12:58:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
675
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrTrip #include "TripAddForm.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "TripProcessForm" #pragma link "VStringStorage" #pragma link "DBLookupComboBoxExt" #pragma resource "*.dfm" TTourTripAddForm *TourTripAddForm; //--------------------------------------------------------------------------- __fastcall TTourTripAddForm::TTourTripAddForm(TComponent* Owner) : TTourTripProcessForm(Owner) { } //---------------------------------------------------------------------------
[ [ [ 1, 19 ] ] ]
14f588ca3b21af64d24957fec2aeca9b9c04eaaf
16d41562840d132a358388c2d02160f6bfd8c7d9
/tpc/source/11235-fv/frequent_values.cpp
311c3f6d398f5f43e031b0f08661bb664908bc27
[]
no_license
LMC00021002/pap2010-grupo14
a19547639506848f33a552dcb8d1bc293d3c528c
1ffebb02f9aa256e1c83ce1c941a2be6da50a218
refs/heads/master
2021-01-10T16:50:29.118977
2010-07-06T16:11:45
2010-07-06T16:11:45
48,855,309
0
0
null
null
null
null
UTF-8
C++
false
false
2,653
cpp
#include <iostream> #include <vector> using namespace std; typedef pair< int, int > pii; vector< vector< int > > tabla; vector< int > enteros; vector< int > mapIndices; vector< pii > rangos; inline int max( int a, int b ) { return a > b ? a : b; } inline int log2( int a ){ int potencia = 0; while( 1 << ++potencia <= a ){} return potencia - 1; } inline pii& rangoEnQueCae( int a ) { return rangos[ mapIndices[ a ] ]; } void convertirARMQ( const vector< int >& arreglo ) { int n = arreglo.size(); int k = 0; int ultimoDiferente = 0; enteros.push_back(1); mapIndices.resize( n, 0 ); rangos.push_back( pii( 0, 0 ) ); for( int i = 1; i < n; i++ ) { if( arreglo[ ultimoDiferente ] != arreglo[i] ) { rangos[ k ].second = i - 1; ultimoDiferente = i; enteros.push_back(0); k++; rangos.push_back( pii( i, i ) ); } enteros[ k ]++; mapIndices[ i ] = k; } rangos[ k ].second = n - 1; } void procesarTabla() { int n = enteros.size(); tabla.resize( n, vector< int >( log2(n) + 1 ) ); for( int i = 0; i < n; i++ ) tabla[i][0] = enteros[ i ]; for( int j = 1; 1 << j <= n; j++ ) for( int i = 0; i + (1 << j) - 1 < n; i++ ) tabla[i][j] = max( tabla[i][j - 1], tabla[i + (1 << (j - 1))][j - 1] ); } int calcularMaximo( int i, int j ) { if ( i > j ) return 1; i = mapIndices[ i ]; j = mapIndices[ j ]; int k = log2( j - i + 1 ); return max( tabla[ i ][ k ], tabla[ j - (1<<k) + 1 ][ k ] ); } int calcularFV( int i, int j ) { pii& a = rangoEnQueCae( i ); pii& b = rangoEnQueCae( j ); if ( a == b ) return j - i + 1; int maximoParcial = calcularMaximo( a.second + 1, b.first - 1 ); return max( maximoParcial, max( a.second - i + 1, j - b.first + 1) ); } int main() { int n, q; while( scanf("%d", &n) == 1 ) { if( n == 0 ) break; tabla.clear(); enteros.clear(); mapIndices.clear(); rangos.clear(); scanf("%d", &q); vector< int > arregloEntrada( n ); for( int i = 0; i < n; i++ ) scanf("%d", &arregloEntrada[ i ]); convertirARMQ( arregloEntrada ); procesarTabla(); for( int i = 0; i < q; i++ ) { int desde, hasta; scanf("%d %d", &desde, &hasta); printf("%d\n", calcularFV(--desde, --hasta)); } } return 0; }
[ "hadeskleizer@d1b1875b-4509-22a8-4f88-0435eeb08bb5", "tutecosta@d1b1875b-4509-22a8-4f88-0435eeb08bb5" ]
[ [ [ 1, 7 ], [ 9, 12 ], [ 14, 20 ], [ 22, 35 ], [ 37, 60 ], [ 63, 90 ], [ 92, 112 ] ], [ [ 8, 8 ], [ 13, 13 ], [ 21, 21 ], [ 36, 36 ], [ 61, 62 ], [ 91, 91 ] ] ]
fbd57dbea7fd062a4de9b6cb33891e4e8005b5bd
6e4f9952ef7a3a47330a707aa993247afde65597
/PROJECTS_ROOT/WireKeys/WP_IconsFont/WP_IconsFont.cpp
a6ad26291cb697c096ee120d644b1617da2c37b9
[]
no_license
meiercn/wiredplane-wintools
b35422570e2c4b486c3aa6e73200ea7035e9b232
134db644e4271079d631776cffcedc51b5456442
refs/heads/master
2021-01-19T07:50:42.622687
2009-07-07T03:34:11
2009-07-07T03:34:11
34,017,037
2
1
null
null
null
null
WINDOWS-1251
C++
false
false
4,551
cpp
// IconsFont.cpp : Defines the initialization routines for the DLL. // #include "stdafx.h" #include <atlbase.h> #include "WP_IconsFont.h" #include "HookCode.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern CIconsFontInfo hookData; extern CIconsFontOptions plgOptions; extern HINSTANCE g_hinstDll; extern BOOL g_bFirstTime; extern HWND g_hTargetWin; extern DWORD g_hTargetThread; extern HANDLE hHookerEventDone; #define SAVELOGFONT_REGKEY "SOFTWARE\\WiredPlane\\WireKeys\\FontMaster" HWND GetSysListView() { static HWND hTargetWindow=NULL; if(hTargetWindow!=NULL && !IsWindow(hTargetWindow)){ hTargetWindow=NULL; } if(hTargetWindow==NULL){ HWND hWnd1 = ::FindWindow("Progman","Program Manager"); if(hWnd1 == 0){ hWnd1 = FindWindow("ProgMan",NULL); } if(hWnd1 == 0){ return 0; } HWND hWnd2 = FindWindowEx(hWnd1,0,"SHELLDLL_DefView",NULL); if(hWnd2 == 0){ hWnd2 = GetWindow(hWnd1,GW_CHILD); } if(hWnd2 == 0){ return 0; } hTargetWindow = FindWindowEx(hWnd2,0,"SysListView32",NULL); if(hTargetWindow == 0){ hTargetWindow = GetWindow(hWnd2,GW_CHILD); // Desktop Window } } return hTargetWindow; } // It is very important to set and remove hook from one thread // For Windows 2000 and higher this is required DWORD WINAPI GlobalHooker(LPVOID pData) { MSG msg; // Создаем очередь сообщений ::PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE); while(GetMessage(&msg,0,0,0)>0){ if(msg.message==WM_ENABLE && msg.wParam!=0){ SetHook(GetSysListView()); } if(msg.message==WM_CLOSE || (msg.message==WM_ENABLE && msg.wParam==0)){ SetHook(NULL); } SetEvent(hHookerEventDone); if(msg.message==WM_CLOSE || msg.message==WM_QUIT){ break; } } return 0; } int CALLBACK OptionsDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { if(uMsg==WM_INITDIALOG){ ::SetWindowLong(hwndDlg,GWL_EXSTYLE,WS_EX_APPWINDOW|::GetWindowLong(hwndDlg,GWL_EXSTYLE)); PostMessage(::GetDesktopWindow(), WM_SYSCOMMAND, (WPARAM) SC_HOTKEY, (LPARAM)hwndDlg); ::SendMessage(GetDlgItem(hwndDlg,IDC_SETFONT), BM_SETCHECK, plgOptions.bSetFont, 0); ::SendMessage(GetDlgItem(hwndDlg,IDC_SETTXCOL), BM_SETCHECK, plgOptions.bSetTxColor, 0); ::SendMessage(GetDlgItem(hwndDlg,IDC_SETBGCOL), BM_SETCHECK, plgOptions.bSetBgColor, 0); ::SendMessage(GetDlgItem(hwndDlg,IDC_SETBGTRANS), BM_SETCHECK, plgOptions.bSetTransp, 0); return TRUE; } if(uMsg==WM_COMMAND && wParam==IDOK){ plgOptions.bSetFont=(int)::SendMessage(GetDlgItem(hwndDlg,IDC_SETFONT), BM_GETCHECK, 0, 0); plgOptions.bSetTxColor=(int)::SendMessage(GetDlgItem(hwndDlg,IDC_SETTXCOL), BM_GETCHECK, 0, 0); plgOptions.bSetBgColor=(int)::SendMessage(GetDlgItem(hwndDlg,IDC_SETBGCOL), BM_GETCHECK, 0, 0); plgOptions.bSetTransp=(int)::SendMessage(GetDlgItem(hwndDlg,IDC_SETBGTRANS), BM_GETCHECK, 0, 0); EndDialog(hwndDlg,0); return TRUE; } if(uMsg==WM_DRAWITEM && wParam==IDC_BT_BG){ static char* szExText="Example"; DRAWITEMSTRUCT* pDr=(DRAWITEMSTRUCT*)lParam; HBRUSH hBr=CreateSolidBrush(hookData.g_FontBgColor); ::FillRect(pDr->hDC,&pDr->rcItem,hBr); DeleteObject(hBr); HFONT hFont = ::CreateFontIndirect(&hookData.g_Font); HFONT hPrevFont=(HFONT)::SelectObject(pDr->hDC,hFont); ::SetTextColor(pDr->hDC,hookData.g_FontColor); ::SetBkColor(pDr->hDC,hookData.g_FontBgColor); ::DrawText(pDr->hDC,szExText,strlen(szExText),&pDr->rcItem,DT_CENTER|DT_VCENTER|DT_SINGLELINE); ::SelectObject(pDr->hDC,hPrevFont); HBRUSH hBr2=CreateSolidBrush(0); ::FrameRect(pDr->hDC,&pDr->rcItem,hBr2); DeleteObject(hBr2); return TRUE; } if(uMsg==WM_COMMAND && wParam==IDC_BGCOL){ CColorDialog dlg(hookData.g_FontBgColor,0,CWnd::FromHandle(hwndDlg)); if(dlg.DoModal()==IDOK){ hookData.g_FontBgColor=dlg.GetColor(); } ::InvalidateRect(hwndDlg,NULL,TRUE); return TRUE; } if(uMsg==WM_COMMAND && wParam==ID_SETFONT){ DWORD dwEffects=CF_EFFECTS|CF_SCREENFONTS; CFontDialog dlg((hookData.g_Font.lfHeight)?&hookData.g_Font:NULL,dwEffects,NULL,CWnd::FromHandle(hwndDlg)); dlg.m_cf.rgbColors=hookData.g_FontColor; dlg.m_cf.Flags|=dwEffects|CF_INITTOLOGFONTSTRUCT|CF_FORCEFONTEXIST|CF_NOVERTFONTS; dlg.m_cf.lpLogFont=&hookData.g_Font; if(dlg.DoModal()==IDOK){ hookData.g_FontColor=dlg.GetColor(); } ::InvalidateRect(hwndDlg,NULL,TRUE); return TRUE; } return FALSE; }
[ "wplabs@3fb49600-69e0-11de-a8c1-9da277d31688" ]
[ [ [ 1, 133 ] ] ]
94b9bfe205523899c8e67af1e1c610b509e41ef9
b24d5382e0575ad5f7c6e5a77ed065d04b77d9fa
/RadiantLaserCross/RLC_BulletManager.cpp
c046341e80b0e752116295f5202e24c9dd4a9592
[]
no_license
Klaim/radiant-laser-cross
f65571018bf612820415e0f672c216caf35de439
bf26a3a417412c0e1b77267b4a198e514b2c7915
refs/heads/master
2021-01-01T18:06:58.019414
2010-11-06T14:56:11
2010-11-06T14:56:11
32,205,098
0
0
null
null
null
null
UTF-8
C++
false
false
455
cpp
#include "RLC_BulletManager.h" #include <algorithm> namespace rlc { void BulletManager::fire_bullet( const BulletTypePtr& bullet_type, Position start_pos, Direction start_dir ) { Bullet* bullet = m_bullets_pool.find_dead_bullet(); if( bullet ) { // activate the bullet by firing it if fire rate time passed bullet->fire( bullet_type, start_pos, start_dir ); }// no dead bullet available // just ignore } }
[ [ [ 1, 22 ] ] ]
e2d7e6d97298d490f185d50017eb14bbcbc91d3a
ed6f03c2780226a28113ba535d3e438ee5d70266
/util/gfunc.cc
a5029a8d99832986f65f9b14f86144c7a6a9131f
[]
no_license
snmsts/wxc
f06c0306d0ff55f0634e5a372b3a71f56325c647
19663c56e4ae2c79ccf647d687a9a1d42ca8cb61
refs/heads/master
2021-01-01T05:41:20.607789
2009-04-08T09:12:08
2009-04-08T09:12:08
170,876
4
1
null
null
null
null
UTF-8
C++
false
false
317
cc
#include "wx/wx.h" #include "wx/string.h" int main(int argc,char **argv) { wxString s = wxString::FromAscii(argv[1]); int tok; tok = s.Find('.'); while (tok != wxNOT_FOUND) { wxPrintf(_T("#include \"src/%s.cpp\"\n"),s.Mid(0,tok).c_str()); s = s.Mid(tok+3); tok = s.Find('.'); } }
[ [ [ 1, 14 ] ] ]
7fbebd12212fbace3e4cebebb5f3904e743a41a5
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/VolumeBrush.h
0da690e11edb0716a65315e1f23bbb0d2c4f414e
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
3,195
h
// ----------------------------------------------------------------------- // // // MODULE : VolumeBrush.h // // PURPOSE : VolumeBrush definition // // CREATED : 1/29/98 // // (c) 1998-2002 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef __VOLUME_BRUSH_H__ #define __VOLUME_BRUSH_H__ LINKTO_MODULE( VolumeBrush ); #include "GameBase.h" #include "ContainerCodes.h" #include "DamageTypes.h" #include "..\shared\SoundFilterMgr.h" #include "SharedMovement.h" class CSoundFilterMgrPlugin; class CSurfaceMgrPlugin; enum SurfaceType; class VolumeBrush : public GameBase { public : VolumeBrush(); ~VolumeBrush(); LTFLOAT GetGravity() const { return m_fGravity; } LTFLOAT GetFriction() const { return m_fFriction; } LTFLOAT GetViscosity() const { return m_fViscosity; } ContainerCode GetCode() const { return m_eContainerCode; } LTVector GetCurrent() const { return m_vCurrent; } bool GetHidden() const { return m_bHidden; } PlayerPhysicsModel GetPhysicsModel() const { return m_ePPhysicsModel; } protected : uint32 EngineMessageFn(uint32 messageID, void *pData, LTFLOAT lData); virtual void ReadProp(ObjectCreateStruct *pStruct); virtual void UpdatePhysics(ContainerPhysics* pCPStruct); virtual void UpdateLiquidPhysics(ContainerPhysics* pCPStruct); virtual void WriteSFXMsg(ILTMessage_Write *pMsg); virtual bool OnTrigger(HOBJECT hSender, const CParsedMsg &cMsg); void Show(); void Hide(); // These variables don't need to be saved since they will be saved in the // special fx message... LTVector m_vTintColor; LTVector m_vLightAdd; LTFLOAT m_fFogFarZ; LTFLOAT m_fFogNearZ; uint8 m_nSfxMsgId; uint8 m_nSoundFilterId; bool m_bFogEnable; bool m_bCanPlayMoveSnds; SurfaceType m_eSurfaceOverrideType; // This associates an override surface, from surfaces.txt, with the volume. // The following need to be saved... LTVector m_vCurrent; LTVector m_vFogColor; LTFLOAT m_fViscosity; LTFLOAT m_fFriction; LTFLOAT m_fDamage; LTFLOAT m_fGravity; uint32 m_dwSaveFlags; DamageType m_eDamageType; ContainerCode m_eContainerCode; bool m_bHidden; PlayerPhysicsModel m_ePPhysicsModel; // The following doesn't need to be saved at all... uint32 m_dwFlags; private : void CreateSpecialFXMsg(); void Save(ILTMessage_Write *pMsg, uint32 dwSaveFlags); void Load(ILTMessage_Read *pMsg, uint32 dwLoadFlags); void PostPropRead(ObjectCreateStruct *pStruct); void InitialUpdate(); }; class CVolumePlugin : public IObjectPlugin { public: CVolumePlugin(); virtual ~CVolumePlugin(); virtual LTRESULT PreHook_EditStringList( const char* szRezPath, const char* szPropName, char** aszStrings, uint32* pcStrings, const uint32 cMaxStrings, const uint32 cMaxStringLength); protected : CSoundFilterMgrPlugin* m_pSoundFilterMgrPlugin; CSurfaceMgrPlugin* m_pSurfaceMgrPlugin; }; #endif // __VOLUME_BRUSH_H__
[ [ [ 1, 122 ] ] ]
1e508f0616d3d815a0f1c5ec3d437f9fba96fad5
65da00cc6f20a83dd89098bb22f8f93c2ff7419b
/HabuGraphics/Library/Source/Surface.cpp
a201f58c92c2397f14725e7703308b759b998872
[]
no_license
skevy/CSC-350-Assignment-5
8b7c42257972d71e3d0cd3e9566e88a1fdcce73c
8091a56694f4b5b8de7e278b64448d4f491aaef5
refs/heads/master
2021-01-23T11:49:35.653361
2011-04-20T02:20:06
2011-04-20T02:20:06
1,638,578
0
0
null
null
null
null
UTF-8
C++
false
false
4,646
cpp
//***************************************************************************// // Surface Class Implementation // // Created Nov 12, 2005 // By: Jeremy M Miller // // Copyright (c) 2005-2010 Jeremy M Miller. All rights reserved. // This source code module, and all information, data, and algorithms // associated with it, are part of BlueHabu technology (tm). // // Usage of HabuGraphics is subject to the appropriate license agreement. // A proprietary/commercial licenses are available. // // HabuGraphics 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 3 of the License, or // (at your option) any later version. // // HabuGraphics 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 HabuGraphics. If not, see <http://www.gnu.org/licenses/>. //***************************************************************************// //***************************************************************************// #include "Surface.hpp" #include "Material.hpp" #include "Texture.hpp" //***************************************************************************// //***************************************************************************// namespace HabuTech { //-------------------------------------------------------------------------// Surface::Surface() { Create(); } //-------------------------------------------------------------------------// Surface::Surface(const Surface& rSource) { Create(); Clone(rSource); } //-------------------------------------------------------------------------// Surface::~Surface() { try { Destroy(); } catch(...) { } } //-------------------------------------------------------------------------// void Surface::Create() { this->mpActiveMaterial = NULL; } void Surface::Destroy() { this->mvMaterials.clear(); this->mvTextures.clear(); } void Surface::Clone(const Surface& rSource) { this->mvMaterials.assign(rSource.mvMaterials.begin(), rSource.mvMaterials.end()); this->mvTextures.assign(rSource.mvTextures.begin(), rSource.mvTextures.end()); if(this->mvMaterials.size() > 0) this->mpActiveMaterial = this->mvMaterials[0]; } //-------------------------------------------------------------------------// void Surface::RenderMaterial() { if(this->mpActiveMaterial) this->mpActiveMaterial->Render(); else if(this->mvMaterials.size() > 0) { this->mpActiveMaterial = mvMaterials[0]; this->mpActiveMaterial->Render(); } } //-------------------------------------------------------------------------// //-------------------------------------------------------------------------// void Surface::RenderTextures() { for(unsigned long ulIndex = 0UL; ulIndex < this->mvTextures.size(); ulIndex++) { this->mvTextures[ulIndex]->Render(); } } //-------------------------------------------------------------------------// //-------------------------------------------------------------------------// bool Surface::AddMaterial(class Material* pMaterial) { bool bReturnValue = false; if(pMaterial) { this->mvMaterials.push_back(pMaterial); mpActiveMaterial = pMaterial; bReturnValue = true; } return bReturnValue; } //-------------------------------------------------------------------------// //-------------------------------------------------------------------------// bool Surface::AddTexture(class Texture* pTexture) { bool bReturnValue = false; if(pTexture) { this->mvTextures.push_back(pTexture); bReturnValue = true; } return bReturnValue; } //-------------------------------------------------------------------------// //-------------------------------------------------------------------------// void Surface::Render() { this->RenderTextures(); this->RenderMaterial(); } //-------------------------------------------------------------------------// } // End of namespace HabuTech //***************************************************************************//
[ [ [ 1, 142 ] ] ]
f360f9b7a8b0119a10062d040a39f4bf75815fde
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/gameplay/src/gameplay/ngamematerialserver_main.cc
f1b59a5122c7720f97373a6976c98daa441de948
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,545
cc
//----------------------------------------------------------------------------- // ngamematerialserver_main.cc // (C) 2005 Conjurer Services, S.A. //----------------------------------------------------------------------------- #include "precompiled/pchgameplay.h" #include "gameplay/ngamematerialserver.h" #include "gameplay/ngamematerial.h" #include "nphysics/nphymaterial.h" #include "nphysics/nphysicsserver.h" #include "kernel/nfileserver2.h" //----------------------------------------------------------------------------- nNebulaScriptClass(nGameMaterialServer, "nroot"); //----------------------------------------------------------------------------- nGameMaterialServer* nGameMaterialServer::Singleton(0); nGameMaterialServer::tContainerGameMaterials nGameMaterialServer::listMaterials( NumInitialMaterialsSpace, NumMaterialsGrowthPace ); int nGameMaterialServer::MaterialsSize = 0; //----------------------------------------------------------------------------- namespace { const char* MaterialsPath("/usr/gamematerials/"); const char* FileMaterialsPath("wc:libs/materials/"); const char* DefaultMaterialName( "defaultmaterial" ); } //----------------------------------------------------------------------------- /** Constructor history: - 21-Oct-2005 Zombie created */ nGameMaterialServer::nGameMaterialServer() { n_assert2( !Singleton , "Trying to instanciate a second instance of a singleton" ); Singleton = this; } //----------------------------------------------------------------------------- /** Destructor history: - 21-Oct-2005 Zombie created */ nGameMaterialServer::~nGameMaterialServer() { // destroying data this->Destroy(); // Has to be the last line. Singleton = 0; } //----------------------------------------------------------------------------- /** Get instance pointer @return pointer to the only instance of this object history: - 21-Oct-2005 Zombie created */ nGameMaterialServer* nGameMaterialServer::Instance() { n_assert2( Singleton , "Accessing to the physics server without instance." ); return Singleton; } //----------------------------------------------------------------------------- /** Destroys server's data history: - 21-Oct-2005 Zombie created */ void nGameMaterialServer::Destroy() { // Empty } //----------------------------------------------------------------------------- /** Returns a material type trough the id. @return a material otherwise a null pointer history: - 01-Aug-2004 Zombie created - 28-Oct-2005 Zombie moved from nGameMaterial */ nGameMaterial* nGameMaterialServer::GetMaterial( const unsigned int id ) const { nGameMaterial* material; if( listMaterials.Find( id, material ) ) return material; return 0; } //----------------------------------------------------------------------------- /** Creates a material. @param name new material's name @return a material otherwise a null pointer history: - 28-Oct-2005 Zombie created */ nGameMaterial* nGameMaterialServer::CreateMaterial( const nString& name ) { #ifndef NGAME nGameMaterial* check(0); // check the name it's not been used before bool found( this->listMaterials.Find( nTag( name ).KeyMap(), check ) ); if( found == true ) { n_assert2_always( "There's a material already with this name." ); return 0; } #endif // NOH Path nString nohPath(MaterialsPath); nohPath += name; nGameMaterial* material(static_cast<nGameMaterial*> (nKernelServer::Instance()->New( "ngamematerial", nohPath.Get()))); n_assert2( material, "Failed to create the game material object." ); // adds itself material->Add(); return material; } //----------------------------------------------------------------------------- /** Updates list of materials. history: - 01-Aug-2004 Zombie created - 28-Oct-2005 Zombie moved from nGameMaterial */ void nGameMaterialServer::UpdateList() { // NOTE: for future use, where some information has to be updated nPhyMaterial::UpdateTableMaterialContacts(); } //----------------------------------------------------------------------------- /** Returns a material type trough the name. @param name material's name @return material if any history: - 28-Oct-2005 Zombie created */ nGameMaterial* nGameMaterialServer::GetMaterialByName( const nString& name ) const { return this->GetMaterial( nTag( name ).KeyMap() ); } //----------------------------------------------------------------------------- /** Adds an already existing material. @param material a material history: - 31-Oct-2005 Zombie created */ void nGameMaterialServer::Add( nGameMaterial* material ) { n_assert2( material, "Error, no material present." ); #ifndef NGAME bool check( strncmp( material->GetFullName().Get(), MaterialsPath,strlen( MaterialsPath )) ? true:false ); // checking it's in the right place n_assert2( !check, "The path it isn't in the right place" ); if( check ) { return; } #endif // creates material->Create(); // adding it to the list listMaterials.Add( material->GetMaterialId(), material ); // updates the list of materials this->UpdateList(); } #ifndef NGAME //----------------------------------------------------------------------------- /** Returns if any of the materials is dirty (changed). @return true/false history: - 31-Oct-2005 Zombie created */ const bool nGameMaterialServer::IsDirty() const { for( int index(0); index < listMaterials.Size(); ++index ) { if( listMaterials.GetElementAt( index )->IsDirty() ) { return true; } } return false; } #endif //----------------------------------------------------------------------------- /** Inits object. @param ignored history: - 02-Nov-2005 Zombie created */ void nGameMaterialServer::InitInstance(nObject::InitInstanceMsg) { // Load materials this->LoadMaterials(); } //----------------------------------------------------------------------------- /** Loads materials. history: - 02-Nov-2005 Zombie created */ void nGameMaterialServer::LoadMaterials() { // load physics materials nPhysicsServer::Instance()->LoadMaterials(); nFileServer2* fserver(nKernelServer::Instance()->GetFileServer()); n_assert2( fserver, "File server required." ); nArray<nString> files(fserver->ListFiles( FileMaterialsPath )); for( int index(0); index < files.Size(); ++index ) { nString NOHPathName( MaterialsPath ); NOHPathName.Append(files[ index ].ExtractFileName()); NOHPathName.StripExtension(); // create an object first nGameMaterial* gmaterial( static_cast<nGameMaterial*>( nKernelServer::Instance()->New( "ngamematerial", NOHPathName.Get() ))); n_assert2( gmaterial, "Failed to createa a Game Material." ); // load scripting info nKernelServer::Instance()->PushCwd( gmaterial ); nKernelServer::Instance()->Load( files[ index ].Get(), false ); nKernelServer::Instance()->PopCwd(); gmaterial->Add(); } } #ifndef NGAME //----------------------------------------------------------------------------- /** Removes a material. @param material a game material history: - 02-Nov-2005 Zombie created */ void nGameMaterialServer::RemoveMaterial(nGameMaterial* material) { n_assert2( material, "Missing game material." ); // removing a game material from the servers list listMaterials.Rem( nTag( material->GetName() ).KeyMap() ); // removing the file in the repository nFileServer2* fserver(nKernelServer::Instance()->GetFileServer()); n_assert2( fserver, "Missing file server." ); nString filePathName( FileMaterialsPath ); filePathName += material->GetName(); filePathName += ".n2"; if( fserver->FileExists( filePathName ) ) { // deleting the material file fserver->DeleteFile( filePathName ); } // destroying the object material->Release(); } //----------------------------------------------------------------------------- /** Removes a material from the server. @param material a game material history: - 04-Nov-2005 Zombie created */ void nGameMaterialServer::Remove(nGameMaterial* material) { n_assert2( material, "Missing game material." ); if( !strcmp( material->GetName(),DefaultMaterialName ) ) { n_assert2_always( "The default material can't be removed." ); return; } if( nPhysicsServer::Instance()->ItsGameMaterialUsed( material->GetGameMaterialId() ) ) { n_assert2_always( "The material can not be removed 'cos it's still in use." ); return; } material->SetToBeRemoved( true ); } #endif //----------------------------------------------------------------------------- /** */ nGameMaterial* nGameMaterialServer::GetMaterialByIndex( const int index ) const { return this->listMaterials.GetElementAt(index); } //----------------------------------------------------------------------------- /** */ int nGameMaterialServer::GetNumMaterials() const { return this->listMaterials.Size(); } ///----------------------------------------------------------------------------- /** Debug function to update the last changes in materials. history: - 07-Feb-2006 Zombie created */ #ifndef NGAME void nGameMaterialServer::Update() { nPhyMaterial::UpdateTableMaterialContacts(); } #endif //----------------------------------------------------------------------------- // EOF //-----------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 400 ] ] ]
5058de3d907df162a22b9b5b2d010a7f5e5b5823
b144663dd43236066d70be6c09a3c4f8ab5541fd
/src/boost/os_services/detail/filesystem_item.hpp
c6bd2f4a86740d02b8d8ded5f6654ad8a94cbc31
[]
no_license
nkzxw/schwimmer-hund
a1ffbf9243fba148461d65b5ad9cee4519f70f9a
2d0e11efef9f401bbccbba838d516341bc9b3283
refs/heads/master
2021-01-10T05:41:38.207721
2011-02-03T14:57:10
2011-02-03T14:57:10
47,530,533
0
0
null
null
null
null
UTF-8
C++
false
false
7,232
hpp
#ifndef BOOST_OS_SERVICES_DETAIL_FILESYSTEM_ITEM_HPP_INCLUDED #define BOOST_OS_SERVICES_DETAIL_FILESYSTEM_ITEM_HPP_INCLUDED #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif //#include <iostream> //TODO: revisar los headers //// C-Std headers //#include <cerrno> //TODO: probar si es necesario //#include <cstdio> //TODO: probar si es necesario //#include <cstdlib> //TODO: probar si es necesario //#include <cstring> // for strerror // POSIX headers //#include <sys/event.h> //#include <sys/fcntl.h> //#include <sys/time.h> //#include <sys/types.h> //#include <unistd.h> #include <boost/filesystem/path.hpp> #include <boost/os_services/detail/file_inode_info.hpp> #include <boost/os_services/detail/posix_syscall_wrapper.hpp> //TODO: sacar enum { /** The atime of a file has been modified */ PN_ACCESS = 0x1 << 0, /** A file was created in a watched directory */ PN_CREATE = 0x1 << 1, /** A file was deleted from a watched directory */ PN_DELETE = 0x1 << 2, /** The modification time of a file has changed */ PN_MODIFY = 0x1 << 3, /** Automatically delete the watch after a matching event occurs */ PN_ONESHOT = 0x1 << 4, /** An error condition in the underlying kernel event queue */ PN_ERROR = 0x1 << 5, PN_RENAME = 0x1 << 6 } __PN_BITMASK; #define PN_ALL_EVENTS (PN_ACCESS | PN_CREATE | PN_DELETE | PN_MODIFY | PN_RENAME) namespace boost { namespace os_services { namespace detail { struct user_entry; //forward-declaration //TODO: no me gusta, ver si se puede agregar al forward declaration typedef boost::shared_ptr<user_entry> user_entry_pointer_type; //TODO: renombrar class filesystem_item { public: typedef boost::shared_ptr<filesystem_item> pointer_type; typedef std::vector<pointer_type> collection_type; static filesystem_item::pointer_type create( const boost::filesystem::path& path, const user_entry_pointer_type& root_user_entry ) { filesystem_item::pointer_type watch ( new filesystem_item ( path, root_user_entry ) ); return watch; } static filesystem_item::pointer_type create( const boost::filesystem::path& path, const user_entry_pointer_type& root_user_entry, const filesystem_item::pointer_type& parent ) { filesystem_item::pointer_type watch ( new filesystem_item ( path, root_user_entry, parent ) ); return watch; } //TODO: proteger y poner deleter a la shared_ptr en metodo create... VER APUNTE QUE EXPLICA COMO HACERLO... ~filesystem_item() { //std::cout << "~filesystem_item()" << std::endl; //std::cout << "~filesystem_item() - " << path_.native_file_string() << std::endl; this->close( true, true ); //no-throw //std::cout << "END ~filesystem_item()" << std::endl; } //TODO: habilitar //bool operator==(const fs_item& other) const //{ // return ( this->path_ == other.path_ && this->inode_info_ == other.inode_info_ ); //} bool is_equal( const filesystem_item& other ) const { return ( this->path_ == other.path_ && this->inode_info_ == other.inode_info_ ); } bool is_equal( const filesystem_item::pointer_type& other) const { return ( this->path_ == other->path_ && this->inode_info_ == other->inode_info_ ); } bool is_equal(const file_inode_info& inode_info, const boost::filesystem::path& path) const { return ( this->inode_info_ == inode_info && this->path_ == path ); } void open() { this->file_descriptor_ = posix_syscall_wrapper::open_file( path_ ); this->inode_info_.set( this->path_ ); } //TODO: protected o no.... ????? ver! void close( bool no_throw = false, bool close_subitems = true ) { if ( this->file_descriptor_ != 0 ) { if ( close_subitems ) { for (filesystem_item::collection_type::iterator it = this->subitems_.begin(); it != this->subitems_.end(); ++it ) { (*it)->close( no_throw, close_subitems ); } } try { posix_syscall_wrapper::close_file( this->file_descriptor_ ); } catch ( std::runtime_error& e ) { if ( no_throw ) //Destructor -> no-throw { std::cerr << e.what() << " - File path: '" << this->path_.native_file_string() << "'"; } else { //TODO: ver como modificar el mensaje de una excepcion y relanzarla... // la idea no es armar otra excepcion sino usar la misma... std::ostringstream oss; oss << e.what() << " - File path: '" << this->path_.native_file_string() << "'"; //std::cout << "THROW - void filesystem_item::close( bool no_throw = false, bool close_subitems = true )" << std::endl; throw (std::runtime_error(oss.str())); } } this->file_descriptor_ = 0; } } void add_subitem ( const filesystem_item::pointer_type& subitem ) { //TODO: ver si se necesita completar algo... subitems_.push_back( subitem ); } void remove_subitem( const filesystem_item::pointer_type& watch ) { filesystem_item::collection_type::iterator it = subitems_.begin(); while ( it != subitems_.end() ) { if ( watch->is_equal( *it ) ) { it = subitems_.erase(it); break; } else { ++it; } } } void set_path ( const boost::filesystem::path& path ) { this->path_ = path; if ( boost::filesystem::is_directory( this->path_ ) ) { this->is_directory_ = true; } } void set_parent ( const filesystem_item::pointer_type& new_parent ) { this->parent_ = new_parent; } filesystem_item::pointer_type parent() const { //TODO: ver si usamos lock o si construimos un shared_ptr a partir del weak_ptr return this->parent_.lock(); } user_entry_pointer_type root_user_entry() const //user_entry::pointer_type { //TODO: ver si usamos lock o si construimos un shared_ptr a partir del weak_ptr return this->root_user_entry_.lock(); } const boost::filesystem::path& path() const { return this->path_; } bool is_directory() const { return this->is_directory_; } boost::uint32_t mask() const { return this->mask_; } protected: //TODO: asignar lo que el usuario quiere monitorear... filesystem_item( const boost::filesystem::path& path, const user_entry_pointer_type& root_user_entry ) : root_user_entry_(root_user_entry), is_directory_(false), file_descriptor_(0), mask_(PN_ALL_EVENTS) //parent_(0), { set_path( path ); } //TODO: asignar lo que el usuario quiere monitorear... filesystem_item ( const boost::filesystem::path& path, const user_entry_pointer_type& root_user_entry, const filesystem_item::pointer_type& parent ) : root_user_entry_(root_user_entry), parent_(parent), is_directory_(false), file_descriptor_(0), mask_(PN_ALL_EVENTS) { set_path( path ); } protected: public: //TODO: sacar boost::filesystem::path path_; bool is_directory_; public: //private: int file_descriptor_; //TODO: ver si es necesario boost::uint32_t mask_; file_inode_info inode_info_; boost::weak_ptr<filesystem_item> parent_; //to avoid circular references //TODO: ver que pasa si agregamos el mismo directorio como dos user_entry distintos... el open da el mismo file descriptor? boost::weak_ptr<user_entry> root_user_entry_; //to avoid circular references collection_type subitems_; }; } // namespace detail } // namespace os_services } // namespace boost #endif // BOOST_OS_SERVICES_DETAIL_FILESYSTEM_ITEM_HPP_INCLUDED
[ "fpelliccioni@07e413c0-050a-11df-afc1-2de6fd616bef" ]
[ [ [ 1, 266 ] ] ]
19e4f6a11eab805240964675b6f557f638dbc928
a352572bc22d863f72020118d8f5b94c69521f3f
/pa2/src/SphereCamera.cpp
b4d97122962f4bd78f0d9e56df7bb16fc5d4296a
[]
no_license
mjs513/cs4620-1
63345a9a7774279d8d6ab63b1af64d65b14b0ae3
419da5df73c5a9c34387b3cd2f7f3c542e0a3c3e
refs/heads/master
2021-01-10T06:45:47.809907
2010-12-10T20:59:46
2010-12-10T20:59:46
46,994,144
0
0
null
null
null
null
UTF-8
C++
false
false
3,590
cpp
/* * SphereCamera.cpp * * Created on: Oct 19, 2010 * Author: Roberto */ #include "SphereCamera.h" #include "OpenGL.h" #include "GLMatrix.h" #include <cmath> #include <iostream> namespace { const double DEFAULT_SENSITIVITY = 0.25; const double NEARVIEW = 2.0; // Minimum camera distance from center const double FARVIEW = 90.0; // Maximum camera distance from center // Update step sizes on camera movements const double LEFT_RIGHT_STEPS = 0.015; const double UP_DOWN_STEPS = 0.0075; const double ZOOM_STEPS = 0.2; } // namespace SphereCamera::SphereCamera(double radius) : _theta(0.0), _fi(M_PI/2 - 0.2), _p(20.0), _mouseSensitivity(DEFAULT_SENSITIVITY) { _zpos=_p*cos(_fi); _r=sqrt(_p*_p-_zpos*_zpos); _xpos=_r*cos(_theta); _ypos=_r*sin(_theta); } Point SphereCamera::eye() const { return Point(_xpos, _ypos, _zpos); } void SphereCamera::moveUp(double k) { if (_fi > 0.0) { _fi -= UP_DOWN_STEPS*k; _p = sqrt(_xpos*_xpos + _ypos*_ypos + _zpos*_zpos); _zpos = _p*cos(_fi); _r = sqrt (_p*_p - _zpos*_zpos); _xpos = _r*cos(_theta); _ypos = _r*sin(_theta); } } void SphereCamera::moveDown(double k) { if (_fi < M_PI/1.91) { _fi += UP_DOWN_STEPS*k; _p = sqrt(_xpos*_xpos + _ypos*_ypos + _zpos*_zpos); _zpos = _p*cos(_fi); _r = sqrt (_p*_p - _zpos*_zpos); _xpos = _r*cos(_theta); _ypos = _r*sin(_theta); } } void SphereCamera::moveRight(double k) { _theta+=LEFT_RIGHT_STEPS*k; _r = sqrt(_xpos*_xpos + _ypos*_ypos); _xpos = _r*cos(_theta); _ypos = _r*sin(_theta); } void SphereCamera::moveLeft(double k) { _theta-=LEFT_RIGHT_STEPS*k; _r = sqrt(_xpos*_xpos + _ypos*_ypos); _xpos = _r*cos(_theta); _ypos = _r*sin(_theta); } void SphereCamera::moveFront(double k) { _p = sqrt(_xpos*_xpos + _ypos*_ypos + _zpos*_zpos); if (_p<NEARVIEW) _p = NEARVIEW; _zpos = (_zpos * (_p-ZOOM_STEPS)) / _p; _p -= ZOOM_STEPS*k; // Avoid sqrt of negative number if (_p*_p - _zpos*_zpos < 0) _r = 1; else _r = sqrt (_p*_p - _zpos*_zpos); _xpos = _r*cos(_theta); _ypos = _r*sin(_theta); } void SphereCamera::moveBack(double k) { _p = sqrt(_xpos*_xpos + _ypos*_ypos + _zpos*_zpos); if (_p>FARVIEW-30.0) _p = FARVIEW-30.0; else { _zpos = (_zpos * (_p+ZOOM_STEPS)) / _p; _p += ZOOM_STEPS*k; } // Avoid sqrt of negative number if (_p*_p - _zpos*_zpos < 0) _r = 1; else _r = sqrt (_p*_p - _zpos*_zpos); _xpos = _r*cos(_theta); _ypos = _r*sin(_theta); } void SphereCamera::applyTransformation() const { gluLookAt (_xpos, _ypos, _zpos, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0); } void SphereCamera::mouseClicked(QMouseEvent *event) { _xOld = event->x(); _yOld = event->y(); } void SphereCamera::mouseMoved(QMouseEvent *event) { const double x = event->x(); const double y = event->y(); // Rotation handler if (event->buttons() & Qt::RightButton) { if (y - _yOld < 0) { moveDown(_mouseSensitivity*std::abs(y - _yOld)); } else if (y - _yOld > 0) { moveUp(_mouseSensitivity*std::abs(y - _yOld)); } if (x - _xOld < 0) { moveRight(_mouseSensitivity*std::abs(x - _xOld)); } else if (x - _xOld > 0) { moveLeft(_mouseSensitivity*std::abs(x - _xOld)); } } // Zoom handler if (event->buttons() & Qt::MiddleButton) { if (y - _yOld < 0) { moveFront(_mouseSensitivity*std::abs(y - _yOld)); // Zoom + } else if (y - _yOld > 0) { moveBack(_mouseSensitivity*std::abs(y - _yOld)); // Zoom - } } _xOld = x; _yOld = y; }
[ "robertorfischer@ebbd4279-5267-bd07-7df5-4dafc36418f6", "[email protected]" ]
[ [ [ 1, 20 ], [ 28, 35 ], [ 40, 43 ], [ 45, 48 ], [ 50, 50 ], [ 57, 60 ], [ 62, 62 ], [ 69, 73 ], [ 77, 81 ], [ 85, 89 ], [ 91, 91 ], [ 93, 93 ], [ 95, 97 ], [ 100, 100 ], [ 103, 106 ], [ 108, 108 ], [ 112, 112 ], [ 114, 115 ], [ 118, 118 ], [ 121, 124 ], [ 128, 135 ], [ 142, 142 ], [ 145, 145 ], [ 148, 148 ], [ 151, 151 ], [ 157, 157 ], [ 160, 160 ], [ 165, 165 ] ], [ [ 21, 27 ], [ 36, 39 ], [ 44, 44 ], [ 49, 49 ], [ 51, 56 ], [ 61, 61 ], [ 63, 68 ], [ 74, 76 ], [ 82, 84 ], [ 90, 90 ], [ 92, 92 ], [ 94, 94 ], [ 98, 99 ], [ 101, 102 ], [ 107, 107 ], [ 109, 111 ], [ 113, 113 ], [ 116, 117 ], [ 119, 120 ], [ 125, 127 ], [ 136, 141 ], [ 143, 144 ], [ 146, 147 ], [ 149, 150 ], [ 152, 156 ], [ 158, 159 ], [ 161, 164 ] ] ]
448c359f12e0c2c0edea5016e2ee395c492037c4
1e299bdc79bdc75fc5039f4c7498d58f246ed197
/App/LicenseCheckThread.h
e9a925d38b8dcc2c8493d5a67ee99ac074cc03c7
[]
no_license
moosethemooche/Certificate-Server
5b066b5756fc44151b53841482b7fa603c26bf3e
887578cc2126bae04c09b2a9499b88cb8c7419d4
refs/heads/master
2021-01-17T06:24:52.178106
2011-07-13T13:27:09
2011-07-13T13:27:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
997
h
//-------------------------------------------------------------------------------- // // Copyright (c) 2000 MarkCare Solutions // // Programming by Rich Schonthal // //-------------------------------------------------------------------------------- #ifndef _LICENSECHECKTHREAD_H_ #define _LICENSECHECKTHREAD_H_ //-------------------------------------------------------------------------------- #include "SSThread.h" class CSecuritySystem; //-------------------------------------------------------------------------------- class CLicenseCheckThread : public CSSThread { private: bool m_bRunOk; bool m_bFirstRun; CTime m_ctLastCheckLicFile; public: CLicenseCheckThread(CSystemObject*); private: virtual bool Init(); virtual bool MainLoop(); virtual DWORD GetThreadLoopSleepInterval() const; void DoChecking(); CSecuritySystem* GetParent() { return (CSecuritySystem*) CThreadObject::GetParent(); } }; #endif // _LICENSECHECKTHREAD_H_
[ [ [ 1, 36 ] ] ]
3c7031772faf4fb0c78c183a3e08b6def4f2e199
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/newton20/engine/ai/src/DialogVariable.cpp
c268e112787ec05629af18162bd884c5bf1c7676
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,090
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * 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 * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "stdinc.h" #include "DialogVariable.h" #include "Creature.h" #include "Dialog.h" #include "RulesSubsystem.h" #include "QuestBook.h" namespace rl { DialogVariable::DialogVariable(const CeGuiString& type) : mRecalculate(true), mType(type) { } DialogVariable::~DialogVariable() { } const CeGuiString& DialogVariable::getType() { return mType; } const Property& DialogVariable::getValue(Dialog* dialog) { if (mRecalculate) { mValue = calculateValue(dialog); mRecalculate = false; } return mValue; } void DialogVariable::invalidate() { mRecalculate = true; } DialogPropertyVariable::DialogPropertyVariable(const Ogre::String &propertyName) : DialogVariable("dialogvariable"), mPropertyName(propertyName) { } Property DialogPropertyVariable::calculateValue(Dialog* dialog) { return dialog->getProperty(mPropertyName); } QuestStateVariable::QuestStateVariable(const Ogre::String &questId, const Ogre::String &propertyName) : DialogVariable("queststate"), mQuestId(questId), mPropertyName(propertyName) { } Property QuestStateVariable::calculateValue(Dialog* dialog) { return RulesSubsystem::getSingleton().getQuestBook()->getQuest(mQuestId)->getProperty(mPropertyName); } TalentProbeVariable::TalentProbeVariable(const rl::CeGuiString &talent, int modifier, const rl::CeGuiString& target) : DialogVariable("talentcheck"), mTalent(talent), mTarget(target), mModifier(modifier) { } Property TalentProbeVariable::calculateValue(Dialog* dialog) { Creature* cr = NULL; if(mTarget == "pc") { cr = dialog->getPc(0); ///@todo allow multiple PCs } else if (mTarget == "npc") { cr = dialog->getNpc(0); } // if no target was given, use the player character. // @todo: remove this, target should be required! if(cr == NULL) { cr = dialog->getPc(0);} return Property(cr->doTalentprobe(mTalent, mModifier)); } EigenschaftsProbeVariable::EigenschaftsProbeVariable(const rl::CeGuiString &eigenschaft, int modifier, const rl::CeGuiString& target) : DialogVariable("attributecheck"), mEigenschaft(eigenschaft), mTarget(target), mModifier(modifier) { } Property EigenschaftsProbeVariable::calculateValue(Dialog* dialog) { Creature* cr = NULL; if(mTarget == "pc") { cr = dialog->getPc(0); ///@todo allow multiple PCs } else if (mTarget == "npc") { cr = dialog->getNpc(0); } // if no target was given, use the player character. // @todo: remove this, target should be required! if(cr == NULL) { cr = dialog->getPc(0);} return Property(cr->doEigenschaftsprobe(mEigenschaft, mModifier)); } RandomVariable::RandomVariable(int maximum) : DialogVariable("random"), mMaximum(maximum) { } Property RandomVariable::calculateValue(Dialog* dialog) { double d = std::rand(); return Property(static_cast<int>(d * mMaximum / RAND_MAX) + 1); } }
[ "melven@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 131 ] ] ]
573ca08f5c44513b19c5581a85d849b21805e491
2fdbf2ba994ba3ed64f0e2dc75cd2dfce4936583
/spectre/editforms/processdialog.cpp
409398d19f4b3965536c26ca9f27373992607872
[]
no_license
TERRANZ/terragraph
36219a4e512e15a925769512a6b60637d39830bf
ea8c36070f532ad0a4af08e46b19f4ee1b85f279
refs/heads/master
2020-05-25T10:31:26.994233
2011-01-29T21:23:04
2011-01-29T21:23:04
1,047,237
0
0
null
null
null
null
UTF-8
C++
false
false
3,589
cpp
#include "processdialog.h" #include "ui_objectdialog.h" #include "paramlistdialog.h" #include <QMessageBox> ProcessDialog::ProcessDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ObjectDialog) { m_EntryModel = new QStringListModel(this); ui->setupUi(this); ui->label_id->setText(tr("Имя процесса")); ui->label_templet->setText(tr("Схема генерации процесса")); ui->entry->setModel(m_EntryModel); connect(ui->save, SIGNAL(clicked()), this, SLOT(save())); connect(ui->cancel, SIGNAL(clicked()), this, SLOT(cancel())); connect(ui->params, SIGNAL(clicked()), this, SLOT(params())); } ProcessDialog::~ProcessDialog() { delete ui; } void ProcessDialog::setData(Process value) { m_Data = value; ui->id->setText(QString::fromStdString(m_Data.id())); ui->templet->setText(QString::fromStdString(m_Data.templet())); ui->rem->setText(QString::fromStdString(m_Data.rem())); ui->entry->setEditText(QString::fromStdString(m_Data.entry())); QStringList entrys; list<Port> ports = m_Data.portList(); { for(list<Port>::iterator i = ports.begin(); i != ports.end(); i++) { entrys<<QString::fromStdString(i->id()); } } list<Method> methods = m_Data.methodList(); { for(list<Method>::iterator i = methods.begin(); i != methods.end(); i++) { entrys<<QString::fromStdString(i->id()); } } m_EntryModel->setStringList(entrys); ui->entry->setCurrentIndex(ui->entry->findText(QString::fromStdString(m_Data.entry()))); } void ProcessDialog::save() { m_Data.setId(ui->id->text().toStdString()); m_Data.setTemplet(ui->templet->text().toStdString()); m_Data.setRem(ui->rem->text().toStdString()); m_Data.setEntry(ui->entry->currentText().toStdString()); accept(); } void ProcessDialog::params() { ParamListDialog dialog(this); dialog.setData(m_Data); dialog.exec(); } void ProcessDialog::cancel() { reject(); } bool ProcessDialog::addProcess(Module module, QWidget *parent) { // Process value = module.createProcess(); // ProcessDialog dialog(parent); // dialog.setData(value); // while(true) // { // if(dialog.exec() == QDialog::Accepted) // { // Process result = module.addProcess(value); // if(result.isNull()) // { // QMessageBox::information(parent, "Ошибка!", "Имя должно быть уникалльно."); // } // else // { // return true; // } // } // else // { // return false; // } // } return true; } bool ProcessDialog::editProcess(Process process, QWidget *parent) { // Process newProcess = process.clone().toProcess(); // ProcessDialog dialog(parent); // dialog.setData(newProcess); // while(true) // { // if(dialog.exec() == QDialog::Accepted) // { // Base result = process.replace(newProcess); // if(result.isNull()) // { // QMessageBox::information(parent, "Ошибка!", "Имя должно быть уникалльно."); // } // else // { // return true; // } // } // else // { // return false; // } // } return true; }
[ [ [ 1, 130 ] ] ]
f0061264cf6f2e55a3403b2fbf16be3a84a73a4e
b22c254d7670522ec2caa61c998f8741b1da9388
/physXtest/MapFileLoader.h
9a24ecb34290dc66e534a32bcfb98d722a9bb45c
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
2,151
h
/* ------------------------[ Lbanet Source ]------------------------- Copyright (C) 2009 Author: Vivien Delage [Rincevent_123] Email : [email protected] -------------------------------[ GNU License ]------------------------------- 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 3 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. If not, see <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------------- */ #if !defined(__LbaNetModel_1_MapFileLoader_h) #define __LbaNetModel_1_MapFileLoader_h #include <string> /* vector */ typedef float lba_vec3[3]; typedef float lba_vec4[4]; /* polygon */ struct MapFace { lba_vec3 p1Text; lba_vec3 p1Norm; lba_vec4 p1Vertex; lba_vec3 p2Text; lba_vec3 p2Norm; lba_vec4 p2Vertex; lba_vec3 p3Text; lba_vec3 p3Norm; lba_vec4 p3Vertex; }; /* obj model structure */ class MapModel { public: //! constructor MapModel(int nbfaces, MapFace * faces); //! destructor ~MapModel(); //! render void Render(); //! compile map for fast display void Compile(int YLimit); protected: void Uncompile(); private: MapFace * _faces; int _nbfaces; unsigned int _list_name; bool _compiled; }; /*********************************************************************** * Module: ObjFileLoader.h * Author: Vivien * Modified: dimanche 12 juillet 2009 21:09:21 * Purpose: Declaration of the class ObjFileLoader ***********************************************************************/ class MapFileLoader { public: static MapModel * LoadMapFile(const std::string &filename); }; #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 92 ] ] ]
5612fc3f2f7acd18089efce769f95b6b1a1ae0af
6dac9369d44799e368d866638433fbd17873dcf7
/src/branches/06112002/src/arch/Win32/OpenGL/WGLDevice.cpp
0613ef94cb8b6cc5c352ab72db04b6724b6632ae
[]
no_license
christhomas/fusionengine
286b33f2c6a7df785398ffbe7eea1c367e512b8d
95422685027bb19986ba64c612049faa5899690e
refs/heads/master
2020-04-05T22:52:07.491706
2006-10-24T11:21:28
2006-10-24T11:21:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,379
cpp
#include <Win32/OpenGL/WGLDevice.h> /** WGL Device Constructor */ WGLDevice::WGLDevice(){} /** WGL Device Deconstructor */ WGLDevice::~WGLDevice(){} /** Closes a WGL Enabled window * * This derived version deletes the WGL Device * context, then calls Win32Device::Close() to * finish off the generic window functions. */ bool WGLDevice::Close(void) { DeleteContext(); return Win32Device::Close(); } /** Creates a WGL Device Context * * @returns boolean true or false, depending on whether there * was a window open, if not, will return false to indicate no window available. * * Operation: * - Finds whether there is a window open. * - If Window open * -# resets the Pixel Format Descriptor. * -# Creates another Pixel Format Descriptor. * -# Tests the Pixel format, whether it's compatible. * - If Pixel Format succeeds * -# Sets the Pixel Format. * -# Creates the WGL Device Context. * -# Makes the Device Context current (sets it to active, basically). * -# Returns true. * * If anything fails, false is returned */ bool WGLDevice::CreateContext(void) { // Is there a window open if(IsOpen() == true) { // Create the Pixel format descriptor memset(&m_platform->m_pfd,0,sizeof(m_platform->m_pfd)); m_platform->m_pfd.nSize = sizeof(m_platform->m_pfd); // Size Of This Pixel Format Descriptor m_platform->m_pfd.nVersion = 1; // Version Number m_platform->m_pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; // Format Must Support Window,OpenGL,Double Buffering m_platform->m_pfd.iPixelType = PFD_TYPE_RGBA; // Request An RGBA Format m_platform->m_pfd.cColorBits = 32; // Select Our Color Depth m_platform->m_pfd.cDepthBits = 16; // 16Bit Z-Buffer (Depth Buffer) m_platform->m_pfd.iLayerType = PFD_MAIN_PLANE; // Main Drawing Layer // Get a device context for this window m_platform->m_hdc=GetDC(m_platform->m_hwnd); int PixelFormat; // Choose a pixel format, Set the window to that format if(PixelFormat = ChoosePixelFormat(m_platform->m_hdc,&m_platform->m_pfd)){ if(SetPixelFormat(m_platform->m_hdc,PixelFormat,&m_platform->m_pfd)){ // Create an OpenGL Rendering context and make that context current if(m_platform->m_hrc=wglCreateContext(m_platform->m_hdc)){ if(wglMakeCurrent(m_platform->m_hdc,m_platform->m_hrc)){ // Everything was ok, context created return true; } } } } } // Something failed, either a window wasnt open, or one other function failed return false; } /** Deletes the WGL Device Context */ void WGLDevice::DeleteContext(void) { wglDeleteContext(m_platform->m_hrc); } /** Sets the WGL Device's context to current (makes it active) */ void WGLDevice::SetContext(void) { wglMakeCurrent(m_platform->m_hdc, m_platform->m_hrc); } /** Retrieves the WGL Devices context */ void * WGLDevice::GetContext(void) { return (void *)m_platform->m_hrc; } /** Updates the WGL Window Device * First updates the Win32 Window, then Updates OpenGl's display */ void WGLDevice::Update(void) { Win32Device::Update(); SwapBuffers(m_platform->m_hdc); }
[ "chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7" ]
[ [ [ 1, 107 ] ] ]
2a1c1bc7816b325d9f8f32648dfbb379efa6beb7
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/src/UILayer/SMIRC/IrcWnd.h
31c373f6d30cc745f5459fcbac090b0e21e23857
[]
no_license
firespeed79/easymule
b2520bfc44977c4e0643064bbc7211c0ce30cf66
3f890fa7ed2526c782cfcfabb5aac08c1e70e033
refs/heads/master
2021-05-28T20:52:15.983758
2007-12-05T09:41:56
2007-12-05T09:41:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,711
h
//this file is part of eMule //Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) // //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; if not, write to the Free Software //Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #pragma once #include "./ResizableLib/ResizableDialog.h" #include "./IrcNickListCtrl.h" #include "./IrcChannelListCtrl.h" #include "./IrcChannelTabCtrl.h" #include "./SplitterControl.h" #if _DISABLE_NONUSE class CIrcMain; class CIrcWnd : public CResizableDialog { DECLARE_DYNAMIC(CIrcWnd) public: CIrcWnd(CWnd* pParent = NULL); virtual ~CIrcWnd(); void Localize(); bool GetLoggedIn(); void SetLoggedIn( bool bFlag ); void SetSendFileString( CString sInFile ); CString GetSendFileString(); bool IsConnected(); void UpdateFonts(CFont* pFont); void ParseChangeMode( CString sChannel, CString sChanger, CString sCommands, CString sParams ); void AddStatus( CString sReceived, ... ); void AddInfoMessage( CString sChannelName, CString sReceived, ... ); void AddColourLine(CString line, Channel* update_channel);//Interprets colour and other formatting tags void AddMessage( CString sChannelName, CString sTargetname, CString sLine,...); void SetConnectStatus( bool bConnected ); void NoticeMessage( CString sSource, CString sTarget, CString sMessage ); CString StripMessageOfFontCodes( CString sTemp ); CString StripMessageOfColorCodes( CString sTemp ); void SetTitle( CString sChannel, CString sTitle ); void SendString( CString sSend ); enum { IDD = IDD_IRC }; afx_msg void OnBnClickedClosechat(int iItem=-1); CEdit m_editTitleWindow; CEdit m_editInputWindow; CIrcMain* m_pIrcMain; CToolTipCtrl* m_pToolTip; CIrcChannelTabCtrl m_tabctrlChannelSelect; CIrcNickListCtrl m_listctrlNickList; CIrcChannelListCtrl m_listctrlServerChannelList; protected: virtual BOOL OnInitDialog(); virtual void OnSize(UINT iType, int iCx, int iCy); virtual int OnCreate(LPCREATESTRUCT lpCreateStruct); virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual BOOL OnCommand(WPARAM wParam,LPARAM lParam ); virtual BOOL PreTranslateMessage(MSG* pMsg); DECLARE_MESSAGE_MAP() afx_msg void OnSysColorChange(); afx_msg void OnBnClickedBnIrcconnect(); afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo); afx_msg void OnBnClickedChatsend(); afx_msg LRESULT OnCloseTab(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnQueryTab(WPARAM wParam, LPARAM lParam); afx_msg void OnBnClickedColour(); afx_msg void OnBnClickedUnderline(); afx_msg void OnBnClickedBold(); afx_msg void OnBnClickedReset(); afx_msg LONG OnSelEndOK(UINT lParam, LONG /*wParam*/); afx_msg LONG OnSelEndCancel(UINT lParam, LONG /*wParam*/); void DoResize(int iDelta); virtual LRESULT DefWindowProc(UINT uMessage, WPARAM wParam, LPARAM lParam); CSplitterControl m_wndSplitterIRC; private: void OnChatTextChange(); void AutoComplete(); CString m_sSendString; bool m_bLoggedIn; bool m_bConnected; }; #endif
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 94 ] ] ]
e3ec6abd8c765cd5221289c44e20458677224dc0
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak.wxWidgets/wxPropertiesWindow.cpp
6ea16090d7b9112efbc7cb2e68c1ad6366ac9a2a
[]
no_license
halak/halak-plusplus
d09ba78640c36c42c30343fb10572c37197cfa46
fea02a5ae52c09ff9da1a491059082a34191cd64
refs/heads/master
2020-07-14T09:57:49.519431
2011-07-09T14:48:07
2011-07-09T14:48:07
66,716,624
0
0
null
null
null
null
UTF-8
C++
false
false
9,240
cpp
#include <Halak.wxWidgets/PCH.h> #include <Halak.wxWidgets/wxPropertiesWindow.h> #include <Halak.wxWidgets/IPropertyUpdateable.h> #include <Halak.wxWidgets/wxNumberProperty.h> #include <Halak.wxWidgets/wxVector3Property.h> #include <Halak.Toolkit/Attributes.h> #include <Halak.Toolkit/ClassInfo.h> #include <Halak.Toolkit/PropertyInfo.h> #include <Halak/CommandHistory.h> #include <wx/propgrid/manager.h> #include <wx/propgrid/propdev.h> #include <wx/propgrid/advprops.h> using namespace Halak; using namespace Halak::Toolkit; namespace Halak { namespace wxWidgets { enum IDs { PropertyGridID = 100, }; BEGIN_EVENT_TABLE(wxPropertiesWindow, wxPanel) EVT_PG_SELECTED (PropertyGridID, wxPropertiesWindow::OnPropertyGridSelected) EVT_PG_CHANGED (PropertyGridID, wxPropertiesWindow::OnPropertyGridChanged) EVT_PG_CHANGING (PropertyGridID, wxPropertiesWindow::OnPropertyGridChanging) EVT_PG_HIGHLIGHTED (PropertyGridID, wxPropertiesWindow::OnPropertyGridHighlighted) EVT_PG_ITEM_COLLAPSED(PropertyGridID, wxPropertiesWindow::OnPropertyGridItemCollapsed) EVT_PG_ITEM_EXPANDED (PropertyGridID, wxPropertiesWindow::OnPropertyGridItemExpanded) END_EVENT_TABLE() wxPropertiesWindow::wxPropertiesWindow(wxWindow* parent) : wxPanel(parent, wxID_ANY), history(nullptr), propertyGridManager(nullptr), propertyGrid(nullptr), panel(nullptr), topSizer(nullptr) { const int style = wxPG_BOLD_MODIFIED | wxPG_SPLITTER_AUTO_CENTER | wxPG_AUTO_SORT /*| wxPG_TOOLTIPS*/ | wxPG_TOOLBAR | wxPG_DESCRIPTION; const int exStyle = wxPG_EX_MODE_BUTTONS | wxPG_EX_ENABLE_TLP_TRACKING | wxPG_EX_UNFOCUS_ON_ENTER | wxPG_EX_MULTIPLE_SELECTION /*| wxPG_EX_GREY_LABEL_WHEN_DISABLED*/; panel = new wxPanel(this, wxID_ANY, wxPoint(0, 0), wxSize(100, 100)); topSizer = new wxBoxSizer(wxVERTICAL); propertyGridManager = new wxPropertyGridManager(panel, PropertyGridID, wxDefaultPosition, wxDefaultSize, style); propertyGridManager->SetExtraStyle(exStyle); propertyGridManager->SetValidationFailureBehavior(wxPG_VFB_BEEP | wxPG_VFB_MARK_CELL | wxPG_VFB_SHOW_MESSAGE); propertyGrid = propertyGridManager->GetGrid(); propertyGrid->SetVerticalSpacing(2); propertyGrid->SetUnspecifiedValueAppearance(wxPGCell("Unspecified", wxNullBitmap, *wxLIGHT_GREY)); topSizer->Add(propertyGridManager, 1, wxEXPAND); panel->SetSizer(topSizer); topSizer->SetSizeHints(panel); wxBoxSizer* panelSizer = new wxBoxSizer(wxHORIZONTAL); panelSizer->Add(panel, 1, wxEXPAND | wxFIXED_MINSIZE); SetSizer(panelSizer); panelSizer->SetSizeHints(this); wxPropertyGridManager::RegisterAdditionalEditors(); } wxPropertiesWindow::~wxPropertiesWindow() { SetHistory(nullptr); // disconnect slots } void wxPropertiesWindow::UpdateProperties() { wxPropertyGridPage* page = propertyGridManager->GetPage(0); for (wxPropertyGridIterator it = page->GetIterator(); it.AtEnd() == false; it++) { if (IPropertyUpdateable* updateable = dynamic_cast<IPropertyUpdateable*>(*it)) updateable->UpdateFrom(targets); } } CommandHistory* wxPropertiesWindow::GetHistory() const { return history; } void wxPropertiesWindow::SetHistory(CommandHistory* value) { if (history != value) { if (history) { history->Redone().Disconnect(this, &wxPropertiesWindow::OnCommandRedone); history->Undone().Disconnect(this, &wxPropertiesWindow::OnCommandUndone); history->Executed().Disconnect(this, &wxPropertiesWindow::OnCommandExecuted); } history = value; if (history) { history->Executed().Connect(this, &wxPropertiesWindow::OnCommandExecuted); history->Undone().Connect(this, &wxPropertiesWindow::OnCommandUndone); history->Redone().Connect(this, &wxPropertiesWindow::OnCommandRedone); } } } const AnyPtr& wxPropertiesWindow::GetTargetPointee() const { if (targets.empty() == false) return targets.front(); else return AnyPtr::Null; } void wxPropertiesWindow::SetTarget(const AnyPtr& value) { if (value.GetPointeeType()->IsClass()) { targets.clear(); targets.push_back(value); FillPage(static_cast<const ClassInfo*>(value.GetPointeeType())); } } const wxPropertiesWindow::AnyPtrCollection& wxPropertiesWindow::GetTargets() const { return targets; } void wxPropertiesWindow::SetTargets(const AnyPtrCollection& value) { targets = value; //FillPage(TypeLibrary::GetInstance().Find<T::element_type>()); } void wxPropertiesWindow::OnPropertyGridSelected(wxPropertyGridEvent& event) { } void wxPropertiesWindow::OnPropertyGridChanged(wxPropertyGridEvent& event) { if (IPropertyUpdateable* updateable = dynamic_cast<IPropertyUpdateable*>(event.GetProperty())) updateable->UpdateTo(targets); } void wxPropertiesWindow::OnPropertyGridChanging(wxPropertyGridEvent& event) { } void wxPropertiesWindow::OnPropertyGridHighlighted(wxPropertyGridEvent& event) { } void wxPropertiesWindow::OnPropertyGridItemCollapsed(wxPropertyGridEvent& event) { } void wxPropertiesWindow::OnPropertyGridItemExpanded(wxPropertyGridEvent& event) { } void wxPropertiesWindow::OnCommandExecuted(CommandHistory* sender, Command* /*command*/, const std::list<Command*>& /*cancelledCommands*/) { HKAssert(history == sender); UpdateProperties(); } void wxPropertiesWindow::OnCommandUndone(CommandHistory* sender, const std::list<Command*>& /*commands*/) { HKAssert(history == sender); UpdateProperties(); } void wxPropertiesWindow::OnCommandRedone(CommandHistory* sender, const std::list<Command*>& /*commands*/) { HKAssert(history == sender); UpdateProperties(); } void wxPropertiesWindow::FillPage(const ClassInfo* classInfo) { const int numberOfPages = propertyGridManager->GetPageCount(); for (int i = numberOfPages - 1; i >= 0; i--) propertyGridManager->RemovePage(i); int index = propertyGridManager->AddPage(classInfo->GetName()); wxPropertyGridPage* propertyGridPage = propertyGridManager->GetPage(index); const ClassInfo::PropertyCollection& properties = classInfo->GetProperties(); for (ClassInfo::PropertyCollection::const_iterator it = properties.begin(); it != properties.end(); it++) { wxPGProperty* newProperty = nullptr; if (String((*it)->GetName()) == "LinearVelocity1" || String((*it)->GetName()) == "LinearVelocity2") { newProperty = new wxVector3Property((*it)->GetName(), wxPG_LABEL, history, (*it)); } else if (String((*it)->GetName()) == "Lifespan1" || String((*it)->GetName()) == "Lifespan2") { newProperty = new wxNumberProperty((*it)->GetName(), wxPG_LABEL, history, (*it)); } else { newProperty = new wxIntProperty((*it)->GetName(), wxPG_LABEL, 0); } if (const UnitAttribute* attribute = (*it)->FindAttribute<UnitAttribute>()) newProperty->SetAttribute(wxPG_ATTR_UNITS, attribute->GetName()); newProperty->SetClientData((void*)(*it)); propertyGridPage->Append(newProperty); } UpdateProperties(); } } }
[ [ [ 1, 232 ] ] ]
81987e959bc238b78e05e5e26d893d5f7e2c1a0f
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Intersection/Wm4IntrPlane3Capsule3.h
51e8eea542393610e9249a56120352f236315063
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
1,479
h
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #ifndef WM4INTRPLANE3CAPSULE3_H #define WM4INTRPLANE3CAPSULE3_H #include "Wm4FoundationLIB.h" #include "Wm4Intersector.h" #include "Wm4Plane3.h" #include "Wm4Capsule3.h" namespace Wm4 { template <class Real> class WM4_FOUNDATION_ITEM IntrPlane3Capsule3 : public Intersector<Real,Vector3<Real> > { public: IntrPlane3Capsule3 (const Plane3<Real>& rkPlane, const Capsule3<Real>& rkCapsule); // object access const Plane3<Real>& GetPlane () const; const Capsule3<Real>& GetCapsule () const; // static intersection query virtual bool Test (); // Culling support. The view frustum is assumed to be on the positive // side of the plane. The capsule is culled if it is on the negative // side of the plane. bool CapsuleIsCulled () const; protected: // the objects to intersect const Plane3<Real>& m_rkPlane; const Capsule3<Real>& m_rkCapsule; }; typedef IntrPlane3Capsule3<float> IntrPlane3Capsule3f; typedef IntrPlane3Capsule3<double> IntrPlane3Capsule3d; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 53 ] ] ]
7fc50072b209d5ab4221ae6ad0f0ac962e1ff288
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Scd/FlwLib/SparseSlv/Indirect/mv/include/mvvtp.h
6e4075635629d538badaa2ab0c2e8b855f78a4c0
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,700
h
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /* */ /* */ /* MV++ Numerical Matrix/Vector C++ Library */ /* MV++ Version 1.5 */ /* */ /* R. Pozo */ /* National Institute of Standards and Technology */ /* */ /* NOTICE */ /* */ /* Permission to use, copy, modify, and distribute this software and */ /* its documentation for any purpose and without fee is hereby granted */ /* provided that this permission notice appear in all copies and */ /* supporting documentation. */ /* */ /* Neither the Institution (National Institute of Standards and Technology) */ /* nor the author makes any representations about the suitability of this */ /* software for any purpose. This software is provided ``as is''without */ /* expressed or implied warranty. */ /* */ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ // // mvvtp.h Basic templated vector class // #ifndef _MV_VECTOR_TPL_H_ #define _MV_VECTOR_TPL_H_ #include <stdlib.h> #ifdef MV_VECTOR_BOUNDS_CHECK # include <assert.h> #endif #include "mvvind.h" #include "mvvrf.h" template <class TYPE> class MV_Vector { protected: TYPE *p_; int dim_; int ref_; // 0 or 1; does this own its own memory space? public: /*::::::::::::::::::::::::::*/ /* Constructors/Destructors */ /*::::::::::::::::::::::::::*/ MV_Vector(); MV_Vector( int); MV_Vector( int, const TYPE&); MV_Vector(TYPE*, int); MV_Vector(const TYPE*, int); // reference of an exisiting data structure // MV_Vector(TYPE*, int, MV_Vector_::ref_type i); MV_Vector(const MV_Vector<TYPE>&); ~MV_Vector(); /*::::::::::::::::::::::::::::::::*/ /* Indices and access operations */ /*::::::::::::::::::::::::::::::::*/ inline TYPE& operator()( int i) { # ifdef MV_VECTOR_BOUNDS_CHECK assert(i < dim_); # endif return p_[i]; } inline const TYPE& operator()( int i) const { # ifdef MV_VECTOR_BOUNDS_CHECK assert(i < dim_); # endif return p_[i]; } inline TYPE& operator[]( int i) { # ifdef MV_VECTOR_BOUNDS_CHECK assert(i < dim_); # endif return p_[i]; } inline const TYPE& operator[]( int i) const { # ifdef MV_VECTOR_BOUNDS_CHECK assert(i < dim_); # endif return p_[i]; } inline MV_Vector<TYPE> operator()(const MV_VecIndex &I) ; inline MV_Vector<TYPE> operator()(void); inline const MV_Vector<TYPE> operator()(void) const; inline const MV_Vector<TYPE> operator()(const MV_VecIndex &I) const; inline int size() const { return dim_;} inline int ref() const { return ref_;} inline int null() const {return dim_== 0;} // // Create a new *uninitalized* vector of size N MV_Vector<TYPE> & newsize( int ); /*::::::::::::::*/ /* Assignment */ /*::::::::::::::*/ MV_Vector<TYPE> & operator=(const MV_Vector<TYPE>&); MV_Vector<TYPE> & operator=(const TYPE&); }; template <class TYPE> MV_Vector<TYPE>::MV_Vector() : p_(0), dim_(0) , ref_(0){}; template <class TYPE> MV_Vector<TYPE>::MV_Vector( int n) : p_(new TYPE[n]), dim_(n), ref_(0) { if (p_ == NULL) { cerr << "Error: NULL pointer in MV_Vector(int) constructor " << endl; cerr << " Most likely out of memory... " << endl; exit(1); } } template <class TYPE> MV_Vector<TYPE>::MV_Vector( int n, const TYPE& v) : p_(new TYPE[n]), dim_(n), ref_(0) { if (p_ == NULL) { cerr << "Error: NULL pointer in MV_Vector(int) constructor " << endl; cerr << " Most likely out of memory... " << endl; exit(1); } for (int i=0; i<n; i++) p_[i] = v; } // operators and member functions // template <class TYPE> MV_Vector<TYPE>& MV_Vector<TYPE>::operator=(const TYPE & m) { #ifdef TRACE_VEC cout << "> MV_Vector<TYPE>::operator=(const TYPE & m) " << endl; #endif // unroll loops to depth of length 4 int N = size(); int Nminus4 = N-4; int i; for (i=0; i<Nminus4; ) { p_[i++] = m; p_[i++] = m; p_[i++] = m; p_[i++] = m; } for (; i<N; p_[i++] = m); // finish off last piece... #ifdef TRACE_VEC cout << "< MV_Vector<TYPE>::operator=(const TYPE & m) " << endl; #endif return *this; } template <class TYPE> MV_Vector<TYPE>& MV_Vector<TYPE>::newsize( int n) { #ifdef TRACE_VEC cout << "> MV_Vector<TYPE>::newsize( int n) " << endl; #endif if (ref_ ) // is this structure just a pointer? { { cerr << "MV_Vector::newsize can't operator on references.\n"; exit(1); } } else if (dim_ != n ) // only delete and new if { // the size of memory is really if (p_) delete [] p_; // changing, otherwise just p_ = new TYPE[n]; // copy in place. if (p_ == NULL) { cerr << "Error : NULL pointer in operator= " << endl; exit(1); } dim_ = n; } #ifdef TRACE_VEC cout << "< MV_Vector<TYPE>::newsize( int n) " << endl; #endif return *this; } template <class TYPE> MV_Vector<TYPE>& MV_Vector<TYPE>::operator=(const MV_Vector<TYPE> & m) { int N = m.dim_; int i; if (ref_ ) // is this structure just a pointer? { if (dim_ != m.dim_) // check conformance, { cerr << "MV_VectorRef::operator= non-conformant assignment.\n"; exit(1); } // handle overlapping matrix references if ((m.p_ + m.dim_) >= p_) { // overlap case, copy backwards to avoid overwriting results for (i= N-1; i>=0; i--) p_[i] = m.p_[i]; } else { for (i=0; i<N; i++) p_[i] = m.p_[i]; } } else { newsize(N); // no need to test for overlap, since this region is new for (i =0; i< N; i++) // careful not to use bcopy() p_[i] = m.p_[i]; // here, but TYPE::operator= TYPE. } return *this; } template <class TYPE> MV_Vector<TYPE>::MV_Vector(const MV_Vector<TYPE> & m) : p_(new TYPE[m.dim_]), dim_(m.dim_) , ref_(0) { if (p_ == NULL) { cerr << "Error: Null pointer in MV_Vector(const MV_Vector&); " << endl; exit(1); } int N = m.dim_; for (int i=0; i<N; i++) p_[i] = m.p_[i]; } // note that ref() is initalized with i rather than 1. // this is so compilers will not generate a warning that i was // not used in the construction. (MV_Vector::ref_type is an enum that // can *only* have the value of 1. // template <class TYPE> MV_Vector<TYPE>::MV_Vector(TYPE* d, int n, MV_Vector_::ref_type i) : p_(d), dim_(n) , ref_(i) {} template <class TYPE> MV_Vector<TYPE>::MV_Vector(TYPE* d, int n) : p_(new TYPE[n]), dim_(n) , ref_(0) { if (p_ == NULL) { cerr << "Error: Null pointer in MV_Vector(TYPE*, int) " << endl; exit(1); } for (int i=0; i<n; i++) p_[i] = d[i]; } template <class TYPE> MV_Vector<TYPE>::MV_Vector(const TYPE* d, int n) : p_(new TYPE[n]), dim_(n) , ref_(0) { if (p_ == NULL) { cerr << "Error: Null pointer in MV_Vector(TYPE*, int) " << endl; exit(1); } for (int i=0; i<n; i++) p_[i] = d[i]; } template <class TYPE> MV_Vector<TYPE> MV_Vector<TYPE>::operator()(void) { return MV_Vector<TYPE>(p_, dim_, MV_Vector_::ref); } template <class TYPE> const MV_Vector<TYPE> MV_Vector<TYPE>::operator()(void) const { return MV_Vector<TYPE>(p_, dim_, MV_Vector_::ref); } template <class TYPE> MV_Vector<TYPE> MV_Vector<TYPE>::operator()(const MV_VecIndex &I) { // default parameters if (I.all()) return MV_Vector<TYPE>(p_, dim_, MV_Vector_::ref); else { // check that index is not out of bounds // if ( I.end() >= dim_) { cerr << "MV_VecIndex: (" << I.start() << ":" << I.end() << ") too big for matrix (0:" << dim_ - 1 << ") " << endl; exit(1); } return MV_Vector<TYPE>(p_+ I.start(), I.end() - I.start() + 1, MV_Vector_::ref); } } template <class TYPE> const MV_Vector<TYPE> MV_Vector<TYPE>::operator()(const MV_VecIndex &I) const { // check that index is not out of bounds // if ( I.end() >= dim_) { cerr << "MV_VecIndex: (" << I.start() << ":" << I.end() << ") too big for matrix (0:" << dim_ - 1 << ") " << endl; exit(1); } return MV_Vector<TYPE>(p_+ I.start(), I.end() - I.start() + 1, MV_Vector_::ref); } template <class TYPE> MV_Vector<TYPE>::~MV_Vector() { if (p_ && !ref_ ) delete [] p_; } template <class TYPE> class FMV_Vector : public MV_Vector<TYPE> { public: FMV_Vector( int n) : MV_Vector<TYPE>(n) {} FMV_Vector<TYPE>& operator=(const FMV_Vector<TYPE>& m); FMV_Vector<TYPE>& operator=(const TYPE& m); }; template <class TYPE> FMV_Vector<TYPE>& FMV_Vector<TYPE>::operator=( const FMV_Vector<TYPE>& m) { #ifdef TRACE_VEC cout << "> FMV_Vector<TYPE>::operator=( const FMV_Vector<TYPE>& m)" << endl; #endif int N = m.dim_; if (ref_ ) // is this structure just a pointer? { if (dim_ != m.dim_) // check conformance, { cerr << "MV_VectorRef::operator= non-conformant assignment.\n"; exit(1); } } else if ( dim_ != m.dim_ ) // resize only if necessary newsize(N); memmove(p_, m.p_, N * sizeof(TYPE)); #ifdef TRACE_VEC cout << "< FMV_Vector<TYPE>::operator=( const FMV_Vector<TYPE>& m)" << endl; #endif return *this; } template <class TYPE> FMV_Vector<TYPE>& FMV_Vector<TYPE>::operator=(const TYPE & m) { #ifdef TRACE_VEC cout << "> FMV_Vector<TYPE>::operator=(const TYPE & m) " << endl; #endif // unroll loops to depth of length 4 int N = size(); int Nminus4 = N-4; int i; for (i=0; i<Nminus4; ) { p_[i++] = m; p_[i++] = m; p_[i++] = m; p_[i++] = m; } for (; i<N; p_[i++] = m); // finish off last piece... #ifdef TRACE_VEC cout << "< FMV_Vector<TYPE>::operator=(const TYPE & m) " << endl; #endif return *this; } #include "mvblas.h" #endif // _MV_VECTOR_TPL_H_
[ [ [ 1, 453 ] ] ]
59a918f4a0255f6e215723708ee1cf8c5e0e9a51
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Integration_WAH_&_Extraction/SMDataExtraction/Algorithm/NaiveBayes.h
75de15eb3a276112b8e621b555e4cee25b62476d
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
1,937
h
#pragma once #include "datasource.h" #include <iostream> #include "classifiertestsource.h" #include "instances.h" #include "smalgorithmexceptions.h" using namespace std; /************************************************************************ * Class :NaiveBayes * Author :Amila De Silva * Subj : * Class for building and using a simple Naive Bayes classifier. * Numeric attributes are modelled by a normal distribution. * * Version: 1 ************************************************************************/ class NaiveBayes { public: /*** * Constructor */ _declspec(dllexport) NaiveBayes(void); /*** * Destructor */ _declspec(dllexport) ~NaiveBayes(void); /**Generates the classifier. */ _declspec(dllexport) void buildClassifier(WrapDataSource * instances,int class_index) throw (algorithm_exception); /**Prints the value of m_count*/ _declspec(dllexport) void PrintCountArr(double *** array); /** Returns a description of the classifier.*/ _declspec(dllexport) string toString(); /** Classifies the supplied test set using the model created*/ _declspec(dllexport) void ClassifyInstances(ClassifierTestSource * _source) throw (algorithm_exception); protected: /** All the counts for nominal attributes. */ double *** m_Counts; /** The means for numeric attributes. */ double ** m_Means; /** The standard deviations for numeric attributes. */ double ** m_Devs; /** The prior probabilities of the classes. */ double * m_Priors; /** The instances used for training. */ //DataSource * m_Instances; Instances * m_Instances; /** The class index used for current model. */ int m_class_index; private: /**Initializes the pointers to NULL*/ void Init(); /** Classifies a single instance*/ int ClassifyInstance(double * _inputs,size_t _no_of_atts,WrapDataSource * _header) throw (algorithm_exception); };
[ "jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 70 ] ] ]
e1f10ceb9499c78367683d6cd45966ea37139542
bfe8eca44c0fca696a0031a98037f19a9938dd26
/libjingle-0.4.0/talk/examples/login/xmppthread.h
138e0589d54d3e27d489263f0ec7c90cf382932c
[ "BSD-3-Clause" ]
permissive
luge/foolject
a190006bc0ed693f685f3a8287ea15b1fe631744
2f4f13a221a0fa2fecab2aaaf7e2af75c160d90c
refs/heads/master
2021-01-10T07:41:06.726526
2011-01-21T10:25:22
2011-01-21T10:25:22
36,303,977
0
0
null
null
null
null
UTF-8
C++
false
false
2,212
h
/* * libjingle * Copyright 2004--2005, Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _XMPPTHREAD_H_ #define _XMPPTHREAD_H_ #include "talk/xmpp/xmppclientsettings.h" #include "talk/base/thread.h" #include "talk/examples/login/xmpppump.h" #include "talk/examples/login/xmppsocket.h" #include <iostream> class XmppThread: public talk_base::Thread, XmppPumpNotify, talk_base::MessageHandler { public: XmppThread(); ~XmppThread(); buzz::XmppClient* client() { return pump_->client(); } void ProcessMessages(int cms); void Login(const buzz::XmppClientSettings & xcs); void Disconnect(); private: XmppPump* pump_; void OnStateChange(buzz::XmppEngine::State state); void OnMessage(talk_base::Message* pmsg); }; #endif // _XMPPTHREAD_H_
[ "[email protected]@756bb6b0-a119-0410-8338-473b6f1ccd30" ]
[ [ [ 1, 57 ] ] ]
832a38a6224d33d4a8d40ceb631d24aa8eb76b85
bfdfb7c406c318c877b7cbc43bc2dfd925185e50
/compiler/hyCJumpControlTree.cpp
b06161b6642599a66784571b90c3c09457372f9c
[ "MIT" ]
permissive
ysei/Hayat
74cc1e281ae6772b2a05bbeccfcf430215cb435b
b32ed82a1c6222ef7f4bf0fc9dedfad81280c2c0
refs/heads/master
2020-12-11T09:07:35.606061
2011-08-01T12:38:39
2011-08-01T12:38:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,292
cpp
/* -*- coding: sjis-dos; -*- */ /* * copyright 2010 FUKUZAWA Tadashi. All rights reserved. */ #include "hyCJumpControlTree.h" #include "hyCSymbolTable.h" #include "hyCContext.h" #include "hyMemPool.h" #include "hyEndian.h" namespace Hayat { namespace Compiler { extern SymbolTable gSymTable; } } using namespace Hayat::Common; using namespace Hayat::Compiler;; extern void compileError(const char* fmt, ...); const hyu32 JumpControlTree::INVALID_ADDR = (hyu32)-1; void* JumpControlTree::operator new(size_t size) { HMD_DEBUG_ASSERT_EQUAL(sizeof(JumpControlTree), size); MemCell* p = gMemPool->alloc(sizeof(JumpControlTree)); p->setMemID("JCT "); return (void*)p; } void JumpControlTree::operator delete(void* p) { gMemPool->free(p); } JumpControlTree::JumpControlTree(JumpControlTree* parent) : m_parent(parent), m_labelAddrs(0), m_res(0), m_childs(0), startAddr(0) { } JumpControlTree::~JumpControlTree() { m_labelAddrs.finalize(); TArray<TArray<hyu32> >& resolveAddrsArr = m_res.values(); TArrayIterator<TArray<hyu32> > itr(&resolveAddrsArr); while (itr.hasMore()) itr.next().finalize(); m_res.finalize(); m_childs.finalize(); } JumpControlTree* JumpControlTree::newChild(void) { JumpControlTree* p = new JumpControlTree(this); m_childs.add(p); return p; } hyu32 JumpControlTree::getLocalLabelAddr(SymbolID_t label) { hyu32* p = m_labelAddrs.find(label); if (p != NULL) return *p; return INVALID_ADDR; } hyu32 JumpControlTree::getLabelAddr(SymbolID_t label) { hyu32* p = m_labelAddrs.find(label); if (p != NULL) return *p; if (m_parent != NULL) return m_parent->getLabelAddr(label); return INVALID_ADDR; } void JumpControlTree::addLabel(SymbolID_t label, hyu32 addr) { if (m_labelAddrs.find(label) != NULL) compileError(M_M("same label '%s' in same context"), gSymTable.id2str(label)); m_labelAddrs[label] = addr; } void JumpControlTree::addResolveAddr(SymbolID_t label, hyu32 resolveAddr) { TArray<hyu32>* p = m_res.find(label); if (p != NULL) { p->add(resolveAddr); } else { TArray<hyu32>& arr = m_res[label]; arr.initialize(1); arr.setContentsMemID("JCTr"); arr.add(resolveAddr); } } void JumpControlTree::resolve(Context* context) { m_resolveLocal(context); hyu32 n = m_childs.size(); for (hyu32 i = 0; i < n; i++) { m_childs[i]->resolve(context); } } void JumpControlTree::m_resolveLocal(Context* context) { TArray<SymbolID_t>& labelArr = m_res.keys(); TArray<TArray<hyu32> >& resolveAddrsArr = m_res.values(); hyu32 n = labelArr.size(); for (hyu32 i = 0; i < n; i++) { SymbolID_t label = labelArr[i]; TArray<hyu32>& resolveAddrs = resolveAddrsArr[i]; hyu32 adr = getLocalLabelAddr(label); if (adr != INVALID_ADDR) { hyu32 m = resolveAddrs.size(); for (hyu32 j = 0; j < m; j++) { context->resolveJumpAddr(resolveAddrs[j], adr); } } else { hyu32 m = resolveAddrs.size(); for (hyu32 j = 0; j < m; j++) { context->replaceJumpControl(resolveAddrs[j], label); } } } } TArray<hyu8>* JumpControlTree::genCode(void) { TArray<hyu8>* bin = new TArray<hyu8>(8); TArray<hyu8> lbl; TArray<hyu8> adr; TArray<SymbolID_t>& syms = m_labelAddrs.keys(); hyu32 n = syms.size(); HMD_ASSERT(n < 256); for (hyu32 i = 0; i < n; i++) { SymbolID_t sym = syms[i]; packOut<SymbolID_t>(lbl, sym); packOut<hys32>(adr, m_labelAddrs[sym] - startAddr); } bin->add(n); bin->add(2); bin->add(1); bin->add(0); bin->add(lbl); bin->align(4, 0xf9); bin->add(adr); return bin; } bool JumpControlTree::haveLabel(SymbolID_t label) { if (m_labelAddrs.keys().isInclude(label)) return true; hyu32 n = m_childs.size(); for (hyu32 i = 0; i < n; ++i) if (m_childs[i]->haveLabel(label)) return true; return false; }
[ [ [ 1, 163 ] ] ]
7aa2e4155778a5fcd187cd74844c78d2a262adfa
b22c254d7670522ec2caa61c998f8741b1da9388
/dependencies/OpenSceneGraph/include/osgGA/UFOManipulator
76f7230bc097d9075c9223a1cbb1ab31b13e8ef8
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
6,987
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library 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 * OpenSceneGraph Public License for more details. */ #ifndef OSGGA_UFO_MANIPULATOR_DEF #define OSGGA_UFO_MANIPULATOR_DEF 1 #include <iostream> #include <osgGA/MatrixManipulator> #include <osg/Node> #include <osg/Matrix> /** \class osgGA::UFOManipulator \brief A UFO manipulator driven with keybindings. The UFOManipulator is better suited for applications that employ architectural walk-throughs, or situations where the eyepoint motion model must move slowly, deliberately and well controlled. The UFO Manipulator allows the following movements with the listed Key combinations: \param UpArrow Acceleration forward. \param DownArrow Acceleration backward (or deceleration forward). \param LeftArrow Rotate view and direction of travel to the left. \param RightArrow Rotate view and direction of travel to the right. \param SpaceBar Brake. Gradually decelerates linear and rotational movement. \param Shift/UpArrow Accelerate up. \param Shift/DownArrow Accelerate down. \param Shift/LeftArrow Accelerate (linearly) left. \param Shift/RightArrow Accelerate (linearly) right. \param Shift/SpaceBar Instant brake. Immediately stop all linear and rotational movement. When the Shift key is released, up, down, linear left and/or linear right movement is decelerated. \param Ctrl/UpArrow Rotate view (but not direction of travel) up. \param Ctrl/DownArrow Rotate view (but not direction of travel) down. \param Ctrl/LeftArrow Rotate view (but not direction of travel) left. \param Ctrl/RightArrow Rotate view (but not direction of travel) right. \param Ctrl/Return Straightens out the view offset. */ namespace osgGA { class OSGGA_EXPORT UFOManipulator : public osgGA::MatrixManipulator { public: /** Default constructor */ UFOManipulator(); /** return className \return returns constant "UFO" */ virtual const char* className() const; /** Set the current position with a matrix \param matrix A viewpoint matrix. */ virtual void setByMatrix( const osg::Matrixd &matrix ) ; /** Set the current position with the inverse matrix \param invmat The inverse of a viewpoint matrix */ virtual void setByInverseMatrix( const osg::Matrixd &invmat); /** Get the current viewmatrix */ virtual osg::Matrixd getMatrix() const; /** Get the current inverse view matrix */ virtual osg::Matrixd getInverseMatrix() const ; /** Set the subgraph this manipulator is driving the eye through. \param node root of subgraph */ virtual void setNode(osg::Node* node); /** Get the root node of the subgraph this manipulator is driving the eye through (const)*/ virtual const osg::Node* getNode() const; /** Get the root node of the subgraph this manipulator is driving the eye through */ virtual osg::Node* getNode(); /** Computes the home position based on the extents and scale of the scene graph rooted at node */ virtual void computeHomePosition(); /** Sets the viewpoint matrix to the home position */ virtual void home(const osgGA::GUIEventAdapter&, osgGA::GUIActionAdapter&) ; void home(double); virtual void init(const GUIEventAdapter& ,GUIActionAdapter&); /** Handles incoming osgGA events */ bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter &aa); /** Reports Usage parameters to the application */ void getUsage(osg::ApplicationUsage& usage) const; /** Report the current position as LookAt vectors */ void getCurrentPositionAsLookAt( osg::Vec3 &eye, osg::Vec3 &center, osg::Vec3 &up ); void setMinHeight( double in_min_height ) { _minHeightAboveGround = in_min_height; } double getMinHeight() const { return _minHeightAboveGround; } void setMinDistance( double in_min_dist ) { _minDistanceInFront = in_min_dist; } double getMinDistance() const { return _minDistanceInFront; } void setForwardSpeed( double in_fs ) { _forwardSpeed = in_fs; } double getForwardSpeed() const { return _forwardSpeed; } void setSideSpeed( double in_ss ) { _sideSpeed = in_ss; } double getSideSpeed() const { return _sideSpeed; } void setRotationSpeed( double in_rot_speed ) { _directionRotationRate = in_rot_speed; } double getRotationSpeed() const { return _directionRotationRate; } protected: virtual ~UFOManipulator(); bool intersect(const osg::Vec3d& start, const osg::Vec3d& end, osg::Vec3d& intersection) const; osg::observer_ptr<osg::Node> _node; float _viewAngle; osg::Matrixd _matrix; osg::Matrixd _inverseMatrix; osg::Matrixd _offset; double _minHeightAboveGround; double _minDistanceInFront; double _speedEpsilon; double _forwardSpeed; double _sideSpeed; double _upSpeed; double _speedAccelerationFactor; double _speedDecelerationFactor; bool _decelerateUpSideRate; double _directionRotationEpsilon; double _directionRotationRate; double _directionRotationAcceleration; double _directionRotationDeceleration; double _viewOffsetDelta; double _pitchOffsetRate; double _pitchOffset; double _yawOffsetRate; double _yawOffset; double _t0; double _dt; osg::Vec3d _direction; osg::Vec3d _position; bool _shift; bool _ctrl; bool _decelerateOffsetRate; bool _straightenOffset; void _stop(); void _keyDown( const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &); void _keyUp( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter &); void _frame(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter &); void _adjustPosition(); }; } #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 188 ] ] ]
5d0c998858da0e67aad44afc0840596635114892
cc336f796b029620d6828804a866824daa6cc2e0
/cximage/CxImage/ximawbmp.cpp
30c2af50cd8c5bfadbdc0fee33ee21d7fc0728d2
[]
no_license
tokyovigilante/xbmc-sources-fork
84fa1a4b6fec5570ce37a69d667e9b48974e3dc3
ac3c6ef8c567f1eeb750ce6e74c63c2d53fcde11
refs/heads/master
2021-01-19T10:11:37.336476
2009-03-09T20:33:58
2009-03-09T20:33:58
29,232
2
0
null
null
null
null
UTF-8
C++
false
false
2,458
cpp
// Place the code and data below here into the CXIMAGE section. #ifndef _DLL #pragma code_seg( "CXIMAGE" ) #pragma data_seg( "CXIMAGE_RW" ) #pragma bss_seg( "CXIMAGE_RW" ) #pragma const_seg( "CXIMAGE_RD" ) #pragma comment(linker, "/merge:CXIMAGE_RW=CXIMAGE") #pragma comment(linker, "/merge:CXIMAGE_RD=CXIMAGE") #endif /* * File: ximawbmp.cpp * Purpose: Platform Independent WBMP Image Class Loader and Writer * 12/Jul/2002 <[email protected]> * CxImage version 5.80 29/Sep/2003 */ #include "ximawbmp.h" #if CXIMAGE_SUPPORT_WBMP #include "ximaiter.h" //////////////////////////////////////////////////////////////////////////////// bool CxImageWBMP::Decode(CxFile *hFile) { if (hFile == NULL) return false; WBMPHEADER wbmpHead; try { if (hFile->Read(&wbmpHead,sizeof(wbmpHead),1)==0) throw "Not a WBMP"; if (wbmpHead.Type != 0) throw "Unsupported WBMP type"; if (wbmpHead.ImageHeight==0 || wbmpHead.ImageWidth==0) throw "Corrupted WBMP"; Create(wbmpHead.ImageWidth, wbmpHead.ImageHeight, 1, CXIMAGE_FORMAT_WBMP); if (!IsValid()) throw "WBMP Create failed"; SetGrayPalette(); int linewidth=(wbmpHead.ImageWidth+7)/8; CImageIterator iter(this); iter.Upset(); for (int y=0; y < wbmpHead.ImageHeight; y++){ hFile->Read(iter.GetRow(),linewidth,1); iter.PrevRow(); } } catch (char *message) { strncpy(info.szLastError,message,255); return FALSE; } return true; } //////////////////////////////////////////////////////////////////////////////// bool CxImageWBMP::Encode(CxFile * hFile) { if (EncodeSafeCheck(hFile)) return false; //check format limits if ((head.biWidth>255)||(head.biHeight>255)||(head.biBitCount!=1)){ strcpy(info.szLastError,"Can't save this image as WBMP"); return false; } WBMPHEADER wbmpHead; wbmpHead.Type=0; wbmpHead.FixHeader=0; wbmpHead.ImageWidth=(BYTE)head.biWidth; wbmpHead.ImageHeight=(BYTE)head.biHeight; // Write the file header hFile->Write(&wbmpHead,sizeof(wbmpHead),1); // Write the pixels int linewidth=(wbmpHead.ImageWidth+7)/8; CImageIterator iter(this); iter.Upset(); for (int y=0; y < wbmpHead.ImageHeight; y++){ hFile->Write(iter.GetRow(),linewidth,1); iter.PrevRow(); } return true; } //////////////////////////////////////////////////////////////////////////////// #endif // CXIMAGE_SUPPORT_WBMP
[ "jmarshallnz@568bbfeb-2a22-0410-94d2-cc84cf5bfa90" ]
[ [ [ 1, 90 ] ] ]
9c2747b55b0cdfb67519a978db101422fedcef19
7f6fe18cf018aafec8fa737dfe363d5d5a283805
/ntk/interface/src/menu.cpp
31acb89d32aa4f09e9de515ca3922c3e2d3ad3e5
[]
no_license
snori/ntk
4db91d8a8fc836ca9a0dc2bc41b1ce767010d5ba
86d1a32c4ad831e791ca29f5e7f9e055334e8fe7
refs/heads/master
2020-05-18T05:28:49.149912
2009-08-04T16:47:12
2009-08-04T16:47:12
268,861
2
0
null
null
null
null
SHIFT_JIS
C++
false
false
9,554
cpp
/****************************************************************************** The NTK Library Copyright (C) 1998-2003 Noritaka Suzuki $Id: menu.cpp,v 1.6 2003/11/19 11:42:08 nsuzuki Exp $ ******************************************************************************/ #define NTK_BUILD #include "ntk/interface/menu.h" #include <assert.h> #include <vector> #include <ntk/windows/windows.h> #include <ntk/interface/menuitem.h> #include "menuwindow.h" namespace ntk { //######################################################## enum{ END_SELECTING = '_ESL', };//massages for menu const Menu::MenuLayout Menu::DEFAULT_LAYOUT = Menu::ITEMS_IN_COLUMN; //######################################################## // public methods Menu::Menu(const String& name, MenuLayout layout, const RGBColor& color) : View(Rect(0, 0, 10, 10), name, FOLLOW_LEFT | FOLLOW_TOP, DEFAULT_FLAGS, color) , m_menu_layout(layout) , m_selecting(false) , m_opened_submenu(NULL) , m_owner_menu_item(NULL) { } Menu::Menu(const Rect& frame, const String& name, uint mode, uint flags, MenuLayout layout, const RGBColor& color) : View(frame, name, mode, flags, color) , m_menu_layout(layout) , m_selecting(false) , m_opened_submenu(NULL) , m_owner_menu_item(NULL) { } Menu::~Menu() { while(! m_item_list.empty()) { delete m_item_list.back(); m_item_list.pop_back(); } } bool Menu::add_item(Menu* menu_, int index) { if(menu_ == NULL) return false; MenuItem* item = new MenuItem(menu_); menu_->m_owner_menu_item = item; return add_item(item); } bool Menu::add_item(MenuItem* item, int index) { if(item == NULL) return false; if(index < 0) m_item_list.push_back(item); else m_item_list.insert(m_item_list.begin() + index, item); item->m_menu = this; if(is_submenu()) { Looper* looper = NULL; Handler* handler = owner_menu_item()->target(&looper); item->set_target(handler, looper); } else item->set_target(NULL, window()); reposition(); return true; } void Menu::add_separator_item() { add_item(new SeparatorItem()); } void Menu::reposition() { switch(m_menu_layout) { case ITEMS_IN_COLUMN: reposition_by_column_(); break; case ITEMS_IN_ROW: reposition_by_row_(); break; case ITEMS_IN_MATRIX: reposition_by_matrix_(); break; } } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // public accessors and manipulators Menu::MenuLayout Menu::menu_layout() const { return m_menu_layout; } status_t Menu::set_target(Handler* target_, Looper* looper_) { status_t sts; bool error = false; for(ItemList::iterator it = m_item_list.begin(); it != m_item_list.end(); ++it) if(! (sts=(*it)->set_target(target_, looper_))) error = true; return error ? st::ERR : st::OK; } MenuItem* Menu::owner_menu_item() const { return m_owner_menu_item; } bool Menu::is_submenu() const { return m_owner_menu_item != NULL; } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // public message hnalder void Menu::attached_to_window() { if(dynamic_cast<MenuWindow*>(window())) { // サブメニューだったらデフォルトで選択状態。target の設定はしてはいけない begin_selecting_(); } else { // トップレベルのメニュー(コントロールとしてウィンドウに貼り付けられる) のときは // target の looper が正しく設定されるように再設定する。 for(ItemList::iterator it = m_item_list.begin(); it != m_item_list.end(); ++it) (*it)->set_target(NULL, window()); } for(ItemList::iterator it = m_item_list.begin(); it != m_item_list.end(); ++it) (*it)->attached_to_window(); } void Menu::detached_from_window() { for(ItemList::iterator it = m_item_list.begin(); it != m_item_list.end(); ++it) (*it)->detached_from_window(); } void Menu::mouse_down(const Point& point, uint buttons, bool dbl) { if(m_selecting == false) { begin_selecting_(); selecting_(point); // HANDLE track_thread = spawn_thread(track_mouse_, "MouseTracker", NORMAL_PRIORITY, this); // resume_thread(track_thread); } else select_menu_item_(point); } void Menu::mouse_up(const Point& point, uint buttons) { select_menu_item_(point); } void Menu::mouse_moved(const Point& point, uint buttons, uint transit, const Message* data) { if(m_selecting) selecting_(point); } void Menu::draw(PaintDC& dc) { for(ItemList::iterator it = m_item_list.begin(); it != m_item_list.end(); ++it) { dc.push_state(); (*it)->draw(dc); dc.pop_state(); } } void Menu::message_received(const Message& message) { switch(message.what) { case END_SELECTING: end_selecting_(); close_submenu_(); break; default: View::message_received(message); } } //******************************************************** // private methods void Menu::reposition_by_column_() { Rect rect = bounds(); coord width, height, max_width = 0, last_bottom = rect.top; for(ItemList::iterator it = m_item_list.begin(); it != m_item_list.end(); ++it) { MenuItem* item = *it; assert(item); item->get_content_size(&width, &height); if(width > max_width) max_width = width; item->m_frame.left = rect.left; item->m_frame.top = last_bottom; item->m_frame.right = rect.right; item->m_frame.bottom = last_bottom = item->m_frame.top + height; } if(flags() & RESIZE_TO_FIT) { resize_to(max_width, last_bottom - rect.top); rect = bounds(); for(ItemList::iterator it = m_item_list.begin(); it != m_item_list.end(); ++it) (*it)->m_frame.right = rect.right; } } void Menu::reposition_by_row_() { Rect rect = bounds(); coord width, height, max_height = 0, last_right = rect.top; for(ItemList::iterator it = m_item_list.begin(); it != m_item_list.end(); ++it) { MenuItem* item = *it; assert(item); item->get_content_size(&width, &height); if(height > max_height) max_height = height; item->m_frame.left = last_right; item->m_frame.top = rect.top; item->m_frame.right = last_right = item->m_frame.left + width; item->m_frame.bottom = rect.bottom; } if(flags() & RESIZE_TO_FIT) { resize_to(last_right - rect.left, max_height); rect = bounds(); for(ItemList::iterator it = m_item_list.begin(); it != m_item_list.end(); ++it) (*it)->m_frame.bottom = rect.bottom; } } void Menu::reposition_by_matrix_() { } void Menu::begin_selecting_() { m_selecting = true; for(ItemList::iterator it = m_item_list.begin(); it != m_item_list.end(); ++it) (*it)->m_selected = false; } void Menu::end_selecting_() { m_selecting = false; for(ItemList::iterator it = m_item_list.begin(); it != m_item_list.end(); ++it) { MenuItem* item = *it; if(item->m_selected) item->m_selected = false; if(item->submenu()) item->submenu()->end_selecting_(); } invalidate(); } void Menu::selecting_(const Point& point) { MenuItem *selected = NULL, *deselected = NULL; for(ItemList::iterator it = m_item_list.begin(); it != m_item_list.end(); ++it) { MenuItem* item = *it; if(item->m_frame.contains(point)) { if(item->m_selected == false) selected = item; } else if(item->m_selected) deselected = item; } if(deselected)// && selected) { deselected->m_selected = false; deselected->draw(dc()); close_submenu_(); end_capture(); } if(selected) { selected->m_selected = true; selected->draw(dc()); if(selected->submenu()) { m_opened_submenu = selected->submenu(); MenuWindow* window = new MenuWindow(m_opened_submenu); Point submenu_point; switch(menu_layout()) { case Menu::ITEMS_IN_COLUMN: submenu_point.x = frame().right; submenu_point.y = selected->frame().top; break; case Menu::ITEMS_IN_ROW: submenu_point.x = selected->frame().left; submenu_point.y = frame().bottom; break; } convert_to_screen(&submenu_point); window->go(submenu_point); } else// サブメニューを持たない NMenuItem はマウスが NMenu の範囲の外に出た時点でもセレクト状態を解除する。 { begin_capture(); } } } void Menu::close_submenu_() { if(m_opened_submenu) { m_opened_submenu->close_submenu_(); m_opened_submenu->window()->quit(); m_opened_submenu = NULL; } } void Menu::select_menu_item_(const Point& point) { MenuItem* item = NULL; for(ItemList::iterator it = m_item_list.begin(); it != m_item_list.end(); ++it) if((*it)->m_frame.contains(point) && (*it)->submenu() == NULL) { item = *it; // トップのメニュー階層を見つけ、全部閉じる。 Menu* menu = item->menu(); while(menu->owner_menu_item()) menu = menu->owner_menu_item()->menu(); menu->end_selecting_(); menu->close_submenu_(); end_capture(); item->invoke(); break; } } uint Menu::track_mouse_(void* data) { Menu* root_menu = reinterpret_cast<Menu*>(data); Point point; uint buttons; do { ntk::get_mouse(&point, &buttons); snooze(20); } while(buttons & LEFT_MOUSE_BUTTON); Messenger messenger(root_menu); messenger.send_message(Message(END_SELECTING)); return 0; } //######################################################## }// namespace ntk
[ [ [ 1, 461 ] ] ]
33399e5999fe97c1b9cc68ac306c185269587822
216398e30aca5f7874edfb8b72a13f95c22fbb5a
/CamMonitor/Server/Test/CSMS.cpp
79ca36d3e85290830acdc5b13fca59cd4f850627
[]
no_license
markisme/healthcare
791813ac6ac811870f3f28d1d31c3d5a07fb2fa2
7ab5a959deba02e7637da02a3f3c681548871520
refs/heads/master
2021-01-10T07:18:42.195610
2009-09-09T13:00:10
2009-09-09T13:00:10
35,987,767
0
0
null
null
null
null
UHC
C++
false
false
327
cpp
// CSMS.cpp : Microsoft Visual C++로 만든 ActiveX 컨트롤 래퍼 클래스의 정의입니다. #include "stdafx.h" #include "CSMS.h" ///////////////////////////////////////////////////////////////////////////// // CSMS IMPLEMENT_DYNCREATE(CSMS, CWnd) // CSMS 속성입니다. // CSMS 작업입니다.
[ "naidzzang@cc586c1e-b153-0410-8069-cfc9d6f95ec9" ]
[ [ [ 1, 14 ] ] ]
3838d4c4b04008550541967cb110a51fc4997787
e3a4fc080ec01d0327eab53c9ff764d31fe4218f
/source.development/TeX/texk/msvc/template-dll.rc
f23adfcb8493801cd5ccae25873b92e6331a0faa
[]
no_license
BackupTheBerlios/texlive
4181be54631e253fce8c15da4f32aeafdc74972f
00ac6a01d9188e3cdb01066f54dd9d3cc6b5bbfc
refs/heads/master
2020-05-17T22:59:10.042995
2004-01-08T17:04:26
2004-01-08T17:04:26
40,044,514
0
0
null
null
null
null
UTF-8
C++
false
false
1,178
rc
/* foo.rc: Foo DLL version number -*- C++ -*- Copyright (C) 1996-2002 Fabrice Popineau <[email protected]> This file is part of the Foo Library (foo.dll). The Foo Library 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, or (at your option) any later version. The Foo Library 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 the Foo Library; if not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #define VER_FILEVERSION 0,6,0,0 #define VER_FILEVERSION_STR "0.6" #define VER_INTERNALNAME_STR "foo" #define VER_ORIGINALFILENAME_STR "foo.dll" #define VER_FILEDESCRIPTION_STR "Foo Core DLL" #define VER_FILETYPE VFT_DLL #include "texlive.version"
[ "rahtz" ]
[ [ [ 1, 32 ] ] ]
b5213b50f7ceded6d9bb6651b5f343c982dda475
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/tools/inspect/cvs_iterator.hpp
ab1a78ffd444f5c8fc0aeb2de98efd3627a277bd
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
2,458
hpp
// cvs_iterator ------------------------------------------------------------// // Copyright Beman Dawes 2003. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // WARNING: This is just a quick hack. It doesn't conform to C++ Standard // Library iterator requirements. #ifndef BOOST_CVS_ITERATOR_HPP #define BOOST_CVS_ITERATOR_HPP #include <string> #include <assert.h> #include "boost/filesystem/path.hpp" #include "boost/filesystem/operations.hpp" #include "boost/filesystem/fstream.hpp" #include "boost/noncopyable.hpp" namespace hack { class cvs_iterator : boost::noncopyable { boost::filesystem::ifstream entries_file; boost::filesystem::path dir_path; boost::filesystem::path value_path; public: cvs_iterator(){} // end iterator ~cvs_iterator() { if ( !!entries_file ) entries_file.close(); } cvs_iterator( const boost::filesystem::path & dir_path ) : dir_path(dir_path) { boost::filesystem::path entries_file_path( dir_path / "CVS/Entries" ); entries_file.open( entries_file_path ); if ( !entries_file ) throw std::string( "could not open: " ) + entries_file_path.string(); ++*this; } const boost::filesystem::path & operator*() const { return value_path; } cvs_iterator & operator++() { assert( !!entries_file ); std::string contents; do { do { std::getline( entries_file, contents ); if ( entries_file.eof() ) { entries_file.close(); value_path = ""; return *this; } } while ( contents == "D" ); if ( contents[0] == 'D' ) contents.erase( 0, 1 ); value_path = dir_path / boost::filesystem::path( contents.substr( 1, contents.find( '/', 1 ) ), boost::filesystem::no_check ); // in case entries file is mistaken, do until value_path actually found } while ( !boost::filesystem::exists( value_path ) ); return *this; } bool operator==( const cvs_iterator & rhs ) { return value_path.string() == rhs.value_path.string(); } bool operator!=( const cvs_iterator & rhs ) { return value_path.string() != rhs.value_path.string(); } }; } #endif // include guard
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 81 ] ] ]
a53789a7f014a55d4f853ac35548efda59842360
9d1cb48ec6f6c1f0e342f0f8f819cbda74ceba6e
/src/OrgGroupDlg.h
1954d84fd84180c566cca5d328431534d3ba3c7a
[]
no_license
correosdelbosque/veryie
e7a5ad44c68dc0b81d4afcff3be76eb8f83320ff
6ea5a68d0a6eb6c3901b70c2dc806d1e2e2858f1
refs/heads/master
2021-01-10T13:17:59.755108
2010-06-16T04:23:26
2010-06-16T04:23:26
53,365,953
1
1
null
null
null
null
UTF-8
C++
false
false
2,432
h
#if !defined(AFX_ORGGROUPDLG_H__4D1B9EF3_D552_11D4_9B6A_0000E85300AE__INCLUDED_) #define AFX_ORGGROUPDLG_H__4D1B9EF3_D552_11D4_9B6A_0000E85300AE__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // OrgGroupDlg.h : header file // ///////////////////////////////////////////////////////////////////////////// // COrgGroupDlg dialog class COrgGroupDlg : public CDialog { // Construction public: BOOL m_bInit; CString m_strStartGroup; int m_nLastSelItemID; void SaveUrlList(int index); COrgGroupDlg(CWnd* pParent = NULL); // standard constructor virtual ~COrgGroupDlg() { if(m_pDragImage) delete m_pDragImage; }; // Dialog Data //{{AFX_DATA(COrgGroupDlg) enum { IDD = IDD_ORG_GROUP }; CButton m_CloseAllBeforeNewGroup; CButton m_GroupShowMember; CButton m_btnInsert; CListCtrl m_UrlList; CListCtrl m_GroupList; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(COrgGroupDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(COrgGroupDlg) virtual BOOL OnInitDialog(); afx_msg void OnSelChanging(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnNewGroup(); afx_msg void OnDelGroup(); afx_msg void OnDelete(); afx_msg void OnEndlabeleditGroupList(NMHDR* pNMHDR, LRESULT* pResult); virtual void OnOK(); afx_msg void OnInsert(); afx_msg void OnUpdate(); afx_msg void OnDeltaposSpin1(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposSpin2(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnClickGroupList(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnBegindragUrlList(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnDblclkUrlList(NMHDR* pNMHDR, LRESULT* pResult); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: void GetUnqBlankName(CString &newblnk); void FillUrlList(int index); CImageList* m_pDragImage; BOOL m_bDragging; int m_nDragIndex, m_nDropIndex; CWnd* m_pDropWnd; }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_ORGGROUPDLG_H__4D1B9EF3_D552_11D4_9B6A_0000E85300AE__INCLUDED_)
[ "songbohr@af2e6244-03f2-11de-b556-9305e745af9e" ]
[ [ [ 1, 83 ] ] ]
f939227ee35cfc5c399ff478a9462e974f06c1de
e46cae4635b79c4016ad85562018214a8305de97
/WinArena/GIFFile.cpp
22625a2451a3d8ef1ec9702f46bbc4f8ed02b417
[]
no_license
basecq/opentesarenapp
febea5fddab920d5987f8067420d0b410aa95656
4b6d097d7c40352c62f9f95068e89df44e323832
refs/heads/master
2021-01-18T01:10:14.561315
2009-10-12T14:32:01
2009-10-12T14:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,845
cpp
///////////////////////////////////////////////////////////////////////////// // // $Header: /WinArena/GIFFile.cpp 3 12/11/05 11:52a Lee $ // // File: GIFFile.cpp // // // Ancient, rickety, experimental version of GIF encode/decode. It works. // That's about all I can say for it. But it is independent of my other // software libraries, so I can include it without having to weld in tens // of thousands of lines of code that have nothing to do with it. // ///////////////////////////////////////////////////////////////////////////// #include <windows.h> #include "GIFFile.h" #pragma pack(push, normalPacking) #pragma pack(1) const BYTE GIFGlobalMapPresent = 0x80; const BYTE GIFGlobalMapSorted = 0x08; const BYTE GIFLocalMapPresent = 0x80; const BYTE GIFInterlaced = 0x40; const BYTE GIFColorMapSorted = 0x20; const BYTE GIFTransparentImage = 0x01; typedef struct tagGIFScreenDescriptor { WORD Width; WORD Height; BYTE PackedFields; BYTE BackgroundIndex; BYTE AspectRatio; } GIFScreenDescriptor; typedef struct tagGIFImageDescriptor { WORD LeftPosition; WORD TopPosition; WORD Width; WORD Height; BYTE PackedFields; } GIFImageDescriptor; typedef struct tagGIFTextExtension { BYTE BlockSize; WORD LeftPosition; WORD TopPosition; WORD Width; WORD Height; BYTE CellWidth; BYTE CellHeight; BYTE ForegroundIndex; BYTE BackgroundIndex; } GIFTextExtension; typedef struct tagGIFControlExtension { BYTE BlockSize; BYTE PackedFields; WORD DelayTime; BYTE TransparentColorIndex; BYTE BlockTerminator; } GIFControlExtension; typedef struct tagGIFApplicationExtension { BYTE BlockSize; BYTE Identifier[8]; BYTE Authentication[3]; } GIFApplicationExtension; #pragma pack(pop, normalPacking) ////////////////////////////////////////////////////////////////////////////// class CGIFEncodeToMemory : public CLZWOutput { public: CGIFEncodeToMemory(void); ~CGIFEncodeToMemory(void); void SetMemory(BYTE *buffer, DWORD size); DWORD DataSize(void); LZWError Initialize(void); LZWError WriteBuffer(const BYTE *buffer, const DWORD byteCount); LZWError CleanUp(void); private: BYTE* m_pBuffer; DWORD m_Offset; DWORD m_Size; }; CGIFEncodeToMemory::CGIFEncodeToMemory(void) : m_pBuffer(0), m_Offset(0), m_Size(0) { } CGIFEncodeToMemory::~CGIFEncodeToMemory(void) { } void CGIFEncodeToMemory::SetMemory(BYTE *buffer, DWORD size) { m_pBuffer = buffer; m_Size = size; } DWORD CGIFEncodeToMemory::DataSize(void) { return m_Offset; } LZWError CGIFEncodeToMemory::Initialize(void) { m_Offset = 0; return LZW_Success; } LZWError CGIFEncodeToMemory::WriteBuffer(const BYTE *buffer, const DWORD byteCount) { BYTE count; DWORD remaining = byteCount; BYTE *buf = (BYTE*)buffer; while (remaining) { if (remaining > 255) count = 255; else count = BYTE(remaining); if ((DWORD(count) + 1 + m_Offset) > m_Size) return LZW_OutputError; m_pBuffer[m_Offset++] = count; memcpy(m_pBuffer + m_Offset, buf, DWORD(count)); m_Offset += count; buf += DWORD(count); remaining -= DWORD(count); } return LZW_Success; } LZWError CGIFEncodeToMemory::CleanUp(void) { m_pBuffer[m_Offset++] = 0; return LZW_Success; } ////////////////////////////////////////////////////////////////////////////// class CGIFDecodeFromMemory : public CLZWOutput { public: CGIFDecodeFromMemory(void); ~CGIFDecodeFromMemory(void); void SetMemory(BYTE *buffer, DWORD size, DWORD pitch); void SetBounds(long left, long top, long width, long height); void SetInterlacing(bool enable); LZWError Initialize(void); LZWError WriteBuffer(const BYTE *buffer, const DWORD byteCount); LZWError CleanUp(void); private: long m_Left; long m_Top; long m_Right; long m_Bottom; long m_Height; long m_LineNum; long m_PixelNum; BYTE* m_pScanLine; bool m_IsInterlaced; long m_InterlaceFirst; long m_InterlaceIncrement; BYTE* m_pBuffer; DWORD m_Size; DWORD m_Pitch; }; CGIFDecodeFromMemory::CGIFDecodeFromMemory(void) : m_pBuffer(0), m_IsInterlaced(false), m_InterlaceFirst(0) { } CGIFDecodeFromMemory::~CGIFDecodeFromMemory(void) { } void CGIFDecodeFromMemory::SetMemory(BYTE *buffer, DWORD size, DWORD pitch) { m_pBuffer = buffer; m_Size = size; m_Pitch = pitch; } void CGIFDecodeFromMemory::SetBounds(long left, long top, long width, long height) { m_Left = left; m_Top = top; m_Right = left + width; m_Bottom = top + height; m_Height = height; } void CGIFDecodeFromMemory::SetInterlacing(bool enable) { m_IsInterlaced = enable; if (m_IsInterlaced) { m_InterlaceFirst = 8; m_InterlaceIncrement = 8; } } LZWError CGIFDecodeFromMemory::Initialize(void) { m_LineNum = 0; m_PixelNum = m_Left; m_pScanLine = m_pBuffer + (m_LineNum + m_Top) * m_Pitch; return LZW_Success; } LZWError CGIFDecodeFromMemory::WriteBuffer(const BYTE *buffer, const DWORD byteCount) { DWORD index; for (index = 0; index < byteCount; ++index) { if (m_LineNum < m_Height) m_pScanLine[m_PixelNum++] = *(buffer++); if (m_PixelNum >= m_Right) { if (m_IsInterlaced) { m_LineNum += m_InterlaceIncrement; if (m_LineNum >= m_Height) { if (m_InterlaceFirst == 8) m_InterlaceFirst = 4; else if (m_InterlaceFirst == 4) { m_InterlaceFirst = 2; m_InterlaceIncrement = 4; } else if (m_InterlaceFirst == 2) { m_InterlaceFirst = 1; m_InterlaceIncrement = 2; } m_LineNum = m_InterlaceFirst; } } else ++m_LineNum; m_PixelNum = m_Left; m_pScanLine = m_pBuffer + (m_LineNum + m_Top) * m_Pitch; } } return LZW_Success; } LZWError CGIFDecodeFromMemory::CleanUp(void) { return LZW_Success; } ////////////////////////////////////////////////////////////////////////////// CGIFFile::CGIFFile() : m_IsInput(false), m_pFileBuffer(0), m_FileOffset(0), m_FileSize(0), m_pCommentBuffer(0), m_CommentBufferSize(0), m_LzwCodeSize(0), m_DelayTime(0), m_IsInterlaced(0) { } CGIFFile::~CGIFFile() { if (m_pCommentBuffer) delete [] m_pCommentBuffer; } GIFError CGIFFile::Open(char *filename, bool isInput) { Close(); if ((filename == 0) || (filename[0] == '\0')) return GIF_NoFileName; long createSize = -1; if (!isInput) createSize = 1024 * 1024; if (!m_File.Open(filename, !isInput, createSize)) return GIF_CannotOpenFile; m_IsInput = isInput; m_pFileBuffer = m_File.Address(); m_FileOffset = 0; m_FileSize = m_File.Size(); m_FrameCount = 0; if (isInput) return readHeader(); return GIF_Success; } GIFError CGIFFile::Close(void) { if (m_File.IsOpen()) { if (m_IsInput) m_File.Close(-1); else m_File.Close(m_FileOffset); } return GIF_Success; } GIFError CGIFFile::GetInfo(DWORD &width, DWORD &height) { if (!m_File.IsOpen()) return GIF_FileNotOpen; if (!m_IsInput) return GIF_ReadFromOutputFile; width = m_ImageWidth; height = m_ImageHeight; return GIF_Success; } GIFError CGIFFile::ReadImage(GIFFrameBuffer &frame) { GIFImageDescriptor imageDesc; GIFError status; BYTE blockSize; BYTE blockData[256]; BYTE extension; bool done = false; BYTE label; while (!done) { status = readFromFile(&label, 1); if (status != GIF_Success) return status; switch (label) { case 0x2C: // image descriptor status = readFromFile(&imageDesc, sizeof(imageDesc)); if (status != GIF_Success) return status; if (imageDesc.PackedFields & GIFLocalMapPresent) { DWORD bitShift = (imageDesc.PackedFields & 0x07) + 1; frame.ColorMapEntryCount = 1 << bitShift; status = readFromFile(frame.ColorMap, 3 * frame.ColorMapEntryCount); if (status != GIF_Success) return status; } else { frame.ColorMapEntryCount = m_GlobalColorMapEntryCount; memcpy(frame.ColorMap, m_GlobalColorMap, m_GlobalColorMapEntryCount * 3); } // If the image is interlaced, then set these values // in preparation of calculating the proper offsets // for each line as it is read in. if (imageDesc.PackedFields & GIFInterlaced) m_IsInterlaced = true; else m_IsInterlaced = false; // Return the result of decoding, which should be GIF_Success, // to indicate that an image was successfully read. return decodeStream(frame, &imageDesc); case 0x21: // extension block status = readFromFile(&extension, 1); if (status != GIF_Success) return status; switch (extension) { case 0x01: // plain text extension GIFTextExtension textExtension; status = readFromFile(&textExtension, sizeof(textExtension)); if (status != GIF_Success) return status; do { status = readBlock(blockData, blockSize); if (status != GIF_Success) return status; } while (blockSize); break; case 0xF9: // graphic control extension GIFControlExtension controlExtension; status = readFromFile(&controlExtension, sizeof(controlExtension)); if (status != GIF_Success) return status; break; case 0xFE: // comment extension do { status = readFromFile(&blockSize, 1); if (status != GIF_Success) return status; if (blockSize) { status = readFromFile(blockData, blockSize); if (status != GIF_Success) return status; blockData[blockSize] = '\0'; } } while (blockSize); break; case 0xFF: // application extension GIFApplicationExtension appExt; status = readFromFile(&appExt, sizeof(appExt)); if (status != GIF_Success) return status; do { status = readFromFile(&blockSize, 1); if (status != GIF_Success) return status; if (blockSize) { status = readFromFile(blockData, blockSize); if (status != GIF_Success) return status; } } while (blockSize); break; default: return GIF_UnknownExtension; } break; // In the case of the file trailer, we know that we have reached the // end of the GIF file. Return false to indicate that we are not able // to read any more images from the file. case 0x3B: // trailer return GIF_NoImage; // If label is not recognized, then the file is either corrupt // or has some application-specific data present. In either // case, abort any further reading. default: return GIF_UnknownLabel; } } return GIF_NoImage; } GIFError CGIFFile::InitOutput(long width, long height) { if (!m_File.IsOpen()) return GIF_FileNotOpen; if (m_IsInput) return GIF_WriteToInputFile; m_ImageWidth = width; m_ImageHeight = height; GIFError status; status = writeToFile("GIF87a", 6); if (status != GIF_Success) return status; GIFScreenDescriptor screen; screen.Width = WORD(m_ImageWidth); screen.Height = WORD(m_ImageHeight); screen.PackedFields = 0; if (m_GlobalColorMapEntryCount > 0) { DWORD highest = highestBit(m_GlobalColorMapEntryCount); if (highest < 3) highest = 1; else highest -= 2; screen.PackedFields |= (BYTE)GIFGlobalMapPresent; screen.PackedFields |= highest; // color table size screen.PackedFields |= highest << 4; // color resolution } screen.BackgroundIndex = 0; screen.AspectRatio = 0; status = writeToFile(&screen, sizeof(screen)); if (status != GIF_Success) return status; if (m_GlobalColorMapEntryCount > 0) { status = writeToFile(m_GlobalColorMap, m_GlobalColorMapEntryCount * 3); if (status != GIF_Success) return status; } if (m_pCommentBuffer != 0) { BYTE extension = 0x21; status = writeToFile(&extension, sizeof(extension)); if (status != GIF_Success) return status; BYTE commentExtension = 0xFE; status = writeToFile(&commentExtension, sizeof(commentExtension)); if (status != GIF_Success) return status; BYTE comLen; int commentLength = m_CommentBufferSize; int commentOffset = 0; do { if (commentLength > 255) comLen = BYTE(255); else comLen = BYTE(commentLength); status = writeToFile(&comLen, sizeof(comLen)); if (status != GIF_Success) return status; status = writeToFile(&(m_pCommentBuffer[commentOffset]), comLen); if (status != GIF_Success) return status; commentLength -= comLen; commentOffset += comLen; } while (commentLength > 0); comLen = 0; status = writeToFile(&comLen, sizeof(comLen)); if (status != GIF_Success) return status; } return GIF_Success; } GIFError CGIFFile::SetCodeSize(long codeSize) { if (codeSize > 8) return GIF_InvalidCodeSize; else if (codeSize < 2) codeSize = 2; m_LzwCodeSize = BYTE(codeSize); return GIF_Success; } GIFError CGIFFile::SetComment(char *pComment) { if (m_pCommentBuffer) { delete [] m_pCommentBuffer; m_pCommentBuffer = 0; } if ((pComment == 0) || (pComment[0] == '\0')) return GIF_Success; m_CommentBufferSize = long(strlen(pComment) + 1); m_pCommentBuffer = new char[m_CommentBufferSize]; memcpy(m_pCommentBuffer, pComment, m_CommentBufferSize); return GIF_Success; } GIFError CGIFFile::SetGlobalColorMap(long entryCount, BYTE *pColorTable) { if (pColorTable == 0) return GIF_InvalidPointer; if (entryCount <= 0) entryCount = 0; else if (entryCount < 4) entryCount = 4; else if (entryCount > 256) entryCount = 256; m_GlobalColorMapEntryCount = entryCount; if (m_GlobalColorMapEntryCount > 0) memcpy(m_GlobalColorMap, pColorTable, (m_GlobalColorMapEntryCount * 3)); return GIF_Success; } GIFError CGIFFile::GetGlobalColorMap(long &entryCount, BYTE *pColorTable) { if (pColorTable == 0) return GIF_InvalidPointer; entryCount = m_GlobalColorMapEntryCount; memcpy(pColorTable, m_GlobalColorMap, (m_GlobalColorMapEntryCount * 3)); return GIF_Success; } GIFError CGIFFile::SetDelayTime(DWORD centiseconds) { m_DelayTime = WORD(centiseconds); return GIF_Success; } GIFError CGIFFile::StartAnimation(void) { writeControlExtension(); return GIF_Success; } GIFError CGIFFile::WriteImage(GIFFrameBuffer &frame, long top, long left) { if (frame.pBuffer == 0) return GIF_InvalidPointer; if (m_IsInput) return GIF_WriteToInputFile; if (top < 0) top = 0; if (left < 0) left = 0; WORD width = WORD(frame.Width); WORD height = WORD(frame.Height); if (width > (m_ImageWidth - left)) width = WORD(m_ImageWidth - left); if (height > (m_ImageHeight - top)) height = WORD(m_ImageHeight - top); if ((width < 1) || (height < 1)) return GIF_InvalidImageSize; // When there are multiple frames, there needs to be a control extension // between each frame to indicate the duration of the delay between // displaying the sequential frames. if (m_FrameCount > 0) writeControlExtension(); GIFError status; BYTE imageDescriptor = 0x2C; status = writeToFile(&imageDescriptor, sizeof(imageDescriptor)); if (status != GIF_Success) return status; GIFImageDescriptor image; image.LeftPosition = 0; image.TopPosition = 0; image.Width = width; image.Height = height; image.PackedFields = 0; if (frame.ColorMapEntryCount > 0) { DWORD highest = highestBit(frame.ColorMapEntryCount); if (highest < 3) highest = 1; else highest -= 2; image.PackedFields |= GIFLocalMapPresent; image.PackedFields |= highest; // color table size } status = writeToFile(&image, sizeof(image)); if (status != GIF_Success) return status; if (frame.ColorMapEntryCount > 0) { DWORD entryCount = frame.ColorMapEntryCount; if (entryCount > 256) entryCount = 256; status = writeToFile(frame.ColorMap, entryCount * 3); if (status != GIF_Success) return status; } status = encodeStream(frame, top, left, width, height); if (status != GIF_Success) return status; ++m_FrameCount; return GIF_Success; } GIFError CGIFFile::FinishOutput(void) { if (!m_File.IsOpen()) return GIF_FileNotOpen; if (m_IsInput) return GIF_WriteToInputFile; if (m_FrameCount > 1) writeControlExtension(); BYTE trailor = 0x3B; GIFError status = writeToFile(&trailor, sizeof(trailor)); if (status != GIF_Success) return status; // Multi-frame GIFs are not supported by the 87a version, so they need // to be tagged as 89a. if (m_FrameCount > 1) memcpy(m_pFileBuffer, "GIF89a", 6); m_File.Close(m_FileOffset); return status; } GIFError CGIFFile::readFromFile(void *buffer, long size) { if (!m_File.IsOpen()) return GIF_FileNotOpen; if (!m_IsInput) return GIF_ReadFromOutputFile; if (!buffer || (size < 0)) return GIF_InvalidPointer; if ((size + m_FileOffset) > m_FileSize) return GIF_ReadPastEndOfFile; memcpy(buffer, m_pFileBuffer + m_FileOffset, size); m_FileOffset += size; return GIF_Success; } GIFError CGIFFile::writeToFile(void *buffer, long size) { if (!m_File.IsOpen()) return GIF_FileNotOpen; if (m_IsInput) return GIF_WriteToInputFile; if (!buffer || (size < 0)) return GIF_InvalidPointer; if ((size + m_FileOffset) > m_FileSize) return GIF_WritePastEndOfFile; memcpy(m_pFileBuffer + m_FileOffset, buffer, size); m_FileOffset += size; return GIF_Success; } GIFError CGIFFile::readHeader(void) { GIFError status; /////////////////////////////// // Read the GIF signature. // /////////////////////////////// // Read in the GIF file signature that identifies the file as a GIF // file. This will consist of one of the two 6-byte strings "GIF87a" // or "GIF89a", so an extra entry is required to NULL-terminate the // data to make it a proper string. char signature[7]; status = readFromFile(signature, 6); if (status != GIF_Success) return status; signature[6] = '\0'; strlwr(signature); // If neither of the valid signatures is present, then this is // not a recognized version of a GIF file. if (strcmp(signature, "gif87a") && strcmp(signature, "gif89a")) return GIF_FileIsNotGIF; /////////////////////////////////// // Read the screen descriptor. // /////////////////////////////////// // Read the image property data from the file header. GIFScreenDescriptor screen; status = readFromFile(&screen, sizeof(screen)); if (status != GIF_Success) return status; // Calculate the color resolution of the global color table. // This tells the number of 3-byte entries in that table. int colorResolution = ((screen.PackedFields >> 4) & 0x07) + 1; if (colorResolution < 2) colorResolution = 2; // Check to see if a global color table is present in the file. // If so, then allocate a color table and read the data from // the file. This global table will be used by all images that // do not have a local color table defined. if (screen.PackedFields & GIFGlobalMapPresent) { DWORD bitShift = (screen.PackedFields & 0x07) + 1; m_GlobalColorMapEntryCount = 1 << bitShift; status = readFromFile(m_GlobalColorMap, 3 * m_GlobalColorMapEntryCount); if (status != GIF_Success) return status; } // Record the full dimensions of the images in the file. m_ImageWidth = screen.Width; m_ImageHeight = screen.Height; return GIF_Success; } GIFError CGIFFile::decodeStream(GIFFrameBuffer &frame, void *desc) { BYTE dataBlock[256]; BYTE dataLength; GIFError status; GIFImageDescriptor *imageDesc = (GIFImageDescriptor*)desc; // get the byte which indicates how many bits to start readFromFile(&m_LzwCodeSize, 1); CGIFDecodeFromMemory decoder; decoder.SetInterlacing(m_IsInterlaced); decoder.SetMemory(frame.pBuffer, frame.BufferSize, frame.Pitch); decoder.SetBounds(imageDesc->LeftPosition, imageDesc->TopPosition, imageDesc->Width, imageDesc->Height); m_Codec.SetOutput(&decoder); m_Codec.StartDecoder(m_LzwCodeSize); for (;;) { status = readBlock(dataBlock, dataLength); if (status != GIF_Success) return status; if (dataLength == 0) break; m_Codec.DecodeStream(dataBlock, dataLength); } m_Codec.StopDecoder(); while (dataLength) { status = readBlock(dataBlock, dataLength); if (status != GIF_Success) return status; } return GIF_Success; } GIFError CGIFFile::readBlock(BYTE *buffer, BYTE &blockSize) { GIFError status = readFromFile(&blockSize, 1); if (status != GIF_Success) return status; if (blockSize) status = readFromFile(buffer, blockSize); return status; } GIFError CGIFFile::encodeStream(GIFFrameBuffer &frame, long top, long left, long width, long height) { GIFError status; // store the bytes indicating how many bits to start status = writeToFile(&m_LzwCodeSize, sizeof(m_LzwCodeSize)); if (status != GIF_Success) return status; if (m_FileOffset >= m_FileSize) return GIF_FileTooSmall; CGIFEncodeToMemory encoder; encoder.SetMemory(m_pFileBuffer + m_FileOffset, (m_FileSize - m_FileOffset)); if (m_Codec.SetOutput(&encoder) != LZW_Success) return GIF_CodecError; if (m_Codec.StartEncoder(m_LzwCodeSize) != LZW_Success) return GIF_CodecError; for (long y = top; y < top+height; ++y) { BYTE *pPixel = frame.pBuffer + (frame.Pitch * y) + left; if (m_Codec.EncodeStream(pPixel, width) != LZW_Success) return GIF_CodecError; } if (m_Codec.StopEncoder() != LZW_Success) return GIF_CodecError; m_FileOffset += encoder.DataSize(); return GIF_Success; } GIFError CGIFFile::writeControlExtension(void) { GIFError status; BYTE extension = 0x21; status = writeToFile(&extension, sizeof(extension)); if (status != GIF_Success) return status; BYTE label = 0xF9; status = writeToFile(&label, sizeof(label)); if (status != GIF_Success) return status; GIFControlExtension graphic; graphic.BlockSize = 4; graphic.PackedFields = 0; graphic.DelayTime = m_DelayTime; graphic.TransparentColorIndex = 0; graphic.BlockTerminator = 0; return writeToFile(&graphic, sizeof(graphic)); } DWORD CGIFFile::highestBit(DWORD value) { DWORD highest = 0; while (value != 0) { value >>= 1; ++highest; } return highest; }
[ [ [ 1, 992 ] ] ]
a053a21fcca1c9bed1713cadccf0e211661a2854
037faae47a5b22d3e283555e6b5ac2a0197faf18
/plugins/gs/gsdx9/GSState.h
4699760b5719a195e14747fc6fbfaad0b03b2ea6
[]
no_license
isabella232/pcsx2-sourceforge
6e5aac8d0b476601bfc8fa83ded66c1564b8c588
dbb2c3a010081b105a8cba0c588f1e8f4e4505c6
refs/heads/master
2023-03-18T22:23:15.102593
2008-11-17T20:10:17
2008-11-17T20:10:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,531
h
/* * Copyright (C) 2003-2005 Gabest * http://www.gabest.org * * 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, 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 GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #pragma once #include "GS.h" #include "GSWnd.h" #include "GSLocalMemory.h" #include "GSTextureCache.h" #include "GSSoftVertex.h" #include "GSVertexList.h" #include "GSCapture.h" #include "GSPerfMon.h" // //#define ENABLE_CAPTURE_STATE // /* //#define DEBUG_SAVETEXTURES #define DEBUG_LOG #define DEBUG_LOG2 #define DEBUG_LOGVERTICES #define DEBUG_RENDERTARGETS */ #define D3DCOLORWRITEENABLE_RGB (D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE) #define D3DCOLORWRITEENABLE_RGBA (D3DCOLORWRITEENABLE_RGB|D3DCOLORWRITEENABLE_ALPHA) struct GSDrawingContext { struct GSDrawingContext() {memset(this, 0, sizeof(*this));} GIFRegXYOFFSET XYOFFSET; GIFRegTEX0 TEX0; GIFRegTEX1 TEX1; GIFRegTEX2 TEX2; GIFRegCLAMP CLAMP; GIFRegMIPTBP1 MIPTBP1; GIFRegMIPTBP2 MIPTBP2; GIFRegSCISSOR SCISSOR; GIFRegALPHA ALPHA; GIFRegTEST TEST; GIFRegFBA FBA; GIFRegFRAME FRAME; GIFRegZBUF ZBUF; GSLocalMemory::psmtbl_t* ftbl; GSLocalMemory::psmtbl_t* ztbl; GSLocalMemory::psmtbl_t* ttbl; }; struct GSDrawingEnvironment { struct GSDrawingEnvironment() {memset(this, 0, sizeof(*this));} GIFRegPRIM PRIM; GIFRegPRMODE PRMODE; GIFRegPRMODECONT PRMODECONT; GIFRegTEXCLUT TEXCLUT; GIFRegSCANMSK SCANMSK; GIFRegTEXA TEXA; GIFRegFOGCOL FOGCOL; GIFRegDIMX DIMX; GIFRegDTHE DTHE; GIFRegCOLCLAMP COLCLAMP; GIFRegPABE PABE; GSDrawingContext CTXT[2]; GIFRegBITBLTBUF BITBLTBUF; GIFRegTRXDIR TRXDIR; GIFRegTRXPOS TRXPOS; GIFRegTRXREG TRXREG, TRXREG2; }; struct GSRegSet { GSRegPMODE* pPMODE; GSRegSMODE1* pSMODE1; GSRegSMODE2* pSMODE2; GSRegDISPFB* pDISPFB[2]; GSRegDISPLAY* pDISPLAY[2]; GSRegEXTBUF* pEXTBUF; GSRegEXTDATA* pEXTDATA; GSRegEXTWRITE* pEXTWRITE; GSRegBGCOLOR* pBGCOLOR; GSRegCSR* pCSR; GSRegIMR* pIMR; GSRegBUSDIR* pBUSDIR; GSRegSIGLBLID* pSIGLBLID; struct GSRegSet() { memset(this, 0, sizeof(*this)); extern BYTE* g_pBasePS2Mem; ASSERT(g_pBasePS2Mem); pPMODE = (GSRegPMODE*)(g_pBasePS2Mem + GS_PMODE); pSMODE1 = (GSRegSMODE1*)(g_pBasePS2Mem + GS_SMODE1); pSMODE2 = (GSRegSMODE2*)(g_pBasePS2Mem + GS_SMODE2); // pSRFSH = (GSRegPMODE*)(g_pBasePS2Mem + GS_SRFSH); // pSYNCH1 = (GSRegPMODE*)(g_pBasePS2Mem + GS_SYNCH1); // pSYNCH2 = (GSRegPMODE*)(g_pBasePS2Mem + GS_SYNCH2); // pSYNCV = (GSRegPMODE*)(g_pBasePS2Mem + GS_SYNCV); pDISPFB[0] = (GSRegDISPFB*)(g_pBasePS2Mem + GS_DISPFB1); pDISPFB[1] = (GSRegDISPFB*)(g_pBasePS2Mem + GS_DISPFB2); pDISPLAY[0] = (GSRegDISPLAY*)(g_pBasePS2Mem + GS_DISPLAY1); pDISPLAY[1] = (GSRegDISPLAY*)(g_pBasePS2Mem + GS_DISPLAY2); pEXTBUF = (GSRegEXTBUF*)(g_pBasePS2Mem + GS_EXTBUF); pEXTDATA = (GSRegEXTDATA*)(g_pBasePS2Mem + GS_EXTDATA); pEXTWRITE = (GSRegEXTWRITE*)(g_pBasePS2Mem + GS_EXTWRITE); pBGCOLOR = (GSRegBGCOLOR*)(g_pBasePS2Mem + GS_BGCOLOR); pCSR = (GSRegCSR*)(g_pBasePS2Mem + GS_CSR); pIMR = (GSRegIMR*)(g_pBasePS2Mem + GS_IMR); pBUSDIR = (GSRegBUSDIR*)(g_pBasePS2Mem + GS_BUSDIR); pSIGLBLID = (GSRegSIGLBLID*)(g_pBasePS2Mem + GS_SIGLBLID); } CSize GetDispSize(int en) { ASSERT(en >= 0 && en < 2); CSize size; size.cx = (pDISPLAY[en]->DW + 1) / (pDISPLAY[en]->MAGH + 1); size.cy = (pDISPLAY[en]->DH + 1) / (pDISPLAY[en]->MAGV + 1); //if(pSMODE2->INT && pSMODE2->FFMD && size.cy > 1) size.cy >>= 1; return size; } CRect GetDispRect(int en) { ASSERT(en >= 0 && en < 2); return CRect(CPoint(pDISPFB[en]->DBX, pDISPFB[en]->DBY), GetDispSize(en)); } bool IsEnabled(int en) { ASSERT(en >= 0 && en < 2); if(en == 0 && pPMODE->EN1) {return(pDISPLAY[0]->DW || pDISPLAY[0]->DH);} else if(en == 1 && pPMODE->EN2) {return(pDISPLAY[1]->DW || pDISPLAY[1]->DH);} return(false); } int GetFPS() { return ((pSMODE1->CMOD&1) ? 50 : 60) / (pSMODE2->INT ? 1 : 2); } }; struct GSVertex { GIFRegRGBAQ RGBAQ; GIFRegST ST; GIFRegUV UV; GIFRegXYZ XYZ; GIFRegFOG FOG; }; struct GIFPath { GIFTag m_tag; int m_nreg; }; class GSState { friend class GSTextureCache; protected: static const int m_version = 4; GIFPath m_path[3]; GSLocalMemory m_lm; GSDrawingEnvironment m_de; GSDrawingContext* m_ctxt; GSRegSet m_rs; GSVertex m_v; float m_q; GSPerfMon m_perfmon; GSCapture m_capture; private: static const int m_nTrMaxBytes = 1024*1024*4; int m_nTrBytes; BYTE* m_pTrBuff; int m_x, m_y; void WriteStep(); void ReadStep(); void WriteTransfer(BYTE* pMem, int len); void FlushWriteTransfer(); void ReadTransfer(BYTE* pMem, int len); void MoveTransfer(); protected: HWND m_hWnd; int m_width, m_height; CComPtr<IDirect3D9> m_pD3D; CComPtr<IDirect3DDevice9> m_pD3DDev; CComPtr<ID3DXFont> m_pD3DXFont; CComPtr<IDirect3DSurface9> m_pOrgRenderTarget; CComPtr<IDirect3DTexture9> m_pTmpRenderTarget; CComPtr<IDirect3DPixelShader9> m_pPixelShaders[20]; CComPtr<IDirect3DPixelShader9> m_pHLSLTFX[38], m_pHLSLMerge[3], m_pHLSLRedBlue; enum {PS11_EN11 = 12, PS11_EN01 = 13, PS11_EN10 = 14, PS11_EN00 = 15}; enum {PS14_EN11 = 16, PS14_EN01 = 17, PS14_EN10 = 18, PS14_EN00 = 19}; enum {PS_M16 = 0, PS_M24 = 1, PS_M32 = 2}; D3DPRESENT_PARAMETERS m_d3dpp; DDCAPS m_ddcaps; D3DCAPS9 m_caps; D3DSURFACE_DESC m_bd; D3DFORMAT m_fmtDepthStencil; bool m_fEnablePalettizedTextures; bool m_fNloopHack; bool m_fField; D3DTEXTUREFILTERTYPE m_texfilter; virtual void VertexKick(bool fSkip) = 0; virtual int DrawingKick(bool fSkip) = 0; virtual void NewPrim() = 0; virtual void FlushPrim() = 0; virtual void Flip() = 0; virtual void EndFrame() = 0; virtual void InvalidateTexture(const GIFRegBITBLTBUF& BITBLTBUF, CRect r) {} virtual void InvalidateLocalMem(DWORD TBP0, DWORD BW, DWORD PSM, CRect r) {} virtual void MinMaxUV(int w, int h, CRect& r) {r.SetRect(0, 0, w, h);} struct FlipInfo {CComPtr<IDirect3DTexture9> pRT; D3DSURFACE_DESC rd; scale_t scale;}; void FinishFlip(FlipInfo rt[2]); void FlushPrimInternal(); // // FIXME: savestate GIFRegPRIM* m_pPRIM; UINT32 m_PRIM; void (*m_fpGSirq)(); typedef void (__fastcall GSState::*GIFPackedRegHandler)(GIFPackedReg* r); GIFPackedRegHandler m_fpGIFPackedRegHandlers[16]; void __fastcall GIFPackedRegHandlerNull(GIFPackedReg* r); void __fastcall GIFPackedRegHandlerPRIM(GIFPackedReg* r); void __fastcall GIFPackedRegHandlerRGBA(GIFPackedReg* r); void __fastcall GIFPackedRegHandlerSTQ(GIFPackedReg* r); void __fastcall GIFPackedRegHandlerUV(GIFPackedReg* r); void __fastcall GIFPackedRegHandlerXYZF2(GIFPackedReg* r); void __fastcall GIFPackedRegHandlerXYZ2(GIFPackedReg* r); void __fastcall GIFPackedRegHandlerTEX0_1(GIFPackedReg* r); void __fastcall GIFPackedRegHandlerTEX0_2(GIFPackedReg* r); void __fastcall GIFPackedRegHandlerCLAMP_1(GIFPackedReg* r); void __fastcall GIFPackedRegHandlerCLAMP_2(GIFPackedReg* r); void __fastcall GIFPackedRegHandlerFOG(GIFPackedReg* r); void __fastcall GIFPackedRegHandlerXYZF3(GIFPackedReg* r); void __fastcall GIFPackedRegHandlerXYZ3(GIFPackedReg* r); void __fastcall GIFPackedRegHandlerA_D(GIFPackedReg* r); void __fastcall GIFPackedRegHandlerNOP(GIFPackedReg* r); typedef void (__fastcall GSState::*GIFRegHandler)(GIFReg* r); GIFRegHandler m_fpGIFRegHandlers[256]; void __fastcall GIFRegHandlerNull(GIFReg* r); void __fastcall GIFRegHandlerPRIM(GIFReg* r); void __fastcall GIFRegHandlerRGBAQ(GIFReg* r); void __fastcall GIFRegHandlerST(GIFReg* r); void __fastcall GIFRegHandlerUV(GIFReg* r); void __fastcall GIFRegHandlerXYZF2(GIFReg* r); void __fastcall GIFRegHandlerXYZ2(GIFReg* r); void __fastcall GIFRegHandlerTEX0_1(GIFReg* r); void __fastcall GIFRegHandlerTEX0_2(GIFReg* r); void __fastcall GIFRegHandlerCLAMP_1(GIFReg* r); void __fastcall GIFRegHandlerCLAMP_2(GIFReg* r); void __fastcall GIFRegHandlerFOG(GIFReg* r); void __fastcall GIFRegHandlerXYZF3(GIFReg* r); void __fastcall GIFRegHandlerXYZ3(GIFReg* r); void __fastcall GIFRegHandlerNOP(GIFReg* r); void __fastcall GIFRegHandlerTEX1_1(GIFReg* r); void __fastcall GIFRegHandlerTEX1_2(GIFReg* r); void __fastcall GIFRegHandlerTEX2_1(GIFReg* r); void __fastcall GIFRegHandlerTEX2_2(GIFReg* r); void __fastcall GIFRegHandlerXYOFFSET_1(GIFReg* r); void __fastcall GIFRegHandlerXYOFFSET_2(GIFReg* r); void __fastcall GIFRegHandlerPRMODECONT(GIFReg* r); void __fastcall GIFRegHandlerPRMODE(GIFReg* r); void __fastcall GIFRegHandlerTEXCLUT(GIFReg* r); void __fastcall GIFRegHandlerSCANMSK(GIFReg* r); void __fastcall GIFRegHandlerMIPTBP1_1(GIFReg* r); void __fastcall GIFRegHandlerMIPTBP1_2(GIFReg* r); void __fastcall GIFRegHandlerMIPTBP2_1(GIFReg* r); void __fastcall GIFRegHandlerMIPTBP2_2(GIFReg* r); void __fastcall GIFRegHandlerTEXA(GIFReg* r); void __fastcall GIFRegHandlerFOGCOL(GIFReg* r); void __fastcall GIFRegHandlerTEXFLUSH(GIFReg* r); void __fastcall GIFRegHandlerSCISSOR_1(GIFReg* r); void __fastcall GIFRegHandlerSCISSOR_2(GIFReg* r); void __fastcall GIFRegHandlerALPHA_1(GIFReg* r); void __fastcall GIFRegHandlerALPHA_2(GIFReg* r); void __fastcall GIFRegHandlerDIMX(GIFReg* r); void __fastcall GIFRegHandlerDTHE(GIFReg* r); void __fastcall GIFRegHandlerCOLCLAMP(GIFReg* r); void __fastcall GIFRegHandlerTEST_1(GIFReg* r); void __fastcall GIFRegHandlerTEST_2(GIFReg* r); void __fastcall GIFRegHandlerPABE(GIFReg* r); void __fastcall GIFRegHandlerFBA_1(GIFReg* r); void __fastcall GIFRegHandlerFBA_2(GIFReg* r); void __fastcall GIFRegHandlerFRAME_1(GIFReg* r); void __fastcall GIFRegHandlerFRAME_2(GIFReg* r); void __fastcall GIFRegHandlerZBUF_1(GIFReg* r); void __fastcall GIFRegHandlerZBUF_2(GIFReg* r); void __fastcall GIFRegHandlerBITBLTBUF(GIFReg* r); void __fastcall GIFRegHandlerTRXPOS(GIFReg* r); void __fastcall GIFRegHandlerTRXREG(GIFReg* r); void __fastcall GIFRegHandlerTRXDIR(GIFReg* r); void __fastcall GIFRegHandlerHWREG(GIFReg* r); void __fastcall GIFRegHandlerSIGNAL(GIFReg* r); void __fastcall GIFRegHandlerFINISH(GIFReg* r); void __fastcall GIFRegHandlerLABEL(GIFReg* r); public: GSState(int w, int h, HWND hWnd, HRESULT& hr); virtual ~GSState(); bool m_fMultiThreaded; virtual HRESULT ResetDevice(bool fForceWindowed = false); UINT32 Freeze(freezeData* fd, bool fSizeOnly); UINT32 Defrost(const freezeData* fd); virtual void Reset(); void WriteCSR(UINT32 csr); void ReadFIFO(BYTE* pMem); void Transfer1(BYTE* pMem, UINT32 addr); void Transfer2(BYTE* pMem, UINT32 size); void Transfer3(BYTE* pMem, UINT32 size); void Transfer(BYTE* pMem, UINT32 size, GIFPath& path); void VSync(int field); void GSirq(void (*fpGSirq)()) {m_fpGSirq = fpGSirq;} UINT32 MakeSnapshot(char* path); void Capture(); CString m_strDefaultTitle; int m_iOSD; void ToggleOSD(); // state void CaptureState(CString fn); FILE* m_sfp; // logging FILE* m_fp; #ifdef DEBUG_LOGVERTICES #define LOGV(_x_) LOGVERTEX _x_ #else #define LOGV(_x_) #endif #ifdef DEBUG_LOG void LOG(LPCTSTR fmt, ...) { va_list args; va_start(args, fmt); //////////// /* if(_tcsstr(fmt, _T("VSync")) || _tcsstr(fmt, _T("*** WARNING ***")) // || _tcsstr(fmt, _T("Flush")) || _tcsstr(fmt, _T("CSR")) || _tcsstr(fmt, _T("DISP")) || _tcsstr(fmt, _T("FRAME")) || _tcsstr(fmt, _T("ZBUF")) || _tcsstr(fmt, _T("SMODE")) || _tcsstr(fmt, _T("PMODE")) || _tcsstr(fmt, _T("BITBLTBUF")) || _tcsstr(fmt, _T("TRX")) // || _tcsstr(fmt, _T("PRIM")) // || _tcsstr(fmt, _T("RGB")) // || _tcsstr(fmt, _T("XYZ")) // || _tcsstr(fmt, _T("ST")) // || _tcsstr(fmt, _T("XYOFFSET")) // || _tcsstr(fmt, _T("TEX")) || _tcsstr(fmt, _T("TEX0")) // || _tcsstr(fmt, _T("TEX2")) // || _tcsstr(fmt, _T("TEXFLUSH")) // || _tcsstr(fmt, _T("UV")) // || _tcsstr(fmt, _T("FOG")) // || _tcsstr(fmt, _T("ALPHA")) // || _tcsstr(fmt, _T("TBP0")) == fmt // || _tcsstr(fmt, _T("CBP")) == fmt // || _tcsstr(fmt, _T("*TC2 ")) == fmt ) */ if(m_fp) { TCHAR buff[2048]; _stprintf(buff, _T("%d: "), clock()); _vstprintf(buff + strlen(buff), fmt, args); _fputts(buff, m_fp); fflush(m_fp); } va_end(args); } #else #define LOG __noop #endif #ifdef DEBUG_LOG2 void LOG2(LPCTSTR fmt, ...) { va_list args; va_start(args, fmt); if(m_fp) { TCHAR buff[2048]; _stprintf(buff, _T("%d: "), clock()); _vstprintf(buff + strlen(buff), fmt, args); _fputts(buff, m_fp); } va_end(args); } #else #define LOG2 __noop #endif };
[ "zerofrog@23c756db-88ba-2448-99d7-e6e4c676ec84" ]
[ [ [ 1, 446 ] ] ]
79498792f616361c5b251bae89820569122e84a7
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/date_time/example/gregorian/days_since_year_start.cpp
657ea9b63e7cb4f443c4563389a0e678989a6423
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
648
cpp
#include <iostream> #include "boost/date_time/gregorian/gregorian.hpp" int main() { using namespace boost::gregorian; date today = day_clock::local_day(); //Subtract two dates to get a duration date_duration days_since_year_start = today - date(today.year(),Jan,1); std::cout << "Days since Jan 1: " << days_since_year_start.days() << std::endl; return 0; }; /* Copyright 2001-2004: CrystalClear Software, Inc * http://www.crystalclearsoftware.com * * Subject to the Boost Software License, Version 1.0. * (See accompanying file LICENSE-1.0 or http://www.boost.org/LICENSE-1.0) */
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 25 ] ] ]
f275bb3ae24e34234a5c8e94bc3af6b9fe13ed88
3b5dcd8c97cf0b128ff4571f616e6f93cde4d14f
/src-qt3/StandardTypes/Modules/Video/Common/v4ldemos/rgb2yuv.h
a96d0045daa4d23a472680d4a43d18b33d3cf960
[]
no_license
jeez/iqr
d096820360516cda49f33a96cfe34ded36300c4c
c6e066cc5d4ce235d4399ca34e0b238d7784a7af
refs/heads/master
2021-01-01T16:55:55.516919
2011-02-10T12:00:01
2011-02-10T12:00:01
1,109,194
1
0
null
null
null
null
UTF-8
C++
false
false
6,600
h
/*--------------------------------------------------------------------------------------*/ // File: rgb2yuv.h // Desription: Rgb2yuv class definition // Author: Ben Bridgwater // History: // 09/16/00 Initial revision. /*--------------------------------------------------------------------------------------*/ #ifndef _RGB2YUV_H #define _RGB2YUV_H /*--------------------------------------------------------------------------------------*/ #include "types.h" /*--------------------------------------------------------------------------------------*/ struct RGB { uint1 r; // 0-255 uint1 g; // 0-255 uint1 b; // 0-255 }; struct YCbCr { uint1 y_; // 16-235 (luma) uint1 cb; // 16-240, 0 at 128 uint1 cr; // 16-240, 0 at 128 }; /*--------------------------------------------------------------------------------------*/ class RGB2YUV { private: static const int MinYUV256 = -127 * 256; static const int MaxYUV256 = 127 * 256; private: // All multiplied by 256 int yr[256]; int yg[256]; int yb[256]; int ur[256]; int ug[256]; int ub[256]; int vr[256]; int vg[256]; int vb[256]; uint y2y_[256]; uint u2cb[256]; uint v2cr[256]; public: RGB2YUV(); ~RGB2YUV() {} void RGBToYCbCr(uint1 r, uint1 g, uint1 b, YCbCr *yCbCr); }; // end RGB2YUV /*--------------------------------------------------------------------------------------*/ class YUV2RGB { private: static const int MaxRGB256 = 255 * 256; private: // All multiplied by 256 int xy[256]; int rv[256]; int gu[256]; int gv[256]; int bu[256]; public: YUV2RGB(); ~YUV2RGB() {} void YCbCrToRGB(uint1 y_, uint1 cb, uint1 cr, RGB *rgb); uint1 YCbCrToBGR233(uint1 y_, uint1 cb, uint1 cr); uint2 YCbCrToRGB555(uint1 y_, uint1 cb, uint1 cr); uint2 YCbCrToRGB565(uint1 y_, uint1 cb, uint1 cr); uint4 YCbCrToARGB32(uint1 y_, uint1 cb, uint1 cr); #if (0) uint1 YCbCrToHi240 (uint y_, uint cb, uint cr); #endif }; // end YUV2RGB /*--------------------------------------------------------------------------------------*/ inline void RGB2YUV::RGBToYCbCr(uint1 r, uint1 g, uint1 b, YCbCr *yCbCr) { // y,u,v all (-127..+127) * 256, since components multiplied by 256 int4 y = yr[r] + yg[g] + yb[b]; int4 u = ur[r] + ug[g] + ub[b]; int4 v = vr[r] + vg[g] + vb[b]; if (y < MinYUV256) y = MinYUV256; else if (y > MaxYUV256) y = MaxYUV256; if (u < MinYUV256) u = MinYUV256; else if (u > MaxYUV256) u = MaxYUV256; if (v < MinYUV256) v = MinYUV256; else if (v > MaxYUV256) v = MaxYUV256; yCbCr->y_ = y2y_[y >> 8]; yCbCr->cb = u2cb[u >> 8]; yCbCr->cr = v2cr[v >> 8]; } // end RGB2YUV::RGBToYCbCr /*--------------------------------------------------------------------------------------*/ inline void YUV2RGB::YCbCrToRGB(uint1 y_, uint1 cb, uint1 cr, RGB *rgb) { // r,g,b all (0..255) * 256, since components multiplied by 256 int4 r = xy[y_] + rv[cr]; int4 g = xy[y_] + gu[cb] + gv[cr]; int4 b = xy[y_] + bu[cb]; if (r < 0) r = 0; else if (r > MaxRGB256) r = MaxRGB256; if (g < 0) g = 0; else if (g > MaxRGB256) g = MaxRGB256; if (b < 0) b = 0; else if (b > MaxRGB256) b = MaxRGB256; rgb->r = r >> 8; rgb->g = g >> 8; rgb->b = b >> 8; } // end YUV2RGB::YCbCrToRGB /*--------------------------------------------------------------------------------------*/ inline uint1 YUV2RGB::YCbCrToBGR233(uint1 y_, uint1 cb, uint1 cr) { // r,g,b all (0..255) * 256, since components multiplied by 256 int4 r = xy[y_] + rv[cr]; int4 g = xy[y_] + gu[cb] + gv[cr]; int4 b = xy[y_] + bu[cb]; if (r < 0) r = 0; else if (r > MaxRGB256) r = MaxRGB256; if (g < 0) g = 0; else if (g > MaxRGB256) g = MaxRGB256; if (b < 0) b = 0; else if (b > MaxRGB256) b = MaxRGB256; // 16 -> 8 = 8. b >> 8, g >> 8 + b2, r >> 8 + b2 + g3 return (((r >> 13) & 0x07) | ((g >> 10) & 0x038) | ((b >> 8) & 0x0c0)); // RGB masks } // end YUV2RGB::YCbCrToBGR233 /*--------------------------------------------------------------------------------------*/ inline uint2 YUV2RGB::YCbCrToRGB555(uint1 y_, uint1 cb, uint1 cr) { // r,g,b all (0..255) * 256, since components multiplied by 256 int4 r = xy[y_] + rv[cr]; int4 g = xy[y_] + gu[cb] + gv[cr]; int4 b = xy[y_] + bu[cb]; if (r < 0) r = 0; else if (r > MaxRGB256) r = MaxRGB256; if (g < 0) g = 0; else if (g > MaxRGB256) g = MaxRGB256; if (b < 0) b = 0; else if (b > MaxRGB256) b = MaxRGB256; // 16 -> 15 = 1. r >> 1, g >> 1 + r5, b >> 1 + r5 + g5 return (((r >> 1) & 0x07c00) | ((g >> 6) & 0x03e0) | ((b >> 11) & 0x01f)); // RGB masks } // end YUV2RGB::YCbCrToRGB555 /*--------------------------------------------------------------------------------------*/ inline uint2 YUV2RGB::YCbCrToRGB565(uint1 y_, uint1 cb, uint1 cr) { // r,g,b all (0..255) * 256, since components multiplied by 256 int4 r = xy[y_] + rv[cr]; int4 g = xy[y_] + gu[cb] + gv[cr]; int4 b = xy[y_] + bu[cb]; if (r < 0) r = 0; else if (r > MaxRGB256) r = MaxRGB256; if (g < 0) g = 0; else if (g > MaxRGB256) g = MaxRGB256; if (b < 0) b = 0; else if (b > MaxRGB256) b = MaxRGB256; // 16 -> 16 = 0. r >> 0, g >> 0 + r5, b >> 0 + r5 + g6 return (((r >> 0) & 0x0f800) | ((g >> 5) & 0x07e0) | ((b >> 11) & 0x01f)); // RGB masks } // end YUV2RGB::YCbCrToRGB565 /*--------------------------------------------------------------------------------------*/ inline uint4 YUV2RGB::YCbCrToARGB32(uint1 y_, uint1 cb, uint1 cr) { // r,g,b all (0..255) * 256, since components multiplied by 256 int4 r = xy[y_] + rv[cr]; int4 g = xy[y_] + gu[cb] + gv[cr]; int4 b = xy[y_] + bu[cb]; if (r < 0) r = 0; else if (r > MaxRGB256) r = MaxRGB256; if (g < 0) g = 0; else if (g > MaxRGB256) g = MaxRGB256; if (b < 0) b = 0; else if (b > MaxRGB256) b = MaxRGB256; return ((uint4) (((r << 8) & 0x0ff0000) | (g & 0x0ff00) | ((b >> 8) & 0x0ff))); } // end YUV2RGB::YCbCrToARGB32 /*--------------------------------------------------------------------------------------*/ #endif /*--------------------------------------------------------------------------------------*/
[ [ [ 1, 274 ] ] ]
892d1dce663cf26fb21ec30345cc1b7e0f2d7e68
63c7e5c07ef73c3d53088ec124a940d383fbfd81
/bullet_ogre/bullet_core.h
2de6027c8e332e75d939a0a9fe1feb5f75dd450c
[]
no_license
dgoemans/openrage
f66e01f0a3e81f760e62d9058f5d6b21d71c2000
fa7d2fc52f3df17d60373736c8061d2560e0ebac
refs/heads/master
2020-02-26T14:33:32.803806
2008-03-14T15:01:25
2008-03-14T15:01:25
32,354,718
0
0
null
null
null
null
UTF-8
C++
false
false
3,694
h
#ifndef H_BULLETCORE_H #define H_BULLETCORE_H #include "btBulletDynamicsCommon.h" #include "Ogre.h" class coreBulletNode : public btDefaultMotionState { public: Ogre::SceneNode *node; float mass; Ogre::String name; btRigidBody *body; public: // build a new object integrating Ogre3D Scene Node and Bullet collision shape // load the scene node, starting transform, and CoM transform (default values provided) // Call various functions to init the physics system transforms (inhereted code) coreBulletNode( Ogre::SceneNode *n, const btTransform startTrans = btTransform::getIdentity(), const btTransform centerOfMassOffset = btTransform::getIdentity() ) : btDefaultMotionState( startTrans, centerOfMassOffset ) { node = n; }; // translate Bullet btTransform into Ogre3D Scene Node orientation and position void hammerNode(); // switch the Ogre3D scene node this Bullet transform is associated with void setNode( Ogre::SceneNode *n ) { node = n; }; // return the Ogre3D scene node this Bullet transform is associated with Ogre::SceneNode *getNode() { return node; }; const Ogre::String getName() { return name; }; }; // Top level interface between Ogre and Bullet // Starts, stops, pauses Bullet world, init objects, processes results class coreBullet { protected: // Array of all Bullet/Ogre crossbread nodes in use DYNAMIC OBJECTS std::vector<coreBulletNode *> bullet_nodes; // Array of all STATIC Bullet collision objects std::vector<coreBulletNode *> static_nodes; // Map of defined Bullet shape instances to be re-used by coreBulletNode's // The Bullet shapes are associated with string names, like, "Hex_Block_01", etc. // These names directly reflec the xxxx.mesh name found in .scene files // So, .mesh's are directly linked to the Bullet shapes that represent them in the physics sim. std::map<Ogre::String, btCollisionShape *> shapes; // Ogre3D specifics Ogre::SceneManager *scene; // specifics of Bullet physics solving system bool idle; float collision_margin; float time_scale; public: // Bullet physics world, including collisions btDynamicsWorld *bullet_world; btDefaultCollisionConfiguration* collision_config; // start a new Bullet world coreBullet( Ogre::SceneManager *s ); // reset all Bullet objects to start transforms, v = 0, ang_v = 0; void resetWorld(); // hammer Bullet orientation/position transform results into Ogre3D Scene Nodes int processNodeList( Ogre::Real time ); bool removeNode( Ogre::SceneNode *n ); btRigidBody *addNode( btCollisionShape *shape, Ogre::Real mass, Ogre::SceneNode *n ); btCollisionShape *addSphere( Ogre::String shapename, Ogre::Real radius ); btCollisionShape *addBox( Ogre::String shapename, Ogre::Vector3 size ); btCollisionShape *addStaticMesh( Ogre::String shapename, Ogre::Mesh *mesh ); // returns a pointer to a collision shape if an instance of it already exists, 0 if not btCollisionShape *getShape( Ogre::String meshname ); unsigned long int getShapeMapSize() { return shapes.size(); }; // start/stop/check physics simulation run flag void toggleIdle() { if( idle ) idle = false; else idle = true; }; bool isIdle() { return idle; }; // set/get the time step scale factor void setTimeStep( Ogre::Real step ) { time_scale = step; }; Ogre::Real getTimeStep() { return time_scale; }; // dump debug data to file void dump( const char *filename ); }; #endif
[ "dgoemans@36ee989d-3a48-0410-af8a-351069dbcf3a" ]
[ [ [ 1, 106 ] ] ]
4df85b513c2fc736c5e374c4904f70020bbd929b
fbe2cbeb947664ba278ba30ce713810676a2c412
/iptv_root/iptv_media_util/dscscript.cpp
a3fcec9964bca26384a9b6572e544ea473826048
[]
no_license
abhipr1/multitv
0b3b863bfb61b83c30053b15688b070d4149ca0b
6a93bf9122ddbcc1971dead3ab3be8faea5e53d8
refs/heads/master
2020-12-24T15:13:44.511555
2009-06-04T17:11:02
2009-06-04T17:11:02
41,107,043
0
0
null
null
null
null
UTF-8
C++
false
false
11,974
cpp
/* * DsCScript * * Script engine implementation using Lua (http://www.lua.org) * * $id:$ * Dario Andrade * * Defines the script engine interface */ #include "dscscript.h" extern "C" { #include <lua.h> #include <lualib.h> } #ifdef WIN32 #include <windows.h> #endif #define _DSLIB_SCRIPT_STACKSIZE_DEFAULT 0 #define L ( ( lua_State* ) m_hPrivateState ) /*************************************************************************** * * DsCScriptEngine * ****************************************************************************/ DsCScriptEngine::DsCScriptEngine() : m_hPrivateState( DsNULL ) { } DsCScriptEngine::~DsCScriptEngine() { if ( L ) { lua_close( L ); m_hPrivateState = DsNULL; } } DsRESULT DsCScriptEngine::Execute( DsPCSTR szFilename ) { DsRESULT hr = DsE_POINTER; if ( szFilename ) { if ( !L ) { m_hPrivateState = lua_open( _DSLIB_SCRIPT_STACKSIZE_DEFAULT ); } // see defined macro for 'L' if ( L ) { lua_baselibopen( L ); int iRet = lua_dofile( L, szFilename ); switch ( iRet ) { case 0: hr = DsS_OK; break; // error while running the chunk case LUA_ERRRUN: // syntax error during pre-compilation. case LUA_ERRSYNTAX: // memory allocation error. For such errors, Lua does not call _ERRORMESSAGE (see Section 4.7). case LUA_ERRMEM: // error while running _ERRORMESSAGE. For such errors, Lua does not call _ERRORMESSAGE again, to avoid loops. case LUA_ERRERR: hr = DsE_SCRIPT_PARSE_FAILED; break; // error opening the file (only for lua_dofile). In this case, you may want to check errno, call strerror, or call perror to tell the user what went wrong. case LUA_ERRFILE: hr = DsE_SCRIPT_FILE_NOT_FOUND; break; } // end switch lua error } else { hr = DsE_OUTOFMEMORY; } // end if lua opened ok } // end if filename pointer return hr; } DsCScriptValue DsCScriptEngine::GetGlobalValue( DsPCSTR szValue ) { DsCScriptValue value; // get the file we're working on // note that before this call the file entry table should be at -1 lua_getglobal( L, szValue ); value.m_hPrivateState = m_hPrivateState; value.m_iRef = lua_ref( L, 1 ); return value; } DsRESULT DsCScriptEngine::CallGlobalFunction( DsPCSTR szFunctionName, DsINT32 nArgs, DsINT32 nRets, ... ) { DsRESULT hr = DsE_POINTER; if ( L && szFunctionName ) { lua_getglobal( L, szFunctionName ); if ( lua_type( L, -1 ) == LUA_TFUNCTION ) { hr = DsS_OK; va_list vl; va_start( vl, nRets ); DsINT32 nRealArgs = 0; for ( DsINT32 i = 0; i < nArgs; i++ ) { DsCScriptValue* parg = va_arg( vl, DsCScriptValue* ); if ( parg && parg->HasRef() && lua_getref( L, parg->m_iRef ) ) { nRealArgs++; } } // end if args lua_call( L, nRealArgs, nRets ); // since the last result is on the top (-1), // we iterate deep in stack (-nRets) until top for ( DsINT32 iRet = nRets; iRet > 0; iRet-- ) { // copy the result into top lua_pushvalue( L, -iRet ); DsCScriptValue* pret = va_arg( vl, DsCScriptValue* ); if ( pret ) { pret->m_hPrivateState = L; pret->m_iRef = lua_ref( L, 1 ); } else { lua_pop( L, 1 ); } } // end if rets lua_pop( L, nRets ); va_end( vl ); } else { hr = DsE_INVALIDARG; lua_pop( L, 1 ); } // end if type is function } // end if valid args return hr; } /*************************************************************************** * * DsCScriptNilValue * ****************************************************************************/ DsCScriptNilValue::DsCScriptNilValue( const DsCScriptEngine& refEngine ) : DsCScriptValue( LUA_REFNIL, refEngine ) { } /*************************************************************************** * * DsCScriptTableValue * ****************************************************************************/ DsCScriptTableValue::DsCScriptTableValue( const DsCScriptEngine& refEngine ) : DsCScriptValue( LUA_NOREF, refEngine ) { lua_newtable( L ); m_iRef = lua_ref( L, 1 ); } void DsCScriptTableValue::AddValue( DsCScriptValue& refValValue ) { // we need a non nil valid reference to a value if ( IsValid() && refValValue.IsValid() ) { if ( lua_getref( L, m_iRef ) ) { if ( lua_getref( L, refValValue.m_iRef ) ) { // set the table at -2, indexed by the incremented length // to the value we have just pushed lua_rawseti( L, -2, lua_getn( L, -2 ) + 1 ); } // end if the value was pushed lua_pop( L, 1 ); } // end if this table was pushed } // end if value and this table are valid } void DsCScriptTableValue::SetValue( DsCScriptValue& refKeyValue, DsCScriptValue& refValValue ) { // the value can be nil, but must be a valid reference hence the HasRef if ( IsValid() && refKeyValue.IsValid() && refValValue.HasRef() ) { if ( lua_getref( L, m_iRef ) ) { if ( lua_getref( L, refKeyValue.m_iRef ) ) { if ( lua_getref( L, refValValue.m_iRef ) ) { // table is at -3 (from top), key -2, value -1 lua_settable ( L, -3 ); } else { // pop key and table from stack lua_pop( L, 2 ); } } else { // pop table from stack lua_pop( L, 1 ); } } } // end if this table, key and values are valid } /*************************************************************************** * * DsCScriptValue * ****************************************************************************/ DsCScriptValue::DsCScriptValue( DsINT32 iRef, const DsCScriptEngine& refEngine ) : m_hPrivateState( refEngine.m_hPrivateState ), m_iRef( iRef ) { } DsCScriptValue::DsCScriptValue() : m_hPrivateState( DsNULL ), m_iRef( LUA_NOREF ) { } DsCScriptValue::DsCScriptValue( const DsCScriptValue& refValue ) : m_hPrivateState( refValue.m_hPrivateState ), m_iRef( LUA_NOREF ) { if ( refValue.IsValid() ) { if ( lua_getref( L, refValue.m_iRef ) ) { // 1 for locking m_iRef = lua_ref( L, 1 ); } } } DsCScriptValue& DsCScriptValue::operator = ( const DsCScriptValue& refValue ) { m_hPrivateState = refValue.m_hPrivateState; m_iRef = LUA_NOREF; if ( refValue.IsValid() ) { if ( lua_getref( L, refValue.m_iRef ) ) { // 1 for locking m_iRef = lua_ref( L, 1 ); } } return *this; } DsCScriptValue::DsCScriptValue( const DsCScriptEngine& refEngine, DsDOUBLE dval ) : m_hPrivateState( refEngine.m_hPrivateState ), m_iRef( LUA_NOREF ) { lua_pushnumber( L, dval ); m_iRef = lua_ref( L, 1 ); } DsCScriptValue::DsCScriptValue( const DsCScriptEngine& refEngine, DsPCSTR szVal ) : m_hPrivateState( refEngine.m_hPrivateState ), m_iRef( LUA_NOREF ) { lua_pushstring( L, szVal ); m_iRef = lua_ref( L, 1 ); } DsCScriptValue::~DsCScriptValue() { if ( IsValid() ) { lua_unref( L, m_iRef ); } m_iRef = LUA_NOREF; m_hPrivateState = DsNULL; } DsBOOL DsCScriptValue::IsValid() const { return ( m_iRef != LUA_NOREF ) && !IsNil(); } DsBOOL DsCScriptValue::IsNil() const { return m_iRef == LUA_REFNIL; } DsBOOL DsCScriptValue::HasRef() const { return m_iRef != LUA_NOREF; } DsCString DsCScriptValue::GetStr() const { DsPCSTR szValue = DsNULL; if ( IsValid() ) { if ( lua_getref( L, m_iRef ) ) { if ( lua_isstring( L, -1 ) ) { szValue = lua_tostring( L, -1 ); } } // end if lua ref could be found and is on the stack } // end if ref is valid return szValue; } DsDOUBLE DsCScriptValue::GetInt() const { DsDOUBLE dVal = 0.0; if ( IsValid() ) { if ( lua_getref( L, m_iRef ) ) { if ( lua_isnumber( L, -1 ) ) { dVal = lua_tonumber( L, -1 ); } } // end if lua ref could be found and is on the stack } // end if ref is valid return dVal; } DsINT32 DsCScriptValue::GetTableLength() const { DsINT32 iLength = 0; if ( IsValid() ) { if ( lua_getref( L, m_iRef ) ) { iLength = lua_getn( L, -1 ); lua_pop( L, 1 ); } } return iLength; } DsCScriptValue DsCScriptValue::GetTableValue( DsPCSTR szKey ) { DsCScriptValue value; if ( IsValid() ) { if ( lua_getref( L, m_iRef ) ) { lua_pushstring( L, szKey ); lua_gettable( L, -2 ); value.m_iRef = lua_ref( L, 1 ); value.m_hPrivateState = m_hPrivateState; } } return value; } DsCScriptValue DsCScriptValue::GetTableValue( DsINT32 uiIndex ) { DsCScriptValue value; if ( IsValid() ) { if ( lua_getref( L, m_iRef ) ) { lua_pushnumber( L, uiIndex ); lua_gettable( L, -2 ); value.m_iRef = lua_ref( L, 1 ); value.m_hPrivateState = m_hPrivateState; } } return value; } DsRESULT DsCScriptValue::Call( DsINT32 nArgs, DsINT32 nRets, ... ) { DsRESULT hr = DsE_INVALIDARG; if ( IsValid() && lua_getref( L, m_iRef ) ) { if ( lua_type( L, -1 ) == LUA_TFUNCTION ) { hr = DsS_OK; va_list vl; va_start( vl, nRets ); DsINT32 nRealArgs = 0; for ( DsINT32 i = 0; i < nArgs; i++ ) { DsCScriptValue* parg = va_arg( vl, DsCScriptValue* ); if ( parg && parg->HasRef() && lua_getref( L, parg->m_iRef ) ) { nRealArgs++; } } // end if args lua_call( L, nRealArgs, nRets ); // since the last result is on the top (-1), // we iterate deep in stack (-nRets) until top for ( DsINT32 iRet = nRets; iRet > 0; iRet-- ) { // copy the result into top lua_pushvalue( L, -iRet ); DsCScriptValue* pret = va_arg( vl, DsCScriptValue* ); if ( pret ) { pret->m_hPrivateState = L; pret->m_iRef = lua_ref( L, 1 ); } else { lua_pop( L, 1 ); } } // end if rets lua_pop( L, nRets ); va_end( vl ); } else { lua_pop( L, 1 ); } // end if type is function } return hr; }
[ "heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89" ]
[ [ [ 1, 503 ] ] ]
97111e1bd5fac978346ec803131c19fb71fdc6fb
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Interpolation/Wm4IntpSphere2.cpp
9c94cdc7266a3480292f0a20025a9a99cdbc5827
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
3,788
cpp
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #include "Wm4FoundationPCH.h" #include "Wm4IntpSphere2.h" namespace Wm4 { //---------------------------------------------------------------------------- template <class Real> IntpSphere2<Real>::IntpSphere2 (int iQuantity, Real* afTheta, Real* afPhi, Real* afF, bool bOwner, Query::Type eQueryType) { // Copy the input data. The larger arrays are used to support wrap-around // in the Delaunay triangulation for the interpolator. The Vector2<Real> // object V corresponds to (V.X(),V.Y()) = (theta,phi). int iThreeQuantity = 3*iQuantity; Vector2<Real>* akWrapAngles = WM4_NEW Vector2<Real>[iThreeQuantity]; Real* afWrapF = WM4_NEW Real[iThreeQuantity]; for (int i = 0; i < iQuantity; i++) { akWrapAngles[i].X() = afTheta[i]; akWrapAngles[i].Y() = afPhi[i]; afWrapF[i] = afF[i]; } if (bOwner) { WM4_DELETE[] afTheta; WM4_DELETE[] afPhi; WM4_DELETE[] afF; } // use periodicity to get wrap-around in the Delaunay triangulation int i0 = 0, i1 = iQuantity, i2 = 2*iQuantity; for (/**/; i0 < iQuantity; i0++, i1++, i2++) { akWrapAngles[i1].X() = akWrapAngles[i0].X() + Math<Real>::TWO_PI; akWrapAngles[i2].X() = akWrapAngles[i0].X() - Math<Real>::TWO_PI; akWrapAngles[i1].Y() = akWrapAngles[i0].Y(); akWrapAngles[i2].Y() = akWrapAngles[i0].Y(); afWrapF[i1] = afWrapF[i0]; afWrapF[i2] = afWrapF[i0]; } m_pkDel = WM4_NEW Delaunay2<Real>(iThreeQuantity,akWrapAngles,(Real)0.001, true,eQueryType); m_pkInterp = WM4_NEW IntpQdrNonuniform2<Real>(*m_pkDel,afWrapF,true); } //---------------------------------------------------------------------------- template <class Real> IntpSphere2<Real>::~IntpSphere2 () { WM4_DELETE m_pkDel; WM4_DELETE m_pkInterp; } //---------------------------------------------------------------------------- template <class Real> void IntpSphere2<Real>::GetSphericalCoords (Real fX, Real fY, Real fZ, Real& rfTheta, Real& rfPhi) { // Assumes (x,y,z) is unit length. Returns -PI <= theta <= PI and // 0 <= phiAngle <= PI. if (fZ < (Real)1.0) { if (fZ > -(Real)1.0) { rfTheta = Math<Real>::ATan2(fY,fX); rfPhi = Math<Real>::ACos(fZ); } else { rfTheta = -Math<Real>::PI; rfPhi = Math<Real>::PI; } } else { rfTheta = -Math<Real>::PI; rfPhi = (Real)0.0; } } //---------------------------------------------------------------------------- template <class Real> bool IntpSphere2<Real>::Evaluate (Real fTheta, Real fPhi, Real& rfF) { Vector2<Real> kAngles(fTheta,fPhi); Real fThetaDeriv, fPhiDeriv; return m_pkInterp->Evaluate(kAngles,rfF,fThetaDeriv,fPhiDeriv); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- template WM4_FOUNDATION_ITEM class IntpSphere2<float>; template WM4_FOUNDATION_ITEM class IntpSphere2<double>; //---------------------------------------------------------------------------- }
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 110 ] ] ]
78a9d8ebe97fb0b180d9b031937c07239b70a7d9
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/ParticleUniverse/include/ParticleRenderers/ParticleUniverseLightRenderer.h
4d5fd3d09aa43ee489ef25afb34732d6b56bbfb0
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
5,314
h
/* ----------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2006-2008 Henry van Merode Usage of this program is free for non-commercial use and licensed under the the terms of the GNU Lesser General Public License. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #ifndef __PU_LIGHT_RENDERER_H__ #define __PU_LIGHT_RENDERER_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseRenderer.h" #include "ParticleUniverseTechnique.h" namespace ParticleUniverse { /** Visual data specific for this type of renderer. */ class _ParticleUniverseExport LightRendererVisualData : public IVisualData { public: LightRendererVisualData (Ogre::SceneNode* sceneNode) : IVisualData(), node(sceneNode){}; Ogre::SceneNode* node; Ogre::Light* light; virtual void setVisible(bool visible) { if (node) { node->setVisible(visible); } }; }; /** The LightRenderer class is responsible to render particles as a light. */ class _ParticleUniverseExport LightRenderer : public ParticleRenderer { protected: Ogre::String mLightName; // Used for random light name prefix std::vector<LightRendererVisualData*> mAllVisualData; std::vector<LightRendererVisualData*> mVisualData; std::vector<Ogre::Light*> mLights; size_t mQuota; Ogre::Light::LightTypes mLightType; Ogre::ColourValue mDiffuseColour; Ogre::ColourValue mSpecularColour; Ogre::Real mAttenuationRange; Ogre::Real mAttenuationConstant; Ogre::Real mAttenuationLinear; Ogre::Real mAttenuationQuadratic; Ogre::Radian mSpotlightInnerAngle; Ogre::Radian mSpotlightOuterAngle; Ogre::Real mSpotlightFalloff; Ogre::Real mPowerScale; public: LightRenderer(void); virtual ~LightRenderer(void); /** Return the type of light that is emitted. */ Ogre::Light::LightTypes getLightType(void) const; /** Set the type of light that is emitted. */ void setLightType(Ogre::Light::LightTypes lightType); /** */ const Ogre::ColourValue& getDiffuseColour(void) const; void setDiffuseColour(const Ogre::ColourValue& diffuseColour); /** */ const Ogre::ColourValue& getSpecularColour(void) const; void setSpecularColour(const Ogre::ColourValue& specularColour); /** */ Ogre::Real getAttenuationRange(void) const; void setAttenuationRange(Ogre::Real attenuationRange); /** */ Ogre::Real getAttenuationConstant(void) const; void setAttenuationConstant(Ogre::Real attenuationConstant); /** */ Ogre::Real getAttenuationLinear(void) const; void setAttenuationLinear(Ogre::Real attenuationLinear); /** */ Ogre::Real getAttenuationQuadratic(void) const; void setAttenuationQuadratic(Ogre::Real attenuationQuadratic); /** */ const Ogre::Radian& getSpotlightInnerAngle(void) const; void setSpotlightInnerAngle(const Ogre::Radian& spotlightInnerAngle); /** */ const Ogre::Radian& getSpotlightOuterAngle(void) const; void setSpotlightOuterAngle(const Ogre::Radian& spotlightOuterAngle); /** */ Ogre::Real getSpotlightFalloff(void) const; void setSpotlightFalloff(Ogre::Real spotlightFalloff); /** */ Ogre::Real getPowerScale(void) const; void setPowerScale(Ogre::Real powerScale); /** Deletes all ChildSceneNodes en Lights. */ void _destroyAll(void); /** Disable all ChildSceneNodes. */ virtual void _notifyStop(void); /** @copydoc ParticleRenderer::setVisible */ virtual void setVisible(bool visible = true); /** @copydoc ParticleRenderer::_prepare */ virtual void _prepare(ParticleTechnique* technique); /** @copydoc ParticleRenderer::_updateRenderQueue */ virtual void _updateRenderQueue(Ogre::RenderQueue* queue, ParticlePool* pool); /** @copydoc ParticleRenderer::_setMaterialName */ virtual void _setMaterialName(const Ogre::String& materialName); /** @copydoc ParticleRenderer::_notifyCurrentCamera */ virtual void _notifyCurrentCamera(Ogre::Camera* cam); /** @copydoc ParticleRenderer::_notifyAttached */ virtual void _notifyAttached(Ogre::Node* parent, bool isTagPoint = false); /** @copydoc ParticleRenderer::_notifyParticleQuota */ virtual void _notifyParticleQuota(size_t quota); /** @copydoc ParticleRenderer::_notifyDefaultDimensions */ virtual void _notifyDefaultDimensions(Ogre::Real width, Ogre::Real height, Ogre::Real depth); /** @copydoc ParticleRenderer::_notifyParticleResized */ virtual void _notifyParticleResized(void); /** @copydoc ParticleRenderer::_getSortMode */ virtual Ogre::SortMode _getSortMode(void) const; /** @copydoc ParticleRenderer::copyAttributesTo */ virtual void copyAttributesTo (ParticleRenderer* renderer); }; } #endif
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 172 ] ] ]
b8091e28d2ecb6397e7edf95e50bbcf5b9c2ac9f
ab41c2c63e554350ca5b93e41d7321ca127d8d3a
/glm/gtx/fast_exponential.inl
e5a3a6c732fa1258ebbe08a57177668b24006c00
[]
no_license
burner/e3rt
2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e
775470cc9b912a8c1199dd1069d7e7d4fc997a52
refs/heads/master
2021-01-11T08:08:00.665300
2010-04-26T11:42:42
2010-04-26T11:42:42
337,021
3
0
null
null
null
null
UTF-8
C++
false
false
8,313
inl
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2009 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2006-01-09 // Updated : 2006-01-09 // Licence : This source is under MIT License // File : glm/gtx/fast_exponential.h /////////////////////////////////////////////////////////////////////////////////////////////////// namespace glm{ namespace gtx{ namespace fast_exponential { // fastPow: template <typename T> inline T fastPow(const T x, const T y) { return exp(y * log(x)); } template <typename T> inline detail::tvec2<T> fastPow( const detail::tvec2<T>& x, const detail::tvec2<T>& y) { return detail::tvec2<T>( fastPow(x.x, y.x), fastPow(x.y, y.y)); } template <typename T> inline detail::tvec3<T> fastPow( const detail::tvec3<T>& x, const detail::tvec3<T>& y) { return detail::tvec3<T>( fastPow(x.x, y.x), fastPow(x.y, y.y), fastPow(x.z, y.z)); } template <typename T> inline detail::tvec4<T> fastPow( const detail::tvec4<T>& x, const detail::tvec4<T>& y) { return detail::tvec4<T>( fastPow(x.x, y.x), fastPow(x.y, y.y), fastPow(x.z, y.z), fastPow(x.w, y.w)); } template <typename T> inline T fastPow(const T x, int y) { T f = T(1); for(int i = 0; i < y; ++i) f *= x; return f; } template <typename T> inline detail::tvec2<T> fastPow( const detail::tvec2<T>& x, const detail::tvec2<int>& y) { return detail::tvec2<T>( fastPow(x.x, y.x), fastPow(x.y, y.y)); } template <typename T> inline detail::tvec3<T> fastPow( const detail::tvec3<T>& x, const detail::tvec3<int>& y) { return detail::tvec3<T>( fastPow(x.x, y.x), fastPow(x.y, y.y), fastPow(x.z, y.z)); } template <typename T> inline detail::tvec4<T> fastPow( const detail::tvec4<T>& x, const detail::tvec4<int>& y) { return detail::tvec4<T>( fastPow(x.x, y.x), fastPow(x.y, y.y), fastPow(x.z, y.z), fastPow(x.w, y.w)); } // fastExp // Note: This function provides accurate results only for value between -1 and 1, else avoid it. template <typename T> inline T fastExp(const T x) { // This has a better looking and same performance in release mode than the following code. However, in debug mode it's slower. // return 1.0f + x * (1.0f + x * 0.5f * (1.0f + x * 0.3333333333f * (1.0f + x * 0.25 * (1.0f + x * 0.2f)))); T x2 = x * x; T x3 = x2 * x; T x4 = x3 * x; T x5 = x4 * x; return T(1) + x + (x2 * T(0.5)) + (x3 * T(0.1666666667)) + (x4 * T(0.041666667)) + (x5 * T(0.008333333333)); } /* // Try to handle all values of float... but often shower than std::exp, glm::floor and the loop kill the performance inline float fastExp(float x) { const float e = 2.718281828f; const float IntegerPart = floor(x); const float FloatPart = x - IntegerPart; float z = 1.f; for(int i = 0; i < int(IntegerPart); ++i) z *= e; const float x2 = FloatPart * FloatPart; const float x3 = x2 * FloatPart; const float x4 = x3 * FloatPart; const float x5 = x4 * FloatPart; return z * (1.0f + FloatPart + (x2 * 0.5f) + (x3 * 0.1666666667f) + (x4 * 0.041666667f) + (x5 * 0.008333333333f)); } // Increase accuracy on number bigger that 1 and smaller than -1 but it's not enough for high and negative numbers inline float fastExp(float x) { // This has a better looking and same performance in release mode than the following code. However, in debug mode it's slower. // return 1.0f + x * (1.0f + x * 0.5f * (1.0f + x * 0.3333333333f * (1.0f + x * 0.25 * (1.0f + x * 0.2f)))); float x2 = x * x; float x3 = x2 * x; float x4 = x3 * x; float x5 = x4 * x; float x6 = x5 * x; float x7 = x6 * x; float x8 = x7 * x; return 1.0f + x + (x2 * 0.5f) + (x3 * 0.1666666667f) + (x4 * 0.041666667f) + (x5 * 0.008333333333f)+ (x6 * 0.00138888888888f) + (x7 * 0.000198412698f) + (x8 * 0.0000248015873f);; } */ template <typename T> inline detail::tvec2<T> fastExp( const detail::tvec2<T>& x) { return detail::tvec2<T>( fastExp(x.x), fastExp(x.y)); } template <typename T> inline detail::tvec3<T> fastExp( const detail::tvec3<T>& x) { return detail::tvec3<T>( fastExp(x.x), fastExp(x.y), fastExp(x.z)); } template <typename T> inline detail::tvec4<T> fastExp( const detail::tvec4<T>& x) { return detail::tvec4<T>( fastExp(x.x), fastExp(x.y), fastExp(x.z), fastExp(x.w)); } // fastLog template <typename T> inline T fastLog(const T x) { return std::log(x); } /* Slower than the VC7.1 function... inline float fastLog(float x) { float y1 = (x - 1.0f) / (x + 1.0f); float y2 = y1 * y1; return 2.0f * y1 * (1.0f + y2 * (0.3333333333f + y2 * (0.2f + y2 * 0.1428571429f))); } */ template <typename T> inline detail::tvec2<T> fastLog( const detail::tvec2<T>& x) { return detail::tvec2<T>( fastLog(x.x), fastLog(x.y)); } template <typename T> inline detail::tvec3<T> fastLog( const detail::tvec3<T>& x) { return detail::tvec3<T>( fastLog(x.x), fastLog(x.y), fastLog(x.z)); } template <typename T> inline detail::tvec4<T> fastLog( const detail::tvec4<T>& x) { return detail::tvec4<T>( fastLog(x.x), fastLog(x.y), fastLog(x.z), fastLog(x.w)); } //fastExp2, ln2 = 0.69314718055994530941723212145818f template <typename T> inline T fastExp2(const T x) { return fastExp(0.69314718055994530941723212145818f * x); } template <typename T> inline detail::tvec2<T> fastExp2( const detail::tvec2<T>& x) { return detail::tvec2<T>( fastExp2(x.x), fastExp2(x.y)); } template <typename T> inline detail::tvec3<T> fastExp2( const detail::tvec3<T>& x) { return detail::tvec3<T>( fastExp2(x.x), fastExp2(x.y), fastExp2(x.z)); } template <typename T> inline detail::tvec4<T> fastExp2( const detail::tvec4<T>& x) { return detail::tvec4<T>( fastExp2(x.x), fastExp2(x.y), fastExp2(x.z), fastExp2(x.w)); } // fastLog2, ln2 = 0.69314718055994530941723212145818f template <typename T> inline T fastLog2(const T x) { return fastLog(x) / 0.69314718055994530941723212145818f; } template <typename T> inline detail::tvec2<T> fastLog2( const detail::tvec2<T>& x) { return detail::tvec2<T>( fastLog2(x.x), fastLog2(x.y)); } template <typename T> inline detail::tvec3<T> fastLog2( const detail::tvec3<T>& x) { return detail::tvec3<T>( fastLog2(x.x), fastLog2(x.y), fastLog2(x.z)); } template <typename T> inline detail::tvec4<T> fastLog2( const detail::tvec4<T>& x) { return detail::tvec4<T>( fastLog2(x.x), fastLog2(x.y), fastLog2(x.z), fastLog2(x.w)); } }//namespace fast_exponential }//namespace gtx }//namespace glm
[ [ [ 1, 294 ] ] ]
6662fc3c07fb2951a988fc9dd4cdc61293e8afc7
c86338cfb9a65230aa7773639eb8f0a3ce9d34fd
/MNCudaMT.cpp
79845c682f55b7dec0ec9c5fed479168aef6d45c
[]
no_license
jonike/mnrt
2319fb48d544d58984d40d63dc0b349ffcbfd1dd
99b41c3deb75aad52afd0c315635f1ca9b9923ec
refs/heads/master
2021-08-24T05:52:41.056070
2010-12-03T18:31:24
2010-12-03T18:31:24
113,554,148
0
0
null
null
null
null
UTF-8
C++
false
false
3,561
cpp
//////////////////////////////////////////////////////////////////////////////////////////////////// // MNRT License //////////////////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010 Mathias Neumann, www.maneumann.com. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name Mathias Neumann, nor the names of contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////////////////////////// #include "MNCudaMT.h" #include "MNCudaUtil.h" #include "MNStatContainer.h" #include "3rdParty/MT/MersenneTwister.h" // See 3rdParty/MT/MersenneTwister_kernel.cu extern "C" bool MersenneTwisterGPUInit(const char *fname); extern "C" void MersenneTwisterGPUSeed(unsigned int seed); extern "C" void MersenneTwisterGPU(float* d_outRand, int nPerRNG); MNCudaMT::MNCudaMT(void) { m_bInited = false; } MNCudaMT::~MNCudaMT(void) { } MNCudaMT& MNCudaMT::GetInstance() { static MNCudaMT cudaMT; return cudaMT; } bool MNCudaMT::Init(const char *fname) { bool res = MersenneTwisterGPUInit(fname); m_bInited = res; return res; } bool MNCudaMT::Seed(unsigned int seed) { if(!m_bInited) return false; MersenneTwisterGPUSeed(seed); static StatCounter& ctrSeed = StatCounter::Create("General", "Mersenne Twister (new seed)"); ++ctrSeed; return true; } cudaError_t MNCudaMT::Generate(float* d_outRand, int count) { if(!m_bInited) return cudaErrorUnknown; // Check if count is OK. if(count != GetAlignedCount(count)) return cudaErrorInvalidValue; int nPerRNG = count / MT_RNG_COUNT; MersenneTwisterGPU(d_outRand, nPerRNG); static StatCounter& ctrRandom = StatCounter::Create("General", "Mersenne Twister (generated randoms)"); ctrRandom += count; return cudaSuccess; } unsigned int MNCudaMT::GetAlignedCount(unsigned int count) { // Taken from SDK 3.0 sample. unsigned int numPerRNG = MNCUDA_DIVUP(count, MT_RNG_COUNT); unsigned int numAligned = MNCUDA_ALIGN_EX(numPerRNG, 2); return numAligned * MT_RNG_COUNT; }
[ [ [ 1, 106 ] ] ]
c66e6aeb8e832629cd06f616e81e8e8c4048db4e
416087e3ebe80322737f53b3ca8ad5581967bb8d
/PCSuit/ECGProject/ECGSignalProcessing.cpp
1b7a21b5d6141daedf9433e5da232b071f8d0324
[]
no_license
caijilong/ecgsystem
a05c5796cbd86e5a4df1f4265ffa8c8252b126c0
fcc385ff759cb377a881af3c8fddca1224522e44
refs/heads/master
2021-01-21T22:26:41.957544
2009-07-28T16:27:17
2009-07-28T16:27:17
37,576,995
0
0
null
null
null
null
UTF-8
C++
false
false
18,029
cpp
#include "stdafx.h" #include "ECGSignalProcessing.h" #include "math.h" CECGsp::CECGsp(int s,int size,int BAT,int Resolution) { sampling_rate = s; result_size = size; PeakDect = new CPeakDetection(s,size,BAT,Resolution); result_buffer = 0; result_buffer3 = 0; Envenlope = 0; FT= 0; Capstrum = 0; x = 0; wk1 = 0; wk2 = 0; } void CECGsp::FullDataFT(short *wave_buffer,int dwDataLength,int fft_length) { int i=0,c,j,fft_power=0; int max_signal = 0; double tempflt,f; double max_spectrum_buffer=0,max_spectrum_buffer3=0; int start_point=0; float b; if (Envenlope == 0){ Envenlope = new float[fft_length/2]; FT= new float[fft_length/2]; Capstrum = new float[fft_length/2]; } for (int j=0 ; j<fft_length/2 ; j++){ Envenlope[j] = 0; FT[j] = 0; Capstrum[j] = 0; } COMPLEX *result_buffer2 = new COMPLEX[fft_length]; if (result_buffer == 0) result_buffer = new float[fft_length]; if (result_buffer3 == 0) result_buffer3 = new float[fft_length]; for (j=0 ; j<dwDataLength ; j++){ max_signal = (max_signal > abs(wave_buffer[j])) ? max_signal : abs(wave_buffer[j]); } i = fft_length; while(i > 1) { i>>=1; fft_power++; } for (start_point=0 ; (start_point + fft_length) < dwDataLength ; start_point+=(fft_length/2)){ i=0; for (c = start_point ; c < fft_length + start_point;c++) { result_buffer2[i].real = double(wave_buffer[c]) / max_signal; i++; } for (j=0 ; j < fft_length ; j++) { if (j == dwDataLength) break; b = 0.54-0.46*cos(2*pi*j/fft_length); result_buffer2[j].real *= b; } fft(result_buffer2,fft_power); max_spectrum_buffer = 0; for (i = 0 ; i < fft_length ; i++) { tempflt = result_buffer2[i].real * result_buffer2[i].real; tempflt += result_buffer2[i].imag * result_buffer2[i].imag; // result_buffer[i] += log10( (double) (sqrt(tempflt) + 1.0) ); // result_buffer[i] = log( (double) (sqrt(tempflt) + 1.0) ); result_buffer[i] = log10(sqrt(tempflt)+1); result_buffer2[i].real = log(sqrt(tempflt)+1); result_buffer2[i].imag = 0; if (i>0) max_spectrum_buffer = (max_spectrum_buffer > fabs(result_buffer[i])) ? max_spectrum_buffer : fabs(result_buffer[i]); } /* for (j = 0 ; j < fft_length ; j++) { result_buffer2[j].real = result_buffer[j]; result_buffer2[j].imag = 0; } */ for (j = 1 ; j < fft_length/2 ; j++) { FT[j] += result_buffer[j]; } result_buffer2[0].real = 0; ifft(result_buffer2,fft_power); /* j = 1; for (f=1;f < fft_length;f+=(float(fft_length)/result_size)) { if (f > fft_length/2) Capstrum[j] = 0; else Capstrum[j] += (fabs(result_buffer2[int(f)].real); j++; }*/ for (j = 0 ; j < fft_length ; j++) { if (j > 30 && j < fft_length - 30 - 1) result_buffer2[j].real = 0; else result_buffer2[j].real /= fft_length; result_buffer2[j].imag = 0; } fft(result_buffer2,fft_power); max_spectrum_buffer3 = 0; for (j = 0 ; j < fft_length ; j++) { result_buffer2[j].real *= LOGeTOLOG10/20; // result_buffer2[j].real *= (LOGeTOLOG10/20); if (i>0) max_spectrum_buffer3 = (max_spectrum_buffer3 > fabs(result_buffer2[j].real)) ? max_spectrum_buffer3 : fabs(result_buffer2[j].real); } for (j = 0 ; j < fft_length/2 ; j++) { Envenlope[j] += fabs(result_buffer2[j].real); } } MaxFT=0; EvenlopeMax=0; CapstrumMax=0; for (int i=0;i< fft_length/2 ;i++){ MaxFT = (MaxFT > FT[i]) ? MaxFT : FT[i]; } for (int i=0;i< fft_length/2 ;i++){ Envenlope[i] /= MaxFT; FT[i] /= MaxFT; Capstrum[i] /= MaxFT; } delete [] result_buffer; delete [] result_buffer2; delete [] result_buffer3; result_buffer = 0; result_buffer2 = 0; result_buffer3 = 0; } void CECGsp::fft(COMPLEX *x, int m) { static COMPLEX *w; /* used to store the w complex array */ static int mstore = 0; /* stores m for future reference */ static int n = 1; /* length of fft stored for future */ COMPLEX u,temp,tm; COMPLEX *xi,*xip,*xj,*wptr; int i,j,k,l,le,windex; double arg,w_real,w_imag,wrecur_real,wrecur_imag,wtemp_real; if(m != mstore) { /* free previously allocated storage and set new m */ if(mstore != 0) free(w); mstore = m; if(m == 0) return; /* if m=0 then done */ /* n = 2**m = fft length */ n = 1 << m; le = n/2; /* allocate the storage for w */ w = (COMPLEX *) calloc(le-1,sizeof(COMPLEX)); if(!w) { printf("\nUnable to allocate complex W array\n"); exit(1); } /* calculate the w values recursively */ arg = 4.0*atan(1.0)/le; /* PI/le calculation */ wrecur_real = w_real = cos(arg); wrecur_imag = w_imag = -sin(arg); xj = w; for (j = 1 ; j < le ; j++) { xj->real = (float)wrecur_real; xj->imag = (float)wrecur_imag; xj++; wtemp_real = wrecur_real*w_real - wrecur_imag*w_imag; wrecur_imag = wrecur_real*w_imag + wrecur_imag*w_real; wrecur_real = wtemp_real; } } /* start fft */ le = n; windex = 1; for (l = 0 ; l < m ; l++) { le = le/2; /* first iteration with no multiplies */ for(i = 0 ; i < n ; i = i + 2*le) { xi = x + i; xip = xi + le; temp.real = xi->real + xip->real; temp.imag = xi->imag + xip->imag; xip->real = xi->real - xip->real; xip->imag = xi->imag - xip->imag; *xi = temp; } /* remaining iterations use stored w */ wptr = w + windex - 1; for (j = 1 ; j < le ; j++) { u = *wptr; for (i = j ; i < n ; i = i + 2*le) { xi = x + i; xip = xi + le; temp.real = xi->real + xip->real; temp.imag = xi->imag + xip->imag; tm.real = xi->real - xip->real; tm.imag = xi->imag - xip->imag; xip->real = tm.real*u.real - tm.imag*u.imag; xip->imag = tm.real*u.imag + tm.imag*u.real; *xi = temp; } wptr = wptr + windex; } windex = 2*windex; } /* rearrange data by bit reversing */ j = 0; for (i = 1 ; i < (n-1) ; i++) { k = n/2; while(k <= j) { j = j - k; k = k/2; } j = j + k; if (i < j) { xi = x + i; xj = x + j; temp = *xj; *xj = *xi; *xi = temp; } } } void CECGsp::ifft(COMPLEX *x, int m) { static COMPLEX *w; /* used to store the w complex array */ static int mstore = 0; /* stores m for future reference */ static int n = 1; /* length of fft stored for future */ COMPLEX u,temp,tm; COMPLEX *xi,*xip,*xj,*wptr; int i,j,k,l,le,windex; double arg,w_real,w_imag,wrecur_real,wrecur_imag,wtemp_real; if(m != mstore) { /* free previously allocated storage and set new m */ if(mstore != 0) free(w); mstore = m; if(m == 0) return; /* if m=0 then done */ /* n = 2**m = fft length */ n = 1 << m; le = n/2; /* allocate the storage for w */ w = (COMPLEX *) calloc(le-1,sizeof(COMPLEX)); if(!w) { printf("\nUnable to allocate complex W array\n"); exit(1); } /* calculate the w values recursively */ arg = 4.0*atan(1.0)/le; /* PI/le calculation */ wrecur_real = w_real = cos(arg); wrecur_imag = w_imag = sin(arg); xj = w; for (j = 1 ; j < le ; j++) { xj->real = (float)wrecur_real; xj->imag = (float)wrecur_imag; xj++; wtemp_real = wrecur_real*w_real - wrecur_imag*w_imag; wrecur_imag = wrecur_real*w_imag + wrecur_imag*w_real; wrecur_real = wtemp_real; } } /* start fft */ le = n; windex = 1; for (l = 0 ; l < m ; l++) { le = le/2; /* first iteration with no multiplies */ for(i = 0 ; i < n ; i = i + 2*le) { xi = x + i; xip = xi + le; temp.real = xi->real + xip->real; temp.imag = xi->imag + xip->imag; xip->real = xi->real - xip->real; xip->imag = xi->imag - xip->imag; *xi = temp; } /* remaining iterations use stored w */ wptr = w + windex - 1; for (j = 1 ; j < le ; j++) { u = *wptr; for (i = j ; i < n ; i = i + 2*le) { xi = x + i; xip = xi + le; temp.real = xi->real + xip->real; temp.imag = xi->imag + xip->imag; tm.real = xi->real - xip->real; tm.imag = xi->imag - xip->imag; xip->real = tm.real*u.real - tm.imag*u.imag; xip->imag = tm.real*u.imag + tm.imag*u.real; *xi = temp; } wptr = wptr + windex; } windex = 2*windex; } /* rearrange data by bit reversing */ j = 0; for (i = 1 ; i < (n-1) ; i++) { k = n/2; while(k <= j) { j = j - k; k = k/2; } j = j + k; if (i < j) { xi = x + i; xj = x + j; temp = *xj; *xj = *xi; *xi = temp; } } } void CECGsp::fasper( float x[], float y[], unsigned long n, float ofac, float hifac, float wk1[], float wk2[], unsigned long nwk, unsigned long *nout, unsigned long *jmax, float *prob) { unsigned long j, k, ndim, nfreq, nfreqt; float ave, ck, ckk, cterm, cwt, den, df, effm, expy, fac, fndim, hc2wt, hs2wt, hypo, pmax, sterm, swt, var, xdif, xmax, xmin; *nout = 0.5*ofac*hifac*n; nfreqt = ofac*hifac*n*MACC; nfreq = 64; while (nfreq < nfreqt) nfreq <<= 1; ndim = nfreq << 1; if (ndim > nwk) nwk = 0; // error("workspaces too small\n"); avevar(y, n, &ave, &var); xmax = xmin = x[1]; for (j = 2; j <= n; j++) { if (x[j] < xmin) xmin = x[j]; if (x[j] > xmax) xmax = x[j]; } xdif = xmax - xmin; for (j = 1; j <= ndim; j++) wk1[j] = wk2[j] = 0.0; fac = ndim/(xdif*ofac); fndim = ndim; for (j = 1; j <= n; j++) { ck = (x[j] - xmin)*fac; MOD(ck, fndim); ckk = 2.0*(ck++); MOD(ckk, fndim); ++ckk; spread(y[j] - ave, wk1, ndim, ck, MACC); spread(1.0, wk2, ndim, ckk, MACC); } realft(wk1, ndim, 1); realft(wk2, ndim, 1); df = 1.0/(xdif*ofac); pmax = -1.0; for (k = 3, j = 1; j <= (*nout); j++, k += 2) { hypo = sqrt(wk2[k]*wk2[k] + wk2[k+1]*wk2[k+1]); hc2wt = 0.5*wk2[k]/hypo; hs2wt = 0.5*wk2[k+1]/hypo; cwt = sqrt(0.5+hc2wt); swt = SIGN(sqrt(0.5-hc2wt), hs2wt); den = 0.5*n + hc2wt*wk2[k] + hs2wt*wk2[k+1]; cterm = SQR(cwt*wk1[k] + swt*wk1[k+1])/den; sterm = SQR(cwt*wk1[k+1] - swt*wk1[k])/(n - den); wk1[j] = j*df; wk2[j] = (cterm+sterm)/(2.0*var); if (wk2[j] > pmax) pmax = wk2[(*jmax = j)]; } expy = exp(-pmax); effm = 2.0*(*nout)/ofac; *prob = effm*expy; // if (*prob > 0.01) *prob = 1.0 - pow(1.0 - expy, effm); } void CECGsp::spread(float y, float yy[], unsigned long n, float x, int m) { int ihi, ilo, ix, j, nden; static int nfac[11] = { 0, 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }; float fac; if (m > 10) m = 0; //error("factorial table too small"); ix = (int)x; if (x == (float)ix) yy[ix] += y; else { ilo = LMIN(LMAX((long)(x - 0.5*m + 1.0), 1), n - m + 1); ihi = ilo + m - 1; nden = nfac[m]; fac = x - ilo; for (j = ilo + 1; j <= ihi; j++) fac *= (x - j); yy[ihi] += y*fac/(nden*(x - ihi)); for (j = ihi-1; j >= ilo; j--) { nden = (nden/(j + 1 - ilo))*(j - ihi); yy[j] += y*fac/(nden*(x - j)); } } } void CECGsp::avevar(float data[], unsigned long n, float *ave, float *var) { unsigned long j; float s, ep; for (*ave = 0.0, j = 1; j <= n; j++) *ave += data[j]; *ave /= n; *var = ep = 0.0; for (j = 1; j <= n; j++) { s = data[j] - (*ave); ep += s; *var += s*s; } *var = (*var - ep*ep/n)/(n-1); pwr = *var; } void CECGsp::realft(float data[], unsigned long n, int isign) { unsigned long i, i1, i2, i3, i4, np3; float c1 = 0.5, c2, h1r, h1i, h2r, h2i; double wr, wi, wpr, wpi, wtemp, theta; theta = 3.141592653589793/(double)(n>>1); if (isign == 1) { c2 = -0.5; four1(data, n>>1, 1); } else { c2 = 0.5; theta = -theta; } wtemp = sin(0.5*theta); wpr = -2.0*wtemp*wtemp; wpi = sin(theta); wr = 1.0 + wpr; wi = wpi; np3 = n+3; for (i = 2; i <= (n>>2); i++) { i4 = 1 + (i3 = np3 - (i2 = 1 + (i1 = i + i - 1))); h1r = c1*(data[i1] + data[i3]); h1i = c1*(data[i2] - data[i4]); h2r = -c2*(data[i2] + data[i4]); h2i = c2*(data[i1] - data[i3]); data[i1] = h1r + wr*h2r - wi*h2i; data[i2] = h1i + wr*h2i + wi*h2r; data[i3] = h1r - wr*h2r + wi*h2i; data[i4] = -h1i +wr*h2i + wi*h2r; wr = (wtemp = wr)*wpr - wi*wpi + wr; wi = wi*wpr + wtemp*wpi + wi; } if (isign == 1) { data[1] = (h1r = data[1]) + data[2]; data[2] = h1r - data[2]; } else { data[1] = c1*((h1r = data[1]) + data[2]); data[2] = c1*(h1r - data[2]); four1(data, n>>1, -1); } } void CECGsp::four1(float data[],unsigned long nn,int isign) { unsigned long n, mmax, m, j, istep, i; double wtemp, wr, wpr, wpi, wi, theta; float tempr, tempi; n = nn << 1; j = 1; for (i = 1; i < n; i += 2) { if (j > i) { SWAP(data[j], data[i]); SWAP(data[j+1], data[i+1]); } m = n >> 1; while (m >= 2 && j > m) { j -= m; m >>= 1; } j += m; } mmax = 2; while (n > mmax) { istep = mmax << 1; theta = isign*(6.28318530717959/mmax); wtemp = sin(0.5*theta); wpr = -2.0*wtemp*wtemp; wpi = sin(theta); wr = 1.0; wi = 0.0; for (m = 1; m < mmax; m += 2) { for (i = m;i <= n;i += istep) { j = i + mmax; tempr = wr*data[j] - wi*data[j+1]; tempi = wr*data[j+1] + wi*data[j]; data[j] = data[i] - tempr; data[j+1] = data[i+1] - tempi; data[i] += tempr; data[i+1] += tempi; } wr = (wtemp = wr)*wpr - wi*wpi + wr; wi = wi*wpr + wtemp*wpi + wi; } mmax = istep; } } unsigned long CECGsp::HRV(float *y,int length) { unsigned long nout, jmax; float prob; nmax = 1; while(nmax < length) nmax <<= 1; zeromean(length,y); if (x == 0){ x = new float[nmax]; for(int i=0;i<length;i++) x[i]=i; } if (wk1 == 0) wk1 = new float[64*nmax]; if (wk2 == 0) wk2 = new float[64*nmax]; /* Compute the Lomb periodogram. */ fasper(x-1, y-1, length, 4.0, 2.0, wk1-1, wk2-1, 64*nmax, &nout, &jmax, &prob); return nout; } /* Read input data, allocating and filling x[] and y[]. The return value is the number of points read. This function allows the input buffers to grow as large as necessary, up to the available memory (assuming that a long int is large enough to address any memory location). */ /* unsigned long CECGsp::input() { unsigned long npts = 0L; if ((x = (float *)malloc(nmax * sizeof(float))) == NULL || (y = (float *)malloc(nmax * sizeof(float))) == NULL || (wk1 = (float *)malloc(64 * nmax * sizeof(float))) == NULL || (wk2 = (float *)malloc(64 * nmax * sizeof(float))) == NULL) { if (x) (void)free(x); fclose(ifile); error("insufficient memory"); } while (fscanf(ifile, "%f%f", &x[npts], &y[npts]) == 2) { if (++npts >= nmax) { // double the size of the input buffers float *xt, *yt, *w1t, *w2t; unsigned long nmaxt = nmax << 1; if (64 * nmaxt * sizeof(float) < nmax) { fprintf(stderr, "%s: insufficient memory, truncating input at row %d\n", pname, npts); break; } if ((xt = (float *)realloc(x, nmaxt * sizeof(float))) == NULL) { fprintf(stderr, "%s: insufficient memory, truncating input at row %d\n", pname, npts); break; } x = xt; if ((yt = (float *)realloc(y, nmaxt * sizeof(float))) == NULL) { fprintf(stderr, "%s: insufficient memory, truncating input at row %d\n", pname, npts); break; } y = yt; if ((w1t = (float *)realloc(wk1,64*nmaxt*sizeof(float))) == NULL){ fprintf(stderr, "%s: insufficient memory, truncating input at row %d\n", pname, npts); break; } wk1 = w1t; if ((w2t = (float *)realloc(wk2,64*nmaxt*sizeof(float))) == NULL){ fprintf(stderr, "%s: insufficient memory, truncating input at row %d\n", pname, npts); break; } wk2 = w2t; nmax = nmaxt; } } fclose(ifile); if (npts < 1) error("no data read"); return (npts); }*/ /* This function calculates the mean of all sample values and subtracts it from each sample value, so that the mean of the adjusted samples is zero. */ void CECGsp::zeromean(unsigned long n,float *y) { unsigned long i; double ysum = 0.0; for (i = 0; i < n; i++) ysum += y[i]; ysum /= n; for (i = 0; i < n; i++) y[i] -= ysum; } CECGsp::~CECGsp() { if (PeakDect != 0) delete PeakDect; if (Envenlope != 0) delete [] Envenlope; if (FT != 0) delete [] FT; delete [] x; delete [] wk1; delete [] wk2; x = 0; wk1 = 0; wk2 = 0; }
[ "hawk.hsieh@6a298216-7b91-11de-a1b3-85d0aeae5c5b" ]
[ [ [ 1, 690 ] ] ]
5b0bce7f8af4221de3be9438d56d01b1ad93aa96
90e001b00ae30ef22a3b07f6c9c374b0f2a1ee65
/Computer Code/Processor.cpp
a3a343e8c27ced198d4523d8ecca41172675ae63
[]
no_license
yazaddaruvala/2010W_UBC_EECE_375_450_Team6
6ca20eacef048a770e4422b45b49cedac8d6efe9
e87918415ac41c7953f67247d6b9d3ce12f6e95a
refs/heads/master
2016-09-11T04:20:55.171140
2011-05-29T08:32:43
2011-05-29T08:32:43
1,816,632
2
0
null
null
null
null
UTF-8
C++
false
false
2,000
cpp
/* * Written by Yazad Daruvala */ #include "Processor.h" Processor::Processor(void) { SegmentFinder *contourFinder = new SegmentFinder(); data_Mutex.lock(); data = new vector<FieldNode>; data_Mutex.unlock(); } Processor::~Processor(void) { delete [] contourFinder; delete [] data; } void Processor::overlayImage( IplImage * overlayImg, IplImage * overlayMask, const int shiftX, const int shiftY){ data_Mutex.lock(); if(!data->empty()){ for(vector<FieldNode>::iterator dataIterator = data->begin(); dataIterator != data->end(); ++dataIterator){ cvCircle( overlayImg, cvPoint(dataIterator->getxPos() + shiftX, dataIterator->getyPos() + shiftY), dataIterator->getRadius(), color, dataIterator->getRadius()); cvCircle( overlayMask, cvPoint(dataIterator->getxPos() + shiftX, dataIterator->getyPos() + shiftY), dataIterator->getRadius(), CV_RGB(0, 0, 0), 2); } } data_Mutex.unlock(); } void Processor::updateData( vector<FieldNode> * input){ data_Mutex.lock(); if(!data->empty()){ for(vector<FieldNode>::iterator dataIterator = data->begin(); dataIterator != data->end(); ++dataIterator){ FieldNode temp(dataIterator->getxPos(), dataIterator->getyPos(), dataIterator->getRadius()); input->push_back( temp ); } } data_Mutex.unlock(); } vector<FieldNode> *Processor::getData( void ){ return data; } CvScalar Processor::getColor( void ) const{ return color; } IplImage * Processor::arrayToThreshed( vector<IplImage *> *input, CvScalar lowerBound, CvScalar upperBound ){ IplImage * threshed = cvCreateImage(cvGetSize(input->front()), 8, 1); cvZero(threshed); for (vector<IplImage *>::iterator inputIterator = input->begin(); inputIterator != input->end(); ++inputIterator){ IplImage * temp = cvCreateImage(cvGetSize((*inputIterator)), 8, 1); cvInRangeS( (*inputIterator), lowerBound, upperBound, temp ); cvOr(threshed, temp, threshed); cvReleaseImage(&temp); } return threshed; }
[ [ [ 1, 63 ] ] ]
bd2f215488002ab89a9e8483c98358ed450ed032
40920d4672465672653eb2c3c6f0c233a2b09a29
/imgpack/uImagePlaner.h
0b2c3ec0568309b2432e102c3b29283b97f4e691
[]
no_license
Letractively/imgpack
70c6786724b80bedbbe9c52813931fc2f4b8bdba
f0504c829d21f6d20e891f7b5208cb40cb5e1c8f
refs/heads/master
2021-01-10T16:55:16.212558
2011-11-14T20:25:32
2011-11-14T20:25:32
46,196,516
0
0
null
null
null
null
UTF-8
C++
false
false
1,243
h
// ImagePacker by DAS ( [email protected] ) // Rectangle placer. Usage: // 1 - Add() all your rectangles in uImagePacker object. // 2 - Callc() it. // 3 - uImagePacker::callcList contains output data. #ifndef _IMAGE_PLANER_H_ #define _IMAGE_PLANER_H_ #include <vector> class uImagePlaner { public: uImagePlaner() : maxTextureSize(1024), startTextureSize(1) {} void add(int x, int y, const std::string imgName); int getTextureSize(int imgSize); void calc(); class uImageRect { public: int rectMinX; int rectMaxX; int rectMinY; int rectMaxY; int sizeX; int sizeY; std::string name; bool done; uImageRect() : done(false) { rectMinX = rectMaxX = rectMinY = rectMaxY = sizeX = sizeY = 0; } const bool operator < ( const uImageRect& rhs ) const { return sizeY == rhs.sizeY ? sizeX < rhs.sizeX : sizeY < rhs.sizeY; } }; typedef std::vector<uImageRect> uImageRectList; uImageRectList calcList; int outSizeX; int outSizeY; int maxTextureSize; int startTextureSize; private: uImageRectList rectList; int fillRect(int minX, int maxX, int minY, int maxY, uImageRectList::iterator start); bool isDone(); }; #endif // _IMAGE_PLANER_H_
[ [ [ 1, 59 ] ] ]
1b3a56c0d140ece1ba1b1dc63583d88704d012bd
867f5533667cce30d0743d5bea6b0c083c073386
/jingxian-network/src/jingxian/protocol/proxy/NullCredentialPolicy.h
0d34a1913a2e65fbb9d0bd40f4e7b01526f7c7a4
[]
no_license
mei-rune/jingxian-project
32804e0fa82f3f9a38f79e9a99c4645b9256e889
47bc7a2cb51fa0d85279f46207f6d7bea57f9e19
refs/heads/master
2022-08-12T18:43:37.139637
2009-12-11T09:30:04
2009-12-11T09:30:04
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,606
h
#ifndef _NullCredentialPolicy_H_ #define _NullCredentialPolicy_H_ #include "jingxian/config.h" #if !defined (JINGXIAN_LACKS_PRAGMA_ONCE) # pragma once #endif /* JINGXIAN_LACKS_PRAGMA_ONCE */ // Include files # include "jingxian/protocol/proxy/AbstractCredentialPolicy.h" _jingxian_begin namespace proxy { class NullCredentialPolicy : public AbstractCredentialPolicy { public: NullCredentialPolicy(ProxyProtocolFactory* server, const config::Credential& credential) : AbstractCredentialPolicy(server, credential) { _complete = true; } virtual ~NullCredentialPolicy() { } virtual size_t onReceived(ProtocolContext& context, InBuffer& inBuffer) { _complete = true; return 0; } }; class NullCredentialPolicyFactory : public ICredentialPolicyFactory { public: NullCredentialPolicyFactory(ProxyProtocolFactory* server) : server_(server) { credential_.AuthenticationType = AuthenticationType::NONE; credential_.Name = _T("NullCredentialPolicy"); credential_.Description = _T("ÎÞÐèÈÏÖ¤!"); } virtual ~NullCredentialPolicyFactory() { } virtual int authenticationType() const { return credential_.AuthenticationType; } virtual ICredentialPolicy* make() { return new NullCredentialPolicy(server_, credential_); } private: config::Credential credential_; ProxyProtocolFactory* server_; }; } _jingxian_end #endif // _NullCredentialPolicy_H_
[ "runner.mei@0dd8077a-353d-11de-b438-597f59cd7555" ]
[ [ [ 1, 73 ] ] ]
805175c3420a13689ab0292694cd4a0bc76b3732
a7d7cc7bde550cc6ad6b387d25dafcb1007723f2
/FftwConvolver/FftwConvolver/FftwConvolver.cpp
047882cedc2a7b006a345cdd08e7e48a15291e08
[]
no_license
JoostZ/astro-deconvolution
be780879352fa279e2141f7813f28e91b0fa8b61
9ae150ae9c37f48637af519c9beef910a26f8c51
refs/heads/master
2021-01-25T07:08:16.999105
2010-03-31T19:13:45
2010-03-31T19:13:45
41,419,138
1
0
null
null
null
null
UTF-8
C++
false
false
4,876
cpp
// This is the main DLL file. #include "stdafx.h" #include <string.h> #include "FftwConvolver.h" namespace FftwConvolver { FftwConvolver::FftwConvolver(Size size, array<double,2>^ psf, Point origin) { Init(size, psf, origin); } FftwConvolver::FftwConvolver(Size size, KernelData^ data) { Init(size, data->Data, data->Origin); } void FftwConvolver::Init(Size size, array<double,2>^ psf, Point origin) { // Allocate buffers for the (real) input image and the complex of FFT int bufferSize = size.Width * size.Height; m_in = (double *)fftw_malloc(sizeof(double) * bufferSize); m_out = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * bufferSize); // Create a plan for the forward FFT ... m_planForward = fftw_plan_dft_r2c_2d(size.Width, size.Height, m_in, m_out, FFTW_MEASURE); // ... and the backward FFT m_planBackward = fftw_plan_dft_c2r_2d(size.Width, size.Height, m_out, m_in, FFTW_MEASURE); m_psfFft = TransformPsf(size, psf, origin); m_psfTransposeFft = TransformPsfTransposed(size, psf, origin); } array<double,2>^ FftwConvolver::Convolve(array<double,2>^ image) { double *p = m_in; for (int y = 0; y < image->GetLength(1); y++) { for(int x = 0; x < image->GetLength(0); x++) { *p++ = image[x, y]; } } fftw_complex* fft = DoConvolve(m_in, image->Length); for (int i = 0; i < image->Length; i++) { m_out[i][0] = fft[i][0] * m_psfFft[i][0] - fft[i][1] * m_psfFft[i][1]; m_out[i][1] = fft[i][0] * m_psfFft[i][1] + fft[i][1] * m_psfFft[i][0]; } fftw_execute_dft_c2r(m_planBackward, m_out, m_in); array<double,2>^ result = gcnew array<double,2>(image->GetLength(0), image->GetLength(1)); double scale = 1.0 / (image->GetLength(0) * image->GetLength(1)); p = m_in; for (int y = 0; y < image->GetLength(1); y++) { for (int x = 0; x < image->GetLength(0); x++) { result[x,y] = *p++ * scale; } } return result; } fftw_complex* FftwConvolver::TransformPsf(Size size, array<double,2>^ psf, Point origin) { double* inBuffer = 0; fftw_complex* outBuffer = 0; int bufferLength = size.Height * size.Width * sizeof(double); try { array<double,2>^ image = gcnew array<double,2>(size.Width, size.Height); inBuffer = (double *)fftw_malloc(bufferLength); memset(inBuffer, 0, bufferLength); int width = psf->GetLength(0); int height = psf->GetLength(1); int idx = 0; int y; for (y = 0; y < height; y++) { int scanLine = (y - origin.Y); int yOffset = 0; if (scanLine < 0) { scanLine += size.Height; } yOffset = scanLine * size.Width; int x; int xOffset = yOffset + size.Width - origin.X; for (x = 0; x < origin.X; x++) { idx = xOffset + x; inBuffer[idx] = psf[x, y]; } for (; x <width; x++) { idx = yOffset + x - origin.X; inBuffer[idx] = psf[x, y]; } } outBuffer = DoConvolve(inBuffer, bufferLength); } catch (Exception^) { fftw_free(inBuffer); fftw_free(outBuffer); throw; } fftw_free(inBuffer); return outBuffer; } fftw_complex* FftwConvolver::TransformPsfTransposed(Size size, array<double,2>^ psf, Point origin) { Point theOrigin; theOrigin.X = origin.Y; theOrigin.Y = origin.X; array<double, 2>^ thePsf = gcnew array<double, 2>(theOrigin.X, theOrigin.Y); for (int x = 0; x < theOrigin.X; x++) { for (int y = 0; y < theOrigin.Y; y++) { thePsf[x, y] = psf[y, x]; } } return TransformPsf(size, thePsf, theOrigin); } fftw_complex* FftwConvolver::DoConvolve(double* in, int bufferSize) { fftw_complex* buffer = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * bufferSize); return DoConvolve(in, buffer); } fftw_complex* FftwConvolver::DoConvolve(double* in, fftw_complex* out) { fftw_execute_dft_r2c(m_planForward, in, out); return out; } }
[ [ [ 1, 155 ] ] ]
5ec820a2dd4ba0fc6310f7a57438b96b2f352c84
ee065463a247fda9a1927e978143186204fefa23
/Src/Engine/Events/EngineEventManager.h
a6590d79ac5a29e49b6a1a6253cf6598bebfbdbd
[]
no_license
ptrefall/hinsimviz
32e9a679170eda9e552d69db6578369a3065f863
9caaacd39bf04bbe13ee1288d8578ece7949518f
refs/heads/master
2021-01-22T09:03:52.503587
2010-09-26T17:29:20
2010-09-26T17:29:20
32,448,374
1
0
null
null
null
null
UTF-8
C++
false
false
402
h
#pragma once #include "IEngineEventManager.h" #include <map> namespace Engine { namespace Events { class EngineEventManager : public IEngineEventManager { public: virtual int init() { return 0; } virtual CallbackClass &GetEvent(const CL_String &name); virtual void SendEvent(const EngineEvent &event); private: std::map<CL_String, CallbackClass> eventHandlers; }; } }
[ "[email protected]@28a56cb3-1e7c-bc60-7718-65c159e1d2df" ]
[ [ [ 1, 24 ] ] ]
1ff3f80ade21c141e706fbbc4ad963e12c00776c
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/renaissance/rnsgameplay/src/ncspawnpoint/ncspawnpoint.cc
1a69ff8ec77d6d14386e9b578b3cc9ce9f576d1b
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,533
cc
//------------------------------------------------------------------------------ // ncspawnpoint.cc // (C) 2005 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "precompiled/pchrnsgameplay.h" #include "ncspawnpoint/ncspawnpoint.h" #include "zombieentity/nctransform.h" #include "nworldinterface/nworldinterface.h" #include "ncfsm/ncfsm.h" #ifndef NGAME #include "nspatial/ncspatial.h" #endif //------------------------------------------------------------------------------ nNebulaComponentObject(ncSpawnPoint,nComponentObject); //------------------------------------------------------------------------------ /** Constructor */ ncSpawnPoint::ncSpawnPoint() : transform(0) { // empty } //------------------------------------------------------------------------------ /** Destructor */ ncSpawnPoint::~ncSpawnPoint() { // empty } //------------------------------------------------------------------------------ /** InitInstance */ void ncSpawnPoint::InitInstance(nObject::InitInstanceMsg /*initType*/) { n_assert(this->entityObject); if ( this->entityObject ) { this->transform = this->entityObject->GetComponent <ncTransform>(); } #ifndef NGAME ncSpatial* spatial = this->GetComponent<ncSpatial>(); if ( spatial ) { spatial->SetOriginalBBox( 0,0,0, 0.5f,0.5f,0.5f ); } #endif } //------------------------------------------------------------------------------ /** SpawnEntity */ nEntityObject* ncSpawnPoint::SpawnEntity (const nString& entityName) { nEntityObject* entity( this->SpawnEntityFrozen( entityName ) ); if ( entity ) { // If entity is an agent, make it begin running its behavior ncFSM* fsm = entity->GetComponent<ncFSM>(); if ( fsm ) { fsm->Init(); } } return entity; } //------------------------------------------------------------------------------ /** SpawnEntityFrozen */ nEntityObject* ncSpawnPoint::SpawnEntityFrozen (const nString& entityName) { nWorldInterface* world = nWorldInterface::Instance(); n_assert( world ); nEntityObject* entity = 0; // Well, this spawn point is able to create this kind of entity if ( world ) { // Now, we must place the entity in the right position, // if wasn't able to allocate in a position, we don't create it vector3 spawnPos; if ( this->CalcSpawnPosition( spawnPos ) ) { entity = world->NewServerEntity (entityName.Get(), spawnPos, NULL); } } return entity; } //------------------------------------------------------------------------------ /** CalcSpawnPosition @return the position where the next entity is going to be spawned */ bool ncSpawnPoint::CalcSpawnPosition (vector3& spawnPoint) const { n_assert(this->transform); bool able = false; if ( this->transform ) { // The following commented block of code has been kept because we // still don't know which was its purpose /* vector3 position = this->transform->GetPosition(); quaternion orientation = this->transform->GetQuat(); matrix44 transform(orientation); position += vector3 (0.f, 0.f, 5.f); transform.mult (position, spawnPoint);*/ spawnPoint = this->transform->GetPosition(); able = true; } return able; } //------------------------------------------------------------------------------ /** PlaceEntity @returns if was able to allocate the entity */ bool ncSpawnPoint::PlaceEntity (nEntityObject* agent) { n_assert(agent); n_assert(this->transform); bool able = false; if ( agent && this->transform ) { vector3 position = this->transform->GetPosition(); quaternion orientation = this->transform->GetQuat(); matrix44 transform(orientation); vector3 spawnPoint; position += vector3 (0.f, 0.f, 5.f); transform.mult (position, spawnPoint); // Temporal solution, it always puts the agent at the selected position ncTransform* agentTransform = agent->GetComponent <ncTransform>(); n_assert(agentTransform); if ( agentTransform ) { agentTransform->SetPosition (spawnPoint); able = true; } } return able; } //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 177 ] ] ]
fd39f998698eed58b1522b56bdffbbf4fb4b1b00
444a151706abb7bbc8abeb1f2194a768ed03f171
/trunk/ENIGMAsystem/SHELL/Universal_System/zlib.cpp
a41ca2bda2043e28794ba5872ebd3d07814335d5
[]
no_license
amorri40/Enigma-Game-Maker
9d01f70ab8de42f7c80af9a0f8c7a66e412d19d6
c6b701201b6037f2eb57c6938c184a5d4ba917cf
refs/heads/master
2021-01-15T11:48:39.834788
2011-11-22T04:09:28
2011-11-22T04:09:28
1,855,342
1
1
null
null
null
null
UTF-8
C++
false
false
2,144
cpp
/** Copyright (C) 2008-2011 Josh Ventura *** *** This file is a part of the ENIGMA Development Environment. *** *** ENIGMA 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, version 3 of the license or any later version. *** *** This application and its source code is distributed AS-IS, 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 code. If not, see <http://www.gnu.org/licenses/> **/ #include <string> #include "../../additional/zlib/zlib.h" #include "../Widget_Systems/widgets_mandatory.h" #include "zlib.h" int zlib_compressed_size=0; int zlib_decompressed_size=0; unsigned char* zlib_compress(unsigned char* inbuffer,int actualsize) { uLongf outsize=(int)(actualsize*1.1)+12; Bytef* outbytef=new Bytef[outsize]; int res=compress(outbytef,&outsize,(Bytef*)inbuffer,actualsize); if (res != Z_OK) { #if SHOWERRORS if (res==Z_MEM_ERROR) show_error("Zlib failed to compress the buffer. Out of memory.",0); if (res==Z_BUF_ERROR) show_error("Zlib failed to compress the buffer. Output size greater than allotted.",0); #endif } zlib_compressed_size=outsize; return (unsigned char*)outbytef; } int zlib_decompress(unsigned char* inbuffer, int insize, int uncompresssize,unsigned char* outbytef) { uLongf outused=uncompresssize; switch(uncompress(outbytef,&outused,(Bytef*)inbuffer,insize)){ case Z_OK:return outused; case Z_MEM_ERROR: #if SHOWERRORS show_error("Zerror: Memory out",0); #endif return -1; case Z_BUF_ERROR: #if SHOWERRORS show_error("Zerror: Output of "+string(outused)+" above alloted "+string(uncompresssize),0); #endif return -2; case Z_DATA_ERROR: #if SHOWERRORS show_error("Zerror: Invalid data",0); #endif return -3; default:return -4; } }
[ [ [ 1, 69 ] ] ]
16cc3bfa211037eb3d8e73c2b34bfffc7904ef55
4a2b2d6d07714e82ecf94397ea6227edbd7893ad
/Curl/CurlTest/JpegFileListener.h
6c2976239590e99d9b600fc0096e5b52a528f94f
[]
no_license
intere/tmee
8b0a6dd4651987a580e3194377cfb999e9615758
327fed841df6351dc302071614a9600e2fa67f5f
refs/heads/master
2021-01-25T07:28:47.788280
2011-07-21T04:24:31
2011-07-21T04:24:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
318
h
#pragma once #include "Listener.h" #include "MJpegEvent.h" class JpegFileListener : public Listener<MJpegEvent*> /*: public Listener<MJpegEvent*>*/ { public: JpegFileListener(void); virtual ~JpegFileListener(void); /** Inherited from Listener: */ virtual eventOccurred(MJpegEvent *event); };
[ "intere@8c6822e2-464b-4b1f-8ae9-3c1f0a8e8225" ]
[ [ [ 1, 16 ] ] ]
1d565439b6fea95a58d68fe46d398771f9b1e76c
4497c10f3b01b7ff259f3eb45d0c094c81337db6
/VideoMontage/VideoSequence.cpp
2ebe3702182221bf20eb339c1d1b16bb1c30f1fb
[]
no_license
liuguoyou/retarget-toolkit
ebda70ad13ab03a003b52bddce0313f0feb4b0d6
d2d94653b66ea3d4fa4861e1bd8313b93cf4877a
refs/heads/master
2020-12-28T21:39:38.350998
2010-12-23T16:16:59
2010-12-23T16:16:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,312
cpp
#include "stdafx.h" #include "VideoSequence.h" // Testing void TestCreateSequence() { VideoSequence sequence; vector<char*> frameList(2); frameList[0] = "Ha ha ha ha"; frameList[1] = "Ha ha ha ha 2"; sequence.frameList = &frameList; } void TestLoadSaveSequence() { VideoSequence sequence; vector<char*> frameList(2); frameList[0] = "Ha ha ha ha"; frameList[1] = "Ha ha ha ha 2"; sequence.frameList = &frameList; SaveVideoSequenceToFile(&sequence, "test.tst"); VideoSequence* sequ = LoadSequenceFromFile("test.tst"); sequ->frameList = 0; } // Load a frame from memory IplImage* LoadFrame(VideoSequence* videoSequence, int frame_number) { char* filename = (*videoSequence->frameList)[frame_number]; return cvLoadImage(filename); } void SaveVideoSequenceToFile(VideoSequence* sequence, char* fileName) { ofstream out(fileName, ios::binary); int count = sequence->frameList->size(); out.write((char*)&count, sizeof(int)); for(int i = 0; i < count; i++) { char* name = (*(sequence->frameList))[i]; int length = strlen(name); out.write((char*)&length, sizeof(int)); out.write(name, sizeof(char) * length); } out.close(); } VideoSequence* LoadSequenceFromFile(char* filename) { ifstream in(filename, ios::binary); VideoSequence* sequence = new VideoSequence(); int count; in.read((char*)&count, sizeof(int)); vector<char*>* frameList = new vector<char*>(count); for(int i = 0; i < count; i++) { int length; in.read((char*)&length, sizeof(int)); char* name = (char*) malloc(length * sizeof(char)); // malloc will allocate more than necessary sometime name[length] = '\0'; in.read(name, sizeof(char) * length); (*frameList)[i] = name; //strncpy((*frameList)[i], name, length); } sequence->frameList = frameList; return sequence; } ShotInfo* LoadShotFromFile(char* fileName) { ifstream in(fileName, ios::binary); ShotInfo* shotInfo = new ShotInfo(); in.read((char*)&(shotInfo->shotCount), sizeof(int)); int shotCount = shotInfo->shotCount; int test = sizeof(long); test = sizeof(Shot); shotInfo->shotList = (Shot*)malloc(shotCount * sizeof(Shot)); Shot* shot = shotInfo->shotList; for(int i = 0; i < shotCount; i++) { in.read((char*)&(shot->subShotCount), sizeof(int)); int subShotCount = shot->subShotCount; shot->subShotList = (SubShot*) malloc(subShotCount * sizeof(SubShot)); SubShot* subShot = shot->subShotList; for(int j = 0; j < subShotCount; j++) { // writing each subShot in.read((char*)&(subShot->shotType), sizeof(int)); in.read((char*)&(subShot->start), sizeof(int)); in.read((char*)&(subShot->end), sizeof(int)); subShot++; } shot++; } return shotInfo; } void SaveShotToFile(ShotInfo* shotInfo, char* fileName) { ofstream out(fileName, ios::binary); int shotCount = shotInfo->shotCount; // number of shot out.write((char*)&shotCount, sizeof(int)); Shot* shot = shotInfo->shotList; for(int i = 0; i < shotCount; i++) { int subShotCount = shot->subShotCount; // number of subShot out.write((char*)&subShotCount, sizeof(int)); SubShot* subShot = shot->subShotList; for(int j = 0; j < subShotCount; j++) { // writing each subShot out.write((char*)&(subShot->shotType), sizeof(int)); out.write((char*)&(subShot->start), sizeof(int)); out.write((char*)&(subShot->end), sizeof(int)); subShot++; } shot++; } out.close(); } void TestSaveLoadShot() { ShotInfo* shotInfo = new ShotInfo(); SubShot subShot[10]; for(int i = 0; i < 10; i++) { subShot[i].end = 20; subShot[i].start = 1; subShot[i].shotType = VCSHOT_PAN; } Shot shot[10]; for(int i = 0; i < 10; i++) { shot[i].subShotCount = 10; shot[i].subShotList = subShot; } shotInfo->shotList = shot; shotInfo->shotCount = 10; SaveShotToFile(shotInfo, "test.txt"); ShotInfo* shotInfo2 = LoadShotFromFile("test.txt"); Shot* shot2 = shotInfo2->shotList; for(int i = 0; i < shotInfo2->shotCount; i++) { SubShot* subShot2 = shot2->subShotList; for(int j = 0; j < shot2->subShotCount; j++) { int end = subShot2->end; subShot2++; } shot2++; } }
[ "kidphys@aeedd7dc-6096-11de-8dc1-e798e446b60a" ]
[ [ [ 1, 177 ] ] ]
932cfb369a99aded76500c7387654daeecbda0ca
c2c93fc3fd90bd77764ac3016d816a59b2370891
/Plugins/AntiSleep 0.1/source/main.cpp
846bd35df977a1d4f3ed53519b17d98e3ea2839e
[]
no_license
MsEmiNeko/samp-alex009-projects
a1d880ee3116de95c189ef3f79ce43b163b91603
9b9517486b28411c8b747fae460266a88d462e51
refs/heads/master
2021-01-10T16:22:34.863725
2011-04-30T04:01:15
2011-04-30T04:01:15
43,719,520
0
1
null
2018-01-19T16:55:45
2015-10-05T23:23:37
SourcePawn
UTF-8
C++
false
false
2,011
cpp
/* * Created: 06.03.10 * Author: 009 * Last Modifed: - */ // SDK #include "SDK/amx/amx.h" #include "SDK/plugincommon.h" // core #include "math.h" #include <stdio.h> // plugin #include "main.h" #include "natives.h" #include "config.h" #include "os.h" AMX* gAMX; int LastUpdate = -1; int max_sleep_time; int action; char creation_file[MAX_CREATION_FILE_LEN]; typedef void (*logprintf_t)(char* format, ...); logprintf_t logprintf; void **ppPluginData; extern void *pAMXFunctions; THREAD_IDENTIFY(AntiSleepThreadHandle); THREAD_START(AntiSleepThread){ while(true) { SLEEP(10); if(LastUpdate == -1) continue; if((GetTickCount() - LastUpdate) > max_sleep_time) { switch(action) { case ACTION_KILL_PROCESS: { exit(1); break; } case ACTION_CREATE_FILE: { FILE* f = fopen(creation_file,"w"); fclose(f); LastUpdate = -1; break; } } } } THREAD_END PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load( void **ppData ) { pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS]; logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; logprintf("================"); logprintf("AntiSleep v " PLUGIN_VERSION); logprintf("by 009"); logprintf("http://samp.club42.ru"); logprintf("================"); // config ReadConfig(); // thread THREAD_RESULT(ThreadId); CREATE_THREAD(AntiSleepThreadHandle,AntiSleepThread,ThreadId); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload( ) { logprintf("================"); logprintf("Useful functions v " PLUGIN_VERSION); logprintf("by 009"); logprintf("http://samp.club42.ru"); logprintf("================"); } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad( AMX *amx ) { gAMX = amx; NativesOnAMXLoad(amx); return 1; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload( AMX *amx ) { return AMX_ERR_NONE; }
[ [ [ 1, 102 ] ] ]
abcf9a9adc432a12f2b18d49b314f715a14271fe
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/locationsrv/landmarks_api/src/testcposlandmarkdatabase.cpp
e94f53cd218626c62e9753b7104b7afb96c47985
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
37,360
cpp
/* * Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ // INCLUDE FILES #include <EPos_CPosLandmark.h> #include <EPos_CPosLandmarkDatabase.h> #include <EPos_CPosLmCategoryManager.h> #include <EPos_CPosLandmarkCategory.h> #include <EPos_CPosLandmarkEncoder.h> #include <EPos_CPosLandmarkParser.h> #include <LbsPosition.h> #include <EPos_CPosLmDatabaseManager.h> #include "testcposlandmarkdatabase.h" #include <StifParser.h> #include <Stiftestinterface.h> // Literals _LIT8( KPosMimeTypeLandmarkCollectionXml, "application/vnd.nokia.landmarkcollection+xml" ); _LIT( KDBUri, "file://c:eposlmtest.ldb" ); // ============================ MEMBER FUNCTIONS =============================== // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::CTestPosLandmarkDatabase // C++ default constructor can NOT contain any code, that // might leave. // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::CTestPosLandmarkDatabase( CStifLogger* aLog ) : CActive(EPriorityStandard), iLog(aLog) { CActiveScheduler::Add(this); } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::NewL // // // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase* CTestPosLandmarkDatabase::NewL(CStifLogger* aLog) { CTestPosLandmarkDatabase* self = new (ELeave) CTestPosLandmarkDatabase( aLog ); CleanupStack::PushL( self ); self->ConstructL(); CleanupStack::Pop(); return self; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::ConstructL // // // ----------------------------------------------------------------------------- // void CTestPosLandmarkDatabase::ConstructL() { } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::~CTestPosLandmarkDatabase // // // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::~CTestPosLandmarkDatabase() { Cancel(); } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::OpenDefaultDatabase // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::OpenDefaultDatabaseL( CStifItemParser& /*aItem*/ ) { // Open default database CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL(); delete lmkDatabase; ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::OpenDatabase // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::OpenDatabaseL( CStifItemParser& aItem ) { TPtrC uriPtr; TInt err = aItem.GetNextString( uriPtr ); // Open database CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); delete lmkDatabase; ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::IsInitializingNeeded // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::IsInitializingNeededL( CStifItemParser& /*aItem*/ ) { // Open default database CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL(KDBUri); CleanupStack::PushL( lmkDatabase ); // Check if init required TBool result = lmkDatabase->IsInitializingNeeded(); if( result ) { // Initializing needed iLog->Log(_L("IsInitializingNeeded successful, initialization needed")); CleanupStack::PopAndDestroy( lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } else { // Initializing not needed iLog->Log(_L("IsInitializingNeeded successful, initialization not needed")); CleanupStack::PopAndDestroy( lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::Initialize // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::InitializeL( CStifItemParser& /*aItem*/ ) { // Open default database CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL(KDBUri); CleanupStack::PushL( lmkDatabase ); // Init CPosLmOperation* initOperation = lmkDatabase->InitializeL(); CleanupStack::PushL( initOperation ); // Perform initialization initOperation->ExecuteL(); iLog->Log(_L("Initialize successful")); CleanupStack::PopAndDestroy( 2, lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::GetDatabaseUri // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::GetDatabaseUriL( CStifItemParser& /*aItem*/ ) { // Open default database CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Init ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Get URI HBufC* uri = lmkDatabase->DatabaseUriLC(); // Print URI iLog->Log(uri->Des()); iLog->Log(_L("GetDatabaseUri successful")); CleanupStack::PopAndDestroy( 2, lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::GetDatabaseSize // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::GetDatabaseSizeL( CStifItemParser& /*aItem*/ ) { // Open default database CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Init ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Get Size CPosLandmarkDatabase::TSize size; size = lmkDatabase->SizeL(); // Print size _LIT( KSize, "Size = " ); TBuf<25> sizebuf(KSize); sizebuf.AppendNum(size.iFileSize); iLog->Log(sizebuf); // Size retrieved iLog->Log(_L("GetDatabaseSize successful")); CleanupStack::PopAndDestroy( lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::LandmarkIterator // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::LandmarkIteratorL( CStifItemParser& /*aItem*/ ) { // Open default database CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Init ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Get Landmark Iterator CPosLmItemIterator* iterator = lmkDatabase->LandmarkIteratorL(); CleanupStack::PushL( iterator ); // print number of lmks TInt numOfLmks = iterator->NumOfItemsL(); _LIT( KTotal, "Total = " ); TBuf<20> buffer; buffer.Copy(KTotal); buffer.AppendNum(numOfLmks); iLog->Log(buffer); iLog->Log(_L("LandmarkIterator successful")); CleanupStack::PopAndDestroy( 2, lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::LmkIteratorSortPref // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::LmkIteratorSortPrefL( CStifItemParser& /*aItem*/ ) { // Open default database CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Init ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Create sort preference TPosLmSortPref sortPref( CPosLandmark::ELandmarkName ); // Get Landmark Iterator with sort preference CPosLmItemIterator* iterator = lmkDatabase->LandmarkIteratorL( sortPref ); CleanupStack::PushL( iterator ); // LandmarkIterator successful iLog->Log(_L("LmkIteratorSortPref successful")); CleanupStack::PopAndDestroy( 2, lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::ReadLandmark // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::ReadLandmarkL( CStifItemParser& /*aItem*/ ) { // Open default database CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Init ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Get Landmark Iterator CPosLmItemIterator* iterator = lmkDatabase->LandmarkIteratorL(); CleanupStack::PushL( iterator ); // Call NextL to get id of next landmark in database TPosLmItemId id = iterator->NextL(); if( KPosLmNullItemId == id ) { iLog->Log(_L("ReadLandmark fails, no landmark in database")); User::Leave( KErrGeneral ); } // Read landmark CPosLandmark* landmark = lmkDatabase->ReadLandmarkLC( id ); // ReadLandmark successful iLog->Log(_L("ReadLandmark successful")); CleanupStack::PopAndDestroy( 3, lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::AddAndRemoveLandmark // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::AddAndRemoveLandmarkL( CStifItemParser& aItem ) { TPtrC lmkNamePtr; TInt err = aItem.GetNextString( lmkNamePtr ); // Open default database CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Init ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Create a new landmark CPosLandmark* landmark = CPosLandmark::NewL(); CleanupStack::PushL( landmark ); // Set name landmark->SetLandmarkNameL( lmkNamePtr ); // Add to database TPosLmItemId lmkId = lmkDatabase->AddLandmarkL( *landmark ); // Check if added lmkId = landmark->LandmarkId(); // Should return valid id of landmark if( KPosLmNullItemId == lmkId ) { iLog->Log(_L("Error in adding landmark to database, AddAndRemoveLandmark failed")); User::Leave( KErrGeneral ); } // Remove from database lmkDatabase->RemoveLandmarkL( lmkId ); // Success iLog->Log(_L("AddAndRemoveLandmark successful")); CleanupStack::PopAndDestroy( 2, lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::UpdateLandmark // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::UpdateLandmarkL( CStifItemParser& aItem ) { TPtrC lmkNamePtr; TInt err = aItem.GetNextString( lmkNamePtr ); // Open default database CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Init ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Read a landmark // Get a valid id CPosLmItemIterator* iter = lmkDatabase->LandmarkIteratorL(); CleanupStack::PushL( iter ); TPosLmItemId id = iter->NextL(); if( KPosLmNullItemId == id ) { iLog->Log(_L("No landmark found in database")); User::Leave( KErrNotFound ); } CPosLandmark* landmark = lmkDatabase->ReadLandmarkLC( id ); // Save original name TPtrC originalName; landmark->GetLandmarkName( originalName ); // Change name of landmark landmark->SetLandmarkNameL( lmkNamePtr ); // Update landmark in DB lmkDatabase->UpdateLandmarkL( *landmark ); // Reset the original name landmark->SetLandmarkNameL( originalName ); // Update landmark in DB lmkDatabase->UpdateLandmarkL( *landmark ); iLog->Log(_L("UpdateLandmark successful")); CleanupStack::PopAndDestroy( 3, lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::RemoveLandmarks // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::RemoveLandmarksL( CStifItemParser& /*aItem*/ ) { // Open Database CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Initialize database ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Add 3 test landmarks, which will be removed by RemoveLandmarksL() TPosLmItemId id; RArray<TPosLmItemId> idArray; CPosLandmark* landmark = CPosLandmark::NewL(); CleanupStack::PushL( landmark ); _LIT( KName, "A Test Landmark " ); TBuf<25> nameBuffer; for(TInt i=1;i<4;i++) { nameBuffer.Copy( KName ); nameBuffer.AppendNum( i ); landmark->SetLandmarkNameL( nameBuffer ); id = lmkDatabase->AddLandmarkL( *landmark ); idArray.AppendL( id ); } // Create iterator and get number of landmarks CPosLmItemIterator* iterator = lmkDatabase->LandmarkIteratorL(); CleanupStack::PushL( iterator ); TInt totalLmkBeforeRemove = iterator->NumOfItemsL(); nameBuffer.Copy( KName ); nameBuffer.AppendNum( totalLmkBeforeRemove ); iLog->Log(nameBuffer); CleanupStack::PopAndDestroy( iterator ); // Remove landmarks (3 landmarks) ExecuteAndDeleteLD( lmkDatabase->RemoveLandmarksL( idArray ) ); // Get number of landmarks after remove iterator = lmkDatabase->LandmarkIteratorL(); CleanupStack::PushL( iterator ); TInt totalLmkAfterRemove = iterator->NumOfItemsL(); nameBuffer.Copy( KName ); nameBuffer.AppendNum( totalLmkAfterRemove ); iLog->Log(nameBuffer); // Check if( totalLmkAfterRemove != (totalLmkBeforeRemove - 3) ) { iLog->Log(_L("RemoveLandmarks fails")); User::Leave( KErrGeneral ); } iLog->Log(_L("RemoveLandmarks succeeds")); CleanupStack::PopAndDestroy( 3, lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::RemoveAllLandmarks // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::RemoveAllLandmarksL( CStifItemParser& /*aItem*/ ) { // Open database CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Initialize database ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Save // Remova All landmarks from database ExecuteAndDeleteLD( lmkDatabase->RemoveAllLandmarksL() ); // Restore iLog->Log(_L("RemoveAllLandmarks successful")); CleanupStack::PopAndDestroy( lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::Compact // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::CompactL( CStifItemParser& /*aItem*/ ) { // Open database CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Initialize database ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Compact DB CPosLmOperation* operation = lmkDatabase->CompactL(); CleanupStack::PushL( operation ); operation->ExecuteL(); iLog->Log(_L("Compact successful")); CleanupStack::PopAndDestroy( 2, lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::SetAndGetPartialReadParams // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::SetAndGetPartialReadParamsL( CStifItemParser& /*aItem*/ ) { // Open and initialize DB CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Initialize database ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Partial read params CPosLmPartialReadParameters* setReadParams = CPosLmPartialReadParameters::NewLC(); // Set 2 attributes, position and coverage radius setReadParams->SetRequestedAttributes( CPosLandmark::EPosition | CPosLandmark::ECoverageRadius ); // Set partial read params lmkDatabase->SetPartialReadParametersL( *setReadParams ); // Read a landmark, and check for name, name should not be found CPosLmItemIterator* iterator = lmkDatabase->LandmarkIteratorL(); CleanupStack::PushL( iterator ); TPosLmItemId id = iterator->NextL(); CPosLandmark* landmark = lmkDatabase->ReadPartialLandmarkLC( id ); TInt error = KErrNone; TPtrC namePtr; // Check for name, should return KErrNotFound error = landmark->GetLandmarkName( namePtr ); if( KErrNotFound != error ) { iLog->Log(_L("SetAndGetPartialReadParams fails")); User::Leave( KErrGeneral ); } // Get partial read params CPosLmPartialReadParameters* getReadParams = lmkDatabase->PartialReadParametersLC(); // Get attributes CPosLandmark::TAttributes attributes = getReadParams->RequestedAttributes(); // Check // EPosition, should exist if( !( attributes & CPosLandmark::EPosition ) ) { iLog->Log(_L("SetAndGetPartialReadParams fails, position not found")); User::Leave( KErrGeneral ); } // ECoverageRadius, should exist if( !( attributes & CPosLandmark::ECoverageRadius ) ) { iLog->Log(_L("SetAndGetPartialReadParams fails, coverage radius not found")); User::Leave( KErrGeneral ); } // EName, should not exist if( attributes & CPosLandmark::ELandmarkName ) { iLog->Log(_L("SetAndGetPartialReadParams fails")); User::Leave( KErrGeneral ); } iLog->Log(_L("SetAndGetPartialReadParams succeeds")); CleanupStack::PopAndDestroy( 5, lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::ReadPartialLandmark // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::ReadPartialLandmarkL( CStifItemParser& /*aItem*/ ) { // Open database CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Initialize database ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Partial read params CPosLmPartialReadParameters* setReadParams = CPosLmPartialReadParameters::NewLC(); // Set 2 attributes, position and name setReadParams->SetRequestedAttributes( CPosLandmark::EPosition | CPosLandmark::ELandmarkName ); // Set partial read params lmkDatabase->SetPartialReadParametersL( *setReadParams ); // Read a landmark using iterator CPosLmItemIterator* iterator = lmkDatabase->LandmarkIteratorL(); CleanupStack::PushL( iterator ); TPosLmItemId id = iterator->NextL(); if( KPosLmNullItemId == id ) { iLog->Log(_L("No landmark exists in database, ReadPartialLandmark fails")); User::Leave( KErrGeneral ); } // This landmark should only have Position and Name, no other attributes should be present CPosLandmark* landmark = lmkDatabase->ReadPartialLandmarkLC( id ); TInt error = KErrNone; TPtrC namePtr; // Check if landmark is partial if( !landmark->IsPartial() ) { iLog->Log(_L("ReadPartialLandmark fails, landmark is not partial")); User::Leave( KErrGeneral ); } // Check for name, should return KErrNone error = landmark->GetLandmarkName( namePtr ); if( KErrNone != error ) { iLog->Log(_L("ReadPartialLandmark fails, name not found")); User::Leave( KErrGeneral ); } // Check for Coverage radius, should return KErrNotFound TReal32 radius; error = landmark->GetCoverageRadius( radius ); if( KErrNotFound != error ) { iLog->Log(_L("ReadPartialLandmark fails, coverage radius was found in partial landmark")); User::Leave( KErrGeneral ); } // iLog->Log(_L("ReadPartialLandmark suceeds")); CleanupStack::PopAndDestroy( 4, lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::PrepareAndTakePartialLmks // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::PrepareAndTakePartialLmksL( CStifItemParser& /*aItem*/ ) { // Open and initialize DB CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Initialize database ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Partial read params CPosLmPartialReadParameters* readParams = CPosLmPartialReadParameters::NewLC(); // Set attributes, only name readParams->SetRequestedAttributes( CPosLandmark::ELandmarkName ); // Set partial read params lmkDatabase->SetPartialReadParametersL( *readParams ); // Get ids of all the landmarks using an iterator RArray<TPosLmItemId> idArray; TPosLmItemId id; CPosLmItemIterator* iterator = lmkDatabase->LandmarkIteratorL(); CleanupStack::PushL( iterator ); if( iterator->NumOfItemsL() == 0 ) { iLog->Log(_L("No landmark exists in database, PrepareAndTakePartialLmks fails")); User::Leave( KErrGeneral ); } // Iterate through all the landmarks and save ids into array while( ( id = iterator->NextL()) != KPosLmNullItemId ) { idArray.Append( id ); } // Prepare partial landmark CPosLmOperation* operation = lmkDatabase->PreparePartialLandmarksL( idArray ); CleanupStack::PushL( operation ); operation->ExecuteL(); iLog->Log(_L("operation done")); // Take partial landmark CArrayPtr<CPosLandmark>* lmkPtrArray = lmkDatabase->TakePreparedPartialLandmarksL( operation ); iLog->Log(_L("Takeprepared done")); //CleanupStack::PushL(lmkPtrArray); iLog->Log(_L("PrepareAndTakePartialLmks succeeds")); // CleanupStack::Pop(lmkPtrArray); lmkPtrArray->ResetAndDestroy(); iLog->Log(_L("after reset done")); CleanupStack::PopAndDestroy( 4, lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::ExportLandmarks // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::ExportLandmarksL( CStifItemParser& aItem ) { TPtrC exportFilePtr; TInt err = aItem.GetNextString( exportFilePtr ); // Open and initialize DB CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Initialize database ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Create encoder CPosLandmarkEncoder* encoder = CPosLandmarkEncoder::NewL( KPosMimeTypeLandmarkCollectionXml ); CleanupStack::PushL( encoder ); // delete output file if already exists RFs rfs; User::LeaveIfError(rfs.Connect()); rfs.Delete( exportFilePtr ); rfs.Close(); // Set output file encoder->SetOutputFileL( exportFilePtr ); // Create iterator CPosLmItemIterator* iterator = lmkDatabase->LandmarkIteratorL(); CleanupStack::PushL( iterator ); // if( iterator->NumOfItemsL() == 0 ) { iLog->Log(_L("No landmark exists in database, ExportLandmarks fails")); User::Leave( KErrGeneral ); } // Get ids RArray<TPosLmItemId> idArray; TPosLmItemId id; while( ( id = iterator->NextL() ) != KPosLmNullItemId ) { idArray.AppendL( id ); } // export landmarks CPosLmOperation* operation = lmkDatabase->ExportLandmarksL( *encoder, idArray, CPosLandmarkDatabase::EDefaultOptions ); CleanupStack::PushL( operation ); operation->ExecuteL(); // Finalize Encoding ExecuteAndDeleteLD( encoder->FinalizeEncodingL() ); // iLog->Log(_L("ExportLandmarks successful")); CleanupStack::PopAndDestroy( 4, lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::ImportLandmarks // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::ImportLandmarksL( CStifItemParser& aItem ) { TPtrC importFilePtr; TInt err = aItem.GetNextString( importFilePtr ); // Open and initialize DB CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Initialize database ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Create parser CPosLandmarkParser* parser = CPosLandmarkParser::NewL( KPosMimeTypeLandmarkCollectionXml ); CleanupStack::PushL( parser ); // Set Input file parser->SetInputFileL( importFilePtr ); // Import landmarks to DB iLog->Log(_L("Before ImportLandmarks ")); CPosLmOperation* operation = lmkDatabase->ImportLandmarksL( *parser, CPosLandmarkDatabase::EDefaultOptions ); iLog->Log(_L("After ImportLandmarks ")); CleanupStack::PushL( operation ); iLog->Log(_L("Before ExecuteL ")); TRAPD(error,operation->ExecuteL()); iLog->Log(_L("After ExecuteL ")); iLog->Log(_L("ImportLandmarks successful")); CleanupStack::PopAndDestroy( 3, lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::ImportSelectedLandmarks // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::ImportSelectedLandmarksL( CStifItemParser& aItem ) { TPtrC importFilePtr; TInt err = aItem.GetNextString( importFilePtr ); // Open and initialize DB CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Initialize database ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Create parser CPosLandmarkParser* parser = CPosLandmarkParser::NewL( KPosMimeTypeLandmarkCollectionXml ); CleanupStack::PushL( parser ); // Set Input file parser->SetInputFileL( importFilePtr ); // Import landmarks to DB // Define index array RArray<TUint> indexArray; // Add indexes of selected landmarks, only these should be imported indexArray.AppendL( 0 ); indexArray.AppendL( 1 ); CPosLmOperation* operation = lmkDatabase->ImportLandmarksL( *parser, indexArray, CPosLandmarkDatabase::EDefaultOptions ); CleanupStack::PushL( operation ); TRAPD(error,operation->ExecuteL()); iLog->Log(_L("ImportSelectedLandmarks successful")); CleanupStack::PopAndDestroy( 3, lmkDatabase ); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::ImportedLmkIterator // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::ImportedLmkIteratorL( CStifItemParser& aItem ) { TPtrC importFilePtr; TInt err = aItem.GetNextString( importFilePtr ); // Open and initialize DB CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Initialize database ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // Create parser CPosLandmarkParser* parser = CPosLandmarkParser::NewL( KPosMimeTypeLandmarkCollectionXml ); CleanupStack::PushL( parser ); // Set Input file parser->SetInputFileL( importFilePtr ); // Import landmarks to DB CPosLmOperation* operation = lmkDatabase->ImportLandmarksL( *parser, CPosLandmarkDatabase::EDefaultOptions ); CleanupStack::PushL( operation ); TRAPD(error,operation->ExecuteL()); // Get iterator for imported landmarks CPosLmItemIterator* iterator = lmkDatabase->ImportedLandmarksIteratorL( operation ); CleanupStack::PushL( iterator ); // Get ids of imported landmarks RArray<TPosLmItemId> idArray; TPosLmItemId id; while( (id = iterator->NextL()) != KPosLmNullItemId ) { idArray.AppendL( id ); } iLog->Log(_L("ImportedLmkIterator successful")); CleanupStack::PopAndDestroy( 4, lmkDatabase); ReleaseLandmarkResources(); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::NotifyDatabaseEventL // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::NotifyDatabaseEventL( CStifItemParser& /*aItem*/ ) { // Open and initialize DB CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // NotfiyEvent request lmkDatabase->NotifyDatabaseEvent( iEvent, iStatus ); SetActive(); // Create a new landmark and add to database CPosLandmark* lmk = CPosLandmark::NewL(); CleanupStack::PushL( lmk ); // Add to database TPosLmItemId id = lmkDatabase->AddLandmarkL( *lmk ); // // Wait CActiveScheduler::Start(); // //lmkDatabase->CancelNotifyDatabaseEvent(); CleanupStack::PopAndDestroy( 2, lmkDatabase ); ReleaseLandmarkResources(); return iLastResult; //return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::CancelNotifyDatabaseEventL // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::CancelNotifyDatabaseEventL( CStifItemParser& /*aItem*/ ) { // Open and initialize DB CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // NotfiyEvent request lmkDatabase->NotifyDatabaseEvent( iEvent, iStatus ); SetActive(); // Cancel lmkDatabase->CancelNotifyDatabaseEvent(); // Wait CActiveScheduler::Start(); // CleanupStack::PopAndDestroy( lmkDatabase ); ReleaseLandmarkResources(); //return iLastResult; return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLmOperation::RunL // // // ----------------------------------------------------------------------------- // void CTestPosLandmarkDatabase::RunL() { iLog->Log(_L("RunL called")); if( iEvent.iEventType == EPosLmEventLandmarkCreated) { iLog->Log(_L("A Landmark is created")); iLastResult = KErrNone; } CActiveScheduler::Stop(); } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::DoCancel // // // ----------------------------------------------------------------------------- // void CTestPosLandmarkDatabase::DoCancel() { } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::InitTestDatabase // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::InitTestDatabaseL( CStifLogger* aLog ) { // URI // Check if exists CPosLmDatabaseManager *manager = CPosLmDatabaseManager::NewL(); CleanupStack::PushL( manager ); if( manager->DatabaseExistsL( KDBUri ) ) { // if yes // Open CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL(KDBUri); CleanupStack::PushL( lmkDatabase ); // Initialize database ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // check if populated // Get landmark iterator CPosLmItemIterator* iterator = lmkDatabase->LandmarkIteratorL(); CleanupStack::PushL( iterator ); TInt numOfLmks = iterator->NumOfItemsL(); if( numOfLmks > 0 ) { // if populated // return CleanupStack::PopAndDestroy( 3, manager ); ReleaseLandmarkResources(); return KErrNone; } else { // else // populate TInt error = AddLandmarksToTestDbL( lmkDatabase ); if( KErrNone != error ) { aLog->Log(_L("Error in populating Test Database")); CleanupStack::PopAndDestroy( 3, manager ); ReleaseLandmarkResources(); return error; } error = AddCategoriesToTestDbL( lmkDatabase ); if( KErrNone != error ) { aLog->Log(_L("Error in populating Test Database")); CleanupStack::PopAndDestroy( 3, manager ); ReleaseLandmarkResources(); return error; } // populated CleanupStack::PopAndDestroy( 3, manager ); ReleaseLandmarkResources(); return KErrNone; } } else { // else // create HPosLmDatabaseInfo* dbInfo = HPosLmDatabaseInfo::NewLC( KDBUri ); manager->CreateDatabaseL( *dbInfo ); // populate // Open CPosLandmarkDatabase* lmkDatabase = CPosLandmarkDatabase::OpenL( KDBUri ); CleanupStack::PushL( lmkDatabase ); // Initialize database ExecuteAndDeleteLD( lmkDatabase->InitializeL() ); // add landmarks TInt error = AddLandmarksToTestDbL( lmkDatabase ); if( KErrNone != error ) { aLog->Log(_L("Error in populating Test Database")); CleanupStack::PopAndDestroy( 3, manager ); ReleaseLandmarkResources(); return error; } // add categories error = AddCategoriesToTestDbL( lmkDatabase ); if( KErrNone != error ) { aLog->Log(_L("Error in populating Test Database")); CleanupStack::PopAndDestroy( 3, manager ); ReleaseLandmarkResources(); return error; } // success CleanupStack::PopAndDestroy( 3, manager ); ReleaseLandmarkResources(); return error; } // success } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::AddLandmarksToTestDb // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::AddLandmarksToTestDbL( CPosLandmarkDatabase* aDatabase ) { _LIT( KLmkName, "A Test Landmark " ); // Create a landmark, has to be trapped CPosLandmark* landmark = NULL; TRAPD( error, landmark = CPosLandmark::NewL() ); if( KErrNone != error ) { return error; } CleanupStack::PushL( landmark ); // Add 5 landmarks to DB TBuf<20> nameBuffer; for(TInt i = 1; i < 6; i++ ) { // Set name nameBuffer.Copy( KLmkName ); nameBuffer.AppendNum( i ); TRAP( error, landmark->SetLandmarkNameL( nameBuffer ) ); if( KErrNone != error ) { CleanupStack::PopAndDestroy( landmark ); return error; } // Add TRAP( error, aDatabase->AddLandmarkL( *landmark ) ); if( KErrNone != error ) { CleanupStack::PopAndDestroy( landmark ); return error; } }// Add loop CleanupStack::PopAndDestroy( landmark ); return KErrNone; } // ----------------------------------------------------------------------------- // CTestPosLandmarkDatabase::AddCategoriesToTestDb // // // ----------------------------------------------------------------------------- // TInt CTestPosLandmarkDatabase::AddCategoriesToTestDbL( CPosLandmarkDatabase* aDatabase ) { _LIT( KCatName, "A Test Category " ); // Create category manager CPosLmCategoryManager* categoryMgr = NULL; TRAPD( error, categoryMgr = CPosLmCategoryManager::NewL( *aDatabase )); if( KErrNone != error ) { return error; } CleanupStack::PushL( categoryMgr ); // Create a category, has to be trapped CPosLandmarkCategory* category = NULL; TRAP(error, category = CPosLandmarkCategory::NewL()); if( KErrNone != error ) { CleanupStack::PopAndDestroy( categoryMgr ); return error; } CleanupStack::PushL( category ); // Add 5 landmarks to DB TBuf<20> nameBuffer; for(TInt i = 1; i < 6; i++) { // Set name nameBuffer.Copy( KCatName ); nameBuffer.AppendNum( i ); TRAP( error, category->SetCategoryNameL( nameBuffer ) ); if( KErrNone != error ) { CleanupStack::PopAndDestroy( 2, categoryMgr ); return error; } // Add TRAP( error, categoryMgr->AddCategoryL( *category ) ); if( KErrNone!= error ) { CleanupStack::PopAndDestroy( 2, categoryMgr ); return error; } }// Add loop CleanupStack::PopAndDestroy( 2, categoryMgr ); return KErrNone; }
[ "none@none" ]
[ [ [ 1, 1113 ] ] ]
749df28f2bdb9db131121eeb28aeeec7702a823a
8e0d57c533957a02d0217507c011ed2c643dccfa
/src/model.cpp
42778e6efdc68003b541c5de88753a57e25984cd
[]
no_license
sbalyakin/lightrus
d26424cad6d44dcd9c947e81a39955cf6bf09e9d
15faa8181560d9fb2c4a79d5bf4ea7433843dd3b
refs/heads/master
2021-05-29T17:11:22.832277
2010-04-03T16:41:17
2010-04-03T16:41:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,269
cpp
/******************************************************************************* Project Lightrus Copyright (C) 2009 Sergey Balyakin 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 3 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. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ #include "model.h" #include "translator.h" #include "infocollector.h" #include "modelhelper.h" #include "constants.h" #include <QApplication> #include <QClipboard> using namespace consts; Model::Model() : translator(new Translator), model_helper(new ModelHelper) { connect(translator, SIGNAL(SendLogMessage(const QString&)), SIGNAL(SendLogMessage(const QString&))); connect(translator, SIGNAL(SendInfoMessage(const QString&)), SIGNAL(SendInfoMessage(const QString&))); connect(translator, SIGNAL(SendErrorMessage(const QString&)), SIGNAL(SendErrorMessage(const QString&))); connect(translator, SIGNAL(StartNewFileTranslate(const QString&)), SIGNAL(StartNewFileTranslate(const QString&))); connect(translator, SIGNAL(CurrentFileProgressChanged(int)), SIGNAL(CurrentFileProgressChanged(int))); connect(model_helper, SIGNAL(SendLogMessage(const QString&)), SIGNAL(SendLogMessage(const QString&))); connect(model_helper, SIGNAL(SendInfoMessage(const QString&)), SIGNAL(SendInfoMessage(const QString&))); connect(model_helper, SIGNAL(SendErrorMessage(const QString&)), SIGNAL(SendErrorMessage(const QString&))); } Model::~Model() { delete translator; delete model_helper; } void Model::Translate(const QString& lightroom_path, const QString& language_abb, bool is_need_backup) { translator->TranslateAll( res_path_russian_dictionary, res_path_english_exclusions, lightroom_path, language_abb, is_need_backup ); } void Model::CopyEnglishHelpFiles(const QString& lightroom_path, const QString& language_abb, bool is_need_backup) { emit SendLogMessage(text_copying_help_files); model_helper->CopyEnglishHelpFiles(lightroom_path, language_abb, is_need_backup); } QString Model::GetDefaultLightroomPath() { return InfoCollector::GetLightroomInstallDir(); } bool Model::IsValidLightroomPath(const QString& path) { return InfoCollector::IsValidLightroomDir(path); } void Model::OpenReadmeFile(const QString& lightroom_path) { model_helper->OpenReadmeFile(lightroom_path); } #ifdef Q_WS_WIN void Model::ToggleLanguageToSelected(const QString& language_abb) { model_helper->ToggleLanguageToSelected(language_abb); } #endif #ifdef Q_WS_MAC void Model::ToggleLanguageToRussian(const QString& lightroom_path) { model_helper->ToggleLanguageToRussian(lightroom_path); } #endif void Model::ExecLightroom(const QString& lightroom_path) { model_helper->ExecLightroom(lightroom_path); } void Model::RefreshLanguagesList(const QString& lightroom_path) { InfoCollector::GetLanguagesList(lightroom_path, languages); } QString Model::GetLanguageAbb(const QString& language_name) { return languages.key(language_name, QString()); } QString Model::GetLanguageName(const QString& language_abb) { return languages.value(language_abb, QString()); } QStringList Model::GetLanguagesNames() { QStringList result; for (Dictionary::iterator iter = languages.begin(); iter != languages.end(); ++iter) result.append(iter.value()); return result; } void Model::BuildMailText(QStringList& text) { text.clear(); text.append(text_os_version_s.arg(InfoCollector::GetOSVersion())); text.append(text_os_word_size_d.arg(InfoCollector::GetWordSize())); text.append(text_application_version_s.arg(application_version)); text.append(text_lightroom_path_s.arg(translator->GetLightroomPath())); text.append(text_language_abb_ss.arg(translator->GetLanguageAbb(), GetLanguageName(translator->GetLanguageAbb()))); text.append(text_unknown_phrases_count_d.arg(translator->GetUnknownKeysCount())); QStringList keys = translator->GetUnknownKeys(); foreach (QString key, keys) text.append(key); } void Model::SendTranslatingStats() { translator->SendTranslatingStats(); } void Model::CopyToClipboard(const QString& text) { qApp->clipboard()->setText(text); } void Model::CopyReadmeFile(const QString& lightroom_path) { model_helper->CopyReadmeFile(lightroom_path); } bool Model::IsUnknownPhrasesAvailable() { return translator->GetUnknownKeysCount() != 0; }
[ "bighatte@635696aa-491d-11de-ba0e-b5da6ac7b600" ]
[ [ [ 1, 160 ] ] ]
345f185029c7fd7601fe6601a67ecd15c995e87b
b26957d6f3a64b19cda1d76b265d93047c114891
/StudentDetection/StudentDetection/snakewindow.h
580074026bc13a47c6493cd92571ba93eb663945
[]
no_license
SachinTS/khoa-luan-tot-nghiep
58e7efbd51d5f807f08b62a641672b4fc62f7990
7200721aded827731232c49aeade804febfba086
refs/heads/master
2016-09-06T13:46:12.228528
2010-08-07T06:47:45
2010-08-07T06:47:45
33,529,631
0
0
null
null
null
null
UTF-8
C++
false
false
683
h
#pragma once #include "cv.h" #include "vector_space.h" #include "vector" using namespace std; class SnakeWindow { public: VectorSpace *space; float threshold; int l, n; // length, number of vector_space float delta; public: SnakeWindow(const char *sData); SnakeWindow(const char *sData, float threshold, float delta, int l); SnakeWindow(FILE *data); Snake *GetSnake(IplImage *image, IplImage *edge, const CvPoint& location); Snake *GetSnake(IplImage *image, IplImage *edge, const CvPoint& location, const CvRect& bounding_rect); Snake *GetSnake(IplImage *edge, const CvPoint& location, const CvRect& bounding_rect); ~SnakeWindow(void); };
[ "hvu.nguyen2007@b0713345-de22-efb3-841d-461946120171" ]
[ [ [ 1, 25 ] ] ]
6ba1ee2c4701c562f6b25040514a9dd77163d69e
3daaefb69e57941b3dee2a616f62121a3939455a
/mgllib/src/common/MyuDebugLog.h
3e9b7e1b72e5ba5e7848a483b2cea72fecbed449
[]
no_license
myun2ext/open-mgl-legacy
21ccadab8b1569af8fc7e58cf494aaaceee32f1e
8faf07bad37a742f7174b454700066d53a384eae
refs/heads/master
2016-09-06T11:41:14.108963
2009-12-28T12:06:58
2009-12-28T12:06:58
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,077
h
////////////////////////////////////////////////////////// // // MyuEasyWin v0.13.04 05/02/21 // - デバッグログクラス // // v0.10.00 04/xx/xx // ・新規作成 // // v0.13.04 05/02/21 // ・Close()でファイルポインタNULLにしてなかった。あぶねーw // ////////////////////////////////////////////////////////// #ifndef __MyuDebugLog_H__ #define __MyuDebugLog_H__ #include <stdio.h> #include <stdarg.h> ////////////////////////////////////////////// // // DLLエクスポート(mglafx.hをincludeするので) // #ifdef MGLLIB_EXPORTS #define DLL_EXP __declspec(dllexport) #endif #ifdef MGLLIB_INPORTS #define DLL_EXP __declspec(dllimport) #endif #ifndef DLL_EXP #define DLL_EXP #endif ///////////////////////////////////// // クラス宣言 class DLL_EXP CMyuDebugLog { private: FILE *m_fp; int m_nSpace; public: CMyuDebugLog(); virtual ~CMyuDebugLog(); void Open( const char* szLogFile ); void Close(); void Print( const char* format, ... ); }; #endif//__MyuDebugLog_H__
[ "myun2@6d62ff88-fa28-0410-b5a4-834eb811a934" ]
[ [ [ 1, 54 ] ] ]
98db082ea22076301b8980754b4ef9836ef9c8dc
bf9ca8636584e8112c392d6ca5cd85b6be4f6ebf
/src/PhysicsManager.cpp
9cdbc3e1f84868afbb7645caf3c7e47146ecbcbc
[]
no_license
RileyA/LD19_Aquatic
34e8e08a450ee9f53365d98ebef505341869dfb5
c30e1f8e3304428e7077cb2042b4169450a35db9
refs/heads/master
2020-05-18T08:49:05.084811
2011-02-17T07:36:14
2011-02-17T07:36:14
1,377,029
0
0
null
null
null
null
UTF-8
C++
false
false
17,740
cpp
#include "stdafx.h" #include "PhysicsManager.h" #include "Game.h" PhysicsManager::PhysicsManager() :started(0), mInterpolation(0.f), mTimeStep(1.f/100.f), mAccumulation(0.f) { } PhysicsManager::~PhysicsManager() { deinit(); } void PhysicsManager::init() { mDynamicsWorld = NULL; mCollisionConfiguration = new btDefaultCollisionConfiguration(); mDispatcher = new btCollisionDispatcher(mCollisionConfiguration); mBroadphase = new btDbvtBroadphase(); btSequentialImpulseConstraintSolver* sol = new btSequentialImpulseConstraintSolver; mSolver = sol; mDynamicsWorld = new btDiscreteDynamicsWorld(mDispatcher,mBroadphase,mSolver,mCollisionConfiguration); mDynamicsWorld->setGravity(btVector3(0,0,0)); mGlobalGravity = Ogre::Vector3(0,0,0); mTimeStep = 1.f/100.f; mAccumulation = 0.f; mInterpolation = 0.f; started = true; } void PhysicsManager::deinit() { if(started) { Game::getPtr()->log("Bullet shutting down!"); int i; for(unsigned int i=0;i<mObjects.size();++i) { delete mObjects[i]; mObjects[i] = 0; } for (i=mDynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--) { btCollisionObject* obj = mDynamicsWorld->getCollisionObjectArray()[i]; btRigidBody* body = btRigidBody::upcast(obj); if (body && body->getMotionState()) { delete body->getMotionState(); } mDynamicsWorld->removeCollisionObject( obj ); delete obj; } mObjects.clear(); std::map<String,btCollisionShape*>::iterator iter = mShapes.begin(); while(iter!=mShapes.end()) { delete iter->second; ++iter; } mShapes.clear(); delete mDynamicsWorld; delete mSolver; delete mBroadphase; delete mDispatcher; delete mCollisionConfiguration; started = false; } } void PhysicsManager::update(Real delta) { if(started) { mAccumulation += delta; while(mAccumulation>=mTimeStep) { mDynamicsWorld->stepSimulation(mTimeStep,0); for(unsigned int i=0;i<mObjects.size();++i) { if(!mObjects[i]->readyForDelete()) { mObjects[i]->update(true,0,getLocalGravity(mObjects[i]->getPosition())); } else { delete mObjects[i]; mObjects[i] = 0; mObjects.erase(mObjects.begin()+i); --i; } } mAccumulation -= mTimeStep; } mInterpolation = mAccumulation/mTimeStep; for(unsigned int i=0;i<mObjects.size();++i) { mObjects[i]->update(false,mInterpolation,mGlobalGravity); } } } float PhysicsManager::getInterpolation() { return mInterpolation; } PhysicsObject* PhysicsManager::createStaticTrimesh(String meshname,Ogre::Vector3 pos) { size_t vertex_count; btVector3* vertices; size_t numTris; size_t index_count; unsigned* indices; float vArray[9]; vertex_count = index_count = 0; bool added_shared = false; size_t current_offset = vertex_count; size_t shared_offset = vertex_count; size_t next_offset = vertex_count; size_t index_offset = index_count; size_t prev_vert = vertex_count; size_t prev_ind = index_count; bool newShape = false; if(mShapes.find(meshname)==mShapes.end()) { newShape = true; btTriangleMesh *mTriMesh = new btTriangleMesh(); Ogre::MeshPtr mesh = Ogre::MeshManager::getSingletonPtr()->load(meshname,Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);//Ogre::MeshPtr(mesh_); for(int i = 0;i < mesh->getNumSubMeshes();i++) { Ogre::SubMesh* submesh = mesh->getSubMesh(i); if(submesh->useSharedVertices) { if(!added_shared) { Ogre::VertexData* vertex_data = mesh->sharedVertexData; vertex_count += vertex_data->vertexCount; added_shared = true; } } else { Ogre::VertexData* vertex_data = submesh->vertexData; vertex_count += vertex_data->vertexCount; } Ogre::IndexData* index_data = submesh->indexData; index_count += index_data->indexCount; } int a = vertex_count; vertices = new btVector3[vertex_count]; indices = new unsigned[index_count]; added_shared = false; int rVT = 0; int rIT = 0; for(int i = 0;i < mesh->getNumSubMeshes();i++) { Ogre::SubMesh* submesh = mesh->getSubMesh(i); Ogre::VertexData* vertex_data = submesh->useSharedVertices ? mesh->sharedVertexData : submesh->vertexData; if((!submesh->useSharedVertices)||(submesh->useSharedVertices && !added_shared)) { if(submesh->useSharedVertices) { added_shared = true; shared_offset = current_offset; } const Ogre::VertexElement* posElem = vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_POSITION); Ogre::HardwareVertexBufferSharedPtr vbuf = vertex_data->vertexBufferBinding->getBuffer(posElem->getSource()); unsigned char* vertex = static_cast<unsigned char*>(vbuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY)); Ogre::Real* pReal; for(size_t j = 0; j < vertex_data->vertexCount; ++j, vertex += vbuf->getVertexSize()) { posElem->baseVertexPointerToElement(vertex, &pReal); Ogre::Vector3 pt; pt.x = (*pReal++); pt.y = (*pReal++); pt.z = (*pReal++); //pt = quat*pt;// + loc; //compensate for scale/transform/rotation (uneeded for static stuff) vertices[rVT + current_offset + j].setX(pt.x); vertices[rVT + current_offset + j].setY(pt.y); vertices[rVT + current_offset + j].setZ(pt.z); } vbuf->unlock(); next_offset += vertex_data->vertexCount; } Ogre::IndexData* index_data = submesh->indexData; numTris = index_data->indexCount / 3; unsigned short* pShort; unsigned int* pInt; Ogre::HardwareIndexBufferSharedPtr ibuf = index_data->indexBuffer; bool use32bitindexes = (ibuf->getType() == Ogre::HardwareIndexBuffer::IT_32BIT); if (use32bitindexes) pInt = static_cast<unsigned int*>(ibuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY)); else pShort = static_cast<unsigned short*>(ibuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY)); for(size_t k = 0; k < numTris; ++k) { size_t offset = (submesh->useSharedVertices)?shared_offset:current_offset; unsigned int vindex = use32bitindexes? *pInt++ : *pShort++; indices[rIT + index_offset + 0] = vindex + offset; vArray[0] = vertices[indices[index_offset + 0]].x(); vArray[1] = vertices[indices[index_offset + 0]].y(); vArray[2] = vertices[indices[index_offset + 0]].z(); vindex = use32bitindexes? *pInt++ : *pShort++; indices[rIT + index_offset + 1] = vindex + offset; vArray[3] = vertices[indices[index_offset + 1]].x(); vArray[4] = vertices[indices[index_offset + 1]].y(); vArray[5] = vertices[indices[index_offset + 1]].z(); vindex = use32bitindexes? *pInt++ : *pShort++; indices[rIT + index_offset + 2] = vindex + offset; vArray[6] = vertices[indices[index_offset + 2]].x(); vArray[7] = vertices[indices[index_offset + 2]].y(); vArray[8] = vertices[indices[index_offset + 2]].z(); mTriMesh->addTriangle(btVector3(vArray[0],vArray[1],vArray[2]), btVector3(vArray[3],vArray[4],vArray[5]), btVector3(vArray[6],vArray[7],vArray[8])); index_offset += 3; } ibuf->unlock(); current_offset = next_offset; } btCollisionShape *triMeshShape = new btBvhTriangleMeshShape(mTriMesh,true); mShapes[meshname] = triMeshShape; } btVector3 localInertia(0,0,0); btCollisionObject* actor = new btCollisionObject(); actor->setCollisionShape(mShapes[meshname]); actor->setWorldTransform(btTransform(btQuaternion::getIdentity(),btVector3(pos.x,pos.y,pos.z))); actor->setRestitution(0.1f); actor->setFriction(1.5f); //actor->setAnisotropicFriction(btVector3(0.8f,0.8f,0.8f)); mDynamicsWorld->addCollisionObject(actor,COLLISION_GROUP_1); mObjects.push_back(new PhysicsObject(actor,mDynamicsWorld)); if(newShape) { delete[] vertices; delete[] indices; } return mObjects[mObjects.size()-1]; //return NULL; } PhysicsObject* PhysicsManager::createStaticTrimesh(GraphicsObject* object,Ogre::Vector3 pos) { return createStaticTrimesh(object->entity->getMesh()->getName(),pos); } PhysicsObject* PhysicsManager::createCube(Ogre::Vector3 scale,Ogre::Vector3 pos) { if(mShapes.find("BOX"+Ogre::StringConverter::toString(scale))==mShapes.end()) { btBoxShape *boxShape = new btBoxShape(btVector3(scale.x,scale.y,scale.z)); mShapes["BOX"+Ogre::StringConverter::toString(scale)] = (boxShape); } btVector3 localInertia(0,0,0); mShapes["BOX"+Ogre::StringConverter::toString(scale)]->calculateLocalInertia(18.f,localInertia); btRigidBody* actor = new btRigidBody(18.f,0,mShapes["BOX"+Ogre::StringConverter::toString(scale)],localInertia); actor->setRestitution(0.3f); actor->setFriction(0.8f); actor->setAnisotropicFriction(btVector3(0.9f,0.9f,0.9f)); actor->setWorldTransform(btTransform(btQuaternion::getIdentity(),btVector3(pos.x,pos.y,pos.z))); dynamic_cast<btDiscreteDynamicsWorld*>(mDynamicsWorld)->addRigidBody(actor,COLLISION_GROUP_1,COLLISION_GROUP_1); mObjects.push_back(new PhysicsObject(actor,mDynamicsWorld)); return mObjects[mObjects.size()-1]; } PhysicsObject* PhysicsManager::createSphere(float radius,Ogre::Vector3 pos) { if(mShapes.find("SPHERE"+Ogre::StringConverter::toString(radius))==mShapes.end()) { btSphereShape *sphereShape = new btSphereShape(radius); mShapes["SPHERE"+Ogre::StringConverter::toString(radius)] = (sphereShape); } btVector3 localInertia(0,0,0); mShapes["SPHERE"+Ogre::StringConverter::toString(radius)]->calculateLocalInertia(18.f,localInertia); btRigidBody* actor = new btRigidBody(18.f,0,mShapes["SPHERE"+Ogre::StringConverter::toString(radius)],localInertia); actor->setRestitution(0.3f); actor->setFriction(0.8f); actor->setAnisotropicFriction(btVector3(0.9f,0.9f,0.9f)); actor->setWorldTransform(btTransform(btQuaternion::getIdentity(),btVector3(pos.x,pos.y,pos.z))); //dynamic_cast<btDiscreteDynamicsWorld*>(mDynamicsWorld)->addRigidBody(actor,COLLISION_GROUP_2,COLLISION_GROUP_2|COLLISION_GROUP_3|COLLISION_GROUP_1); dynamic_cast<btDiscreteDynamicsWorld*>(mDynamicsWorld)->addRigidBody(actor,COLLISION_GROUP_1,COLLISION_GROUP_1); //if I need collision filtering.. mObjects.push_back(new PhysicsObject(actor,mDynamicsWorld)); return mObjects[mObjects.size()-1]; } PhysicsObject* PhysicsManager::createConvexHull(String meshname,Ogre::Vector3 pos,Ogre::Vector3 scale) { bool newshape = false; size_t vertex_count; float* vertices; size_t index_count; vertex_count = index_count = 0; bool added_shared = false; size_t current_offset = vertex_count; size_t shared_offset = vertex_count; size_t next_offset = vertex_count; size_t index_offset = index_count; size_t prev_vert = vertex_count; size_t prev_ind = index_count; std::vector<Ogre::Vector3> vertVect; btConvexShape *convexShape; //btShapeHull* hull; if(meshname=="CUBE"||meshname=="BOX") { return createCube(scale,pos); } if(mShapes.find(meshname)==mShapes.end()) { newshape = true; Ogre::MeshPtr mesh = Ogre::MeshManager::getSingletonPtr()->load(meshname,Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); // Calculate how many vertices and indices we're going to need for(int i = 0;i < mesh->getNumSubMeshes();i++) { Ogre::SubMesh* submesh = mesh->getSubMesh(i); // We only need to add the shared vertices once if(submesh->useSharedVertices) { if(!added_shared) { Ogre::VertexData* vertex_data = mesh->sharedVertexData; vertex_count += vertex_data->vertexCount; added_shared = true; } } else { Ogre::VertexData* vertex_data = submesh->vertexData; vertex_count += vertex_data->vertexCount; } // Add the indices Ogre::IndexData* index_data = submesh->indexData; index_count += index_data->indexCount; } // Allocate space for the vertices and indices int a = vertex_count; vertices = new float[vertex_count*3]; added_shared = false; // Run through the submeshes again, adding the data into the arrays for(int i = 0;i < mesh->getNumSubMeshes();i++) { Ogre::SubMesh* submesh = mesh->getSubMesh(i); Ogre::VertexData* vertex_data = submesh->useSharedVertices ? mesh->sharedVertexData : submesh->vertexData; if((!submesh->useSharedVertices)||(submesh->useSharedVertices && !added_shared)) { if(submesh->useSharedVertices) { added_shared = true; shared_offset = current_offset; } const Ogre::VertexElement* posElem = vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_POSITION); Ogre::HardwareVertexBufferSharedPtr vbuf = vertex_data->vertexBufferBinding->getBuffer(posElem->getSource()); unsigned char* vertex = static_cast<unsigned char*>(vbuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY)); Ogre::Real* pReal; for(size_t j = 0; j < vertex_data->vertexCount; ++j, vertex += vbuf->getVertexSize()) { posElem->baseVertexPointerToElement(vertex, &pReal); Ogre::Vector3 pt; pt.x = (*pReal++); pt.y = (*pReal++); pt.z = (*pReal++); bool skip = false; // ignore duped verts for(unsigned int i=0;i<vertVect.size();++i) { if(vertVect[i]==pt) { skip = true; //std::cout<<"IGNORED!\n"; } } // skipping duped verts caused some kind of f-up, TOBEFIXED eventually if(!skip) { vertices[current_offset + (j*3)] = pt.x*0.92f; vertices[current_offset + (j*3) + 1] = pt.y*0.92f; vertices[current_offset + (j*3) + 2] = pt.z*0.92f; vertVect.push_back(pt); } } vbuf->unlock(); next_offset += vertex_data->vertexCount; } } convexShape = new btConvexHullShape(static_cast<btScalar*>(vertices),vertVect.size(),3*sizeof(btScalar)); //create a hull approximation btConvexShape *finalShape = 0; //std::cout<<"size: "<<vertVect.size()<<"\n"; // seemed kinda iffy? //if(vertVect.size()>75) //{ // hull = new btShapeHull(convexShape); // btScalar margin = convexShape->getMargin(); // hull->buildHull(margin); // //btConvexHullShape* simplifiedConvexShape = new btConvexHullShape(hull->getVertexPointer(),hull->numVertices()); // // btConvexHullShape* simplifiedConvexShape = new btConvexHullShape(); // for (int i=0;i<hull->numVertices();i++) // { // btVector3 vect = hull->getVertexPointer()[i]*0.9; // std::cout<<"Vert: "<<vect.x()<<" "<<vect.y()<<" "<<vect.z()<<"\n"; // simplifiedConvexShape->addPoint(vect); // } // mShapes[meshname] = (simplifiedConvexShape); // finalShape = simplifiedConvexShape; //} //else //{ mShapes[meshname] = (convexShape); finalShape = convexShape; //} } //finalShape->setMargin(0.f); btVector3 localInertia(0,0,0); mShapes[meshname]->calculateLocalInertia(180.f,localInertia); btRigidBody* actor = new btRigidBody(180.f,0,mShapes[meshname],localInertia); actor->setWorldTransform(btTransform(btQuaternion::getIdentity(),btVector3(pos.x,pos.y,pos.z))); actor->setRestitution(0.f); actor->setFriction(0.8f); //actor->setAnisotropicFriction(btVector3(0.3f,0.3f,0.3f)); actor->setDamping(0.2f,0.7f); dynamic_cast<btDiscreteDynamicsWorld*>(mDynamicsWorld)->addRigidBody(actor,COLLISION_GROUP_1,COLLISION_GROUP_1); mObjects.push_back(new PhysicsObject(actor,mDynamicsWorld)); if(newshape) { delete[] vertices; //if(vertVect.size()>75) //{ // delete hull; // delete convexShape; //} } return mObjects[mObjects.size()-1]; } PhysicsObject* PhysicsManager::createConvexHull(GraphicsObject* object,Ogre::Vector3 pos) { return createConvexHull(object->entity->getMesh()->getName(),pos); } Ogre::Vector3 PhysicsManager::getLocalGravity(Ogre::Vector3 pos) { return mGlobalGravity; } Ogre::Vector3 PhysicsManager::getLocalGravityCCT(Ogre::Vector3 pos) { return mGlobalGravity; } Ogre::Vector3 PhysicsManager::getGravity() { return mGlobalGravity; } void PhysicsManager::setGravity(Ogre::Vector3 grav) { mGlobalGravity = grav; } RaycastReport PhysicsManager::raycastSimple(Ogre::Vector3 pos,Ogre::Vector3 dir,Real dist,short group,short mask) { dir.normalise(); dir*=dist; btCollisionWorld::ClosestRayResultCallback cb(btVector3(pos.x,pos.y,pos.z), btVector3(pos.x+dir.x,pos.y+dir.y,pos.z+dir.z)); // everythang: cb.m_collisionFilterGroup = COLLISION_GROUP_0|COLLISION_GROUP_1|COLLISION_GROUP_3|COLLISION_GROUP_4|COLLISION_GROUP_5|COLLISION_GROUP_6| COLLISION_GROUP_7|COLLISION_GROUP_8|COLLISION_GROUP_9|COLLISION_GROUP_10|COLLISION_GROUP_11|COLLISION_GROUP_12| COLLISION_GROUP_13|COLLISION_GROUP_14|COLLISION_GROUP_15; cb.m_collisionFilterMask = COLLISION_GROUP_0|COLLISION_GROUP_1|COLLISION_GROUP_3|COLLISION_GROUP_4|COLLISION_GROUP_5|COLLISION_GROUP_6| COLLISION_GROUP_7|COLLISION_GROUP_8|COLLISION_GROUP_9|COLLISION_GROUP_10|COLLISION_GROUP_11|COLLISION_GROUP_12| COLLISION_GROUP_13|COLLISION_GROUP_14|COLLISION_GROUP_15; cb.m_collisionFilterGroup = cb.m_collisionFilterGroup^group; cb.m_collisionFilterMask = cb.m_collisionFilterMask^mask; mDynamicsWorld->rayTest(btVector3(pos.x,pos.y,pos.z),btVector3(pos.x+dir.x,pos.y+dir.y,pos.z+dir.z),cb); if(cb.hasHit()) { return RaycastReport(Ogre::Vector3(cb.m_hitNormalWorld.x(),cb.m_hitNormalWorld.y(),cb.m_hitNormalWorld.z()),Ogre::Vector3(cb.m_hitPointWorld.x(),cb.m_hitPointWorld.y(),cb.m_hitPointWorld.z()),cb.m_collisionObject->getBroadphaseHandle()->m_collisionFilterGroup,cb.m_collisionObject->getUserPointer()); } else { return RaycastReport(); } }
[ [ [ 1, 568 ] ] ]
9c9ce2a39a741ea65bba3453797f3efad5d2a729
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Dynamics/Constraint/Chain/hkpConstraintChainInstance.h
7c685ba09880cc99fef395abbc0105cb489e7bc9
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,481
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_DYNAMICS2_CONSTRAINT_CHAIN_INSTANCE_H #define HK_DYNAMICS2_CONSTRAINT_CHAIN_INSTANCE_H #include <Physics/Dynamics/Constraint/hkpConstraintInstance.h> #include <Physics/Dynamics/Constraint/Chain/hkpConstraintChainData.h> class hkpEntity; class hkpConstraintChainInstanceAction; /// hkpConstraintChainInstance allows you to create chains of constraints which are solved with a full-matrix solver (as opposed to Havok's iterative solver). /// This approach allows for creating much more stable setups. It is useful for creating long ropes, linking objects with high relative mass ratio, and creating /// more sturdy rag-doll setups. /// /// Solving of the constraint chains is based on the solver-in-a-solver approach. The entire constraint-chain is treated by the main Havok's solver as a single /// constraint. When the chain is processed it performs calculations on all its bodies at once using its own custom information. This means that in itself /// the constraint chain is perfectly stiff, however if single elements of the chain are colliding with other objects, separation can occur. /// /// If you have a more complicated constraint system, like a ragdoll, you can use several constraint chain instances at the same time. /// Example, you can create a chain going from the left foot to the right hand and another one going from the right foot to the left hand. /// Ideally the body/bodies which are shared by the two chains should be as heavy as possible to reduce stretching artefacts. /// /// Note: Constraints chains must use PRIORITY_PSI. Constraint chains do not support TOI-event solving. /// /// hkpConstraintChainInstance implements hkpConstraintInstance's interface and is treated by hkdynamics just like a normal constraint. However the hkpConstraintInstance /// is designed to only connect two rigid bodies. hkpConstraintChainInstance stores internally the full list of bodies it links. That information is then passed /// to the constraint constraint solver with hkpConstraintChainInstance's custom code. /// /// In order to properly react to e.g. bodies being removed from the hkpWorld, a hkpConstraintChainInstance is always coupled with a hkpConstraintChainInstanceAction /// which is automatically added to the world with the constraint chain. This action makes sure that the constraint-chain is removed from the world when some of the bodies /// that it references are missing. /// /// Data organization: /// - hkpConstraintChainInstance stores the list of bodies linked. /// - The constraint properties are stored in its hkpConstraintChainData. /// - The current state of those constraints is stored in the chain's Runtime. /// class hkpConstraintChainInstance : public hkpConstraintInstance { public: HK_DECLARE_REFLECTION(); HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_CONSTRAINT ); /// Constructor. hkpConstraintChainInstance(hkpConstraintChainData* data); /// Destructor. Deletes the hkpConstraintChainInstanceAction belonging to the chain. ~hkpConstraintChainInstance(); /// Get the hkpConstraintChainData object inline hkpConstraintChainData* getData() const { return static_cast<hkpConstraintChainData*>(m_data); } /// Interface implementation. Also removes the chain's hkpConstraintChainInstanceAction from the world. virtual void entityRemovedCallback(hkpEntity* entity); /// Returns constraint type (normal/chain). virtual InstanceType getType() const { return TYPE_CHAIN; } /// Adds entity to the constraint-chain. The number of entities cannot exceed (getData()->getNumConstraintInfos() + 1) but may be less than that. In such /// case the constraint infos at the end are ignored when solving the constraint. void addEntity(hkpEntity* entity); /// Adds entity to the constraint chain at the beginning of the list, and shifts all previous constraints. /// Note that this causes a reorganization in the entity-to-constraintInfo matching. inline void insertEntityAtFront(hkpEntity* entity) { HK_ASSERT2(0xad6d5d44, m_owner == HK_NULL, "Cannot add entities when constraint chain is added to the world"); HK_ASSERT2(0xad7877dd, m_chainedEntities.getSize() <= getData()->getNumConstraintInfos(), "Cannot add anymore entities to the chain -- pivots not specified."); m_chainedEntities.insertAt( 0, entity ); entity->addReference(); } /// Returns the number of constraints that will be solved in the chain. inline int getNumConstraints() { return hkMath::max2( 0, m_chainedEntities.getSize() - 1 ); } /// List of entieties linked by the chain. This array is also referenced by the hkpConstraintChainInstanceAction. hkArray<hkpEntity*> m_chainedEntities; /// Action guarding the chain constraint. When an entity belonging to the chain is removed, that action receives a callback and removes the constraint. /// We use this workaround because constraints can only hold references to two bodies. hkpConstraintChainInstanceAction* m_action; /// Serialization constructor hkpConstraintChainInstance( hkFinishLoadedObjectFlag f ) : hkpConstraintInstance(f), m_chainedEntities(f) {} }; #endif // HK_DYNAMICS2_CONSTRAINT_CHAIN_INSTANCE_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 116 ] ] ]
b0b0342e7f22579aa1dbc9c6496160602eb2f8e8
7e68ef369eff945f581e22595adecb6b3faccd0e
/code/linux/minifw/eventhandler.h
828b2c93e6fb24b92faedb895c117c4a4d9ddf5b
[]
no_license
kimhmadsen/mini-framework
700bb1052227ba18eee374504ff90f41e98738d2
d1983a68c6b1d87e24ef55ca839814ed227b3956
refs/heads/master
2021-01-01T05:36:55.074091
2008-12-16T00:33:10
2008-12-16T00:33:10
32,415,758
0
0
null
null
null
null
UTF-8
C++
false
false
769
h
#pragma once #include <sys/socket.h> typedef unsigned int Event_Type; typedef int HANDLE; /** * Enum definning events for a the event handlers. */ enum { READ_EVENT = 1, ///< ACCEPT_EVENT alias READ_EVENT ACCEPT_EVENT = 1, ///< Accept event WRITE_EVENT = 2, ///< Write event TIMEOUT_EVENT = 4, ///< Timeout event CLOSE_EVENT = 8, ///< Close event }; /** Event handler used as an abstract class. Responsibility: - Defines an interface for processing indication event tht occur on a handle. Collaborator: - Handle */ class EventHandler { public: EventHandler(void); ~EventHandler(void); virtual void HandleEvent(HANDLE handle, Event_Type et ) = 0; virtual HANDLE GetHandle(void); private: HANDLE handle; };
[ "mariasolercliment@77f6bdef-6155-0410-8b08-fdea0229669f" ]
[ [ [ 1, 34 ] ] ]
617f7fc408db6e656e7da643ec0664a37beca601
fbaccf402034416a5dc1dfd037f802499efa6aff
/2d/benchmarks-nist/09-wave-front-kelly-dealii/definitions.h
518abc1625ace824fef3ed176faace2e6841776a
[]
no_license
davidquantum/hermes-examples
ddcdff3139de86500bd19c174fb7f06da59918eb
ca469bda756919a52d8624439e2d28d6dc441699
refs/heads/master
2021-01-15T23:41:25.975781
2011-08-02T13:33:55
2011-08-02T13:33:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,486
h
#include "hermes2d.h" using namespace Hermes::Hermes2D; using namespace WeakFormsH1; using Hermes::Ord; /* Right-hand side */ class CustomWeakForm : public WeakForm<double> { class Jacobian : public MatrixFormVol<double> { public: Jacobian() : MatrixFormVol<double>(0, 0, Hermes::HERMES_ANY, HERMES_SYM) {}; virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v, Geom<double> *e, ExtData<double> *ext) const; virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, Geom<Ord> *e, ExtData<Ord> *ext) const; }; class Residual : public VectorFormVol<double> { const Hermes::Hermes2DFunction<double>* rhs; public: Residual(const Hermes::Hermes2DFunction<double>* rhs) : VectorFormVol<double>(0), rhs(rhs) {}; virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, Geom<double> *e, ExtData<double> *ext) const; virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e, ExtData<Ord> *ext) const; }; public: CustomWeakForm(const Hermes::Hermes2DFunction<double>* rhs) { add_matrix_form(new Jacobian); add_vector_form(new Residual(rhs)); } }; class CustomRightHandSide : public Hermes::Hermes2DFunction<double> { public: CustomRightHandSide(double alpha, double x_loc, double y_loc, double r_zero) : Hermes::Hermes2DFunction<double>(), alpha(alpha), x_loc(x_loc), y_loc(y_loc), r_zero(r_zero) { }; virtual double value(double x, double y) const; virtual Ord value_ord (Ord x, Ord y) const { return Ord(8); } double alpha, x_loc, y_loc, r_zero; }; /* Exact solution */ class CustomExactSolution : public ExactSolutionScalar<double> { public: CustomExactSolution(Mesh* mesh, double alpha, double x_loc, double y_loc, double r_zero) : ExactSolutionScalar<double>(mesh), alpha(alpha), x_loc(x_loc), y_loc(y_loc), r_zero(r_zero) { }; virtual double value(double x, double y) const { return atan(alpha * (sqrt(pow(x - x_loc, 2) + pow(y - y_loc, 2)) - r_zero)); }; virtual void derivatives (double x, double y, double& dx, double& dy) const; virtual Ord ord (Ord x, Ord y) const { return Ord(Ord::get_max_order()); } double alpha, x_loc, y_loc, r_zero; }; /* Bilinear form inducing the energy norm */ class EnergyErrorForm : public Adapt<double>::MatrixFormVolError { public: EnergyErrorForm(WeakForm<double> *problem_wf) : Adapt<double>::MatrixFormVolError(HERMES_UNSET_NORM) { this->form = problem_wf->get_matrix_form(0); } virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v, Geom<double> *e, ExtData<double> *ext) const { return this->form->value(n, wt, u_ext, u, v, e, ext); } virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, Geom<Ord> *e, ExtData<Ord> *ext) const { return this->form->ord(n, wt, u_ext, u, v, e, ext); } private: const MatrixFormVol<double>* form; }; /* Linear form for the residual error estimator */ class ResidualErrorForm : public KellyTypeAdapt<double>::ErrorEstimatorForm { public: ResidualErrorForm(CustomRightHandSide* rhs) : KellyTypeAdapt<double>::ErrorEstimatorForm(0), rhs(rhs) { }; double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Geom<double> *e, ExtData<double> *ext) const; Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Geom<Ord> *e, ExtData<Ord> *ext) const; private: CustomRightHandSide* rhs; }; class ConvergenceTable { public: void save(const char* filename) const; void add_column(const std::string& name, const std::string& format) { columns.push_back(Column(name, format)); } void add_value(unsigned int col, double x) { add_value_internal<double>(col, x, "%g"); } void add_value(unsigned int col, int x) { add_value_internal<int>(col, x, "%d"); } int num_rows() const { return columns[0].data.size(); } int num_columns() const { return columns.size(); } private: struct Column { Column(const std::string& name, const std::string& format) : label(name), format(format) { } struct Entry { union { int ivalue; double dvalue; }; enum { INT, DOUBLE } data_type; Entry(int x) : ivalue(x), data_type(INT) {}; Entry(double x) : dvalue(x), data_type(DOUBLE) {}; }; std::string label; std::string format; std::vector<Entry> data; }; std::vector<Column> columns; template <typename T> void add_value_internal(unsigned int col, T x, const std::string& default_fmt) { if (columns.size() == 0) add_column("", default_fmt); if (col < 0 || col >= columns.size()) error("Invalid column number."); columns[col].data.push_back(Column::Entry(x)); } }; // Convert int to string. std::string itos(const unsigned int i);
[ [ [ 1, 24 ], [ 26, 26 ], [ 28, 36 ], [ 38, 43 ], [ 45, 47 ], [ 49, 187 ] ], [ [ 25, 25 ], [ 27, 27 ], [ 37, 37 ], [ 44, 44 ], [ 48, 48 ] ] ]
022befeffad3584b702f8038db5cb94435cb39b4
119ba245bea18df8d27b84ee06e152b35c707da1
/qreal/qrgui/mainwindow/errorReporter.cpp
03bb4a8973836bb468fe2b215a92465465277e6e
[]
no_license
nfrey/qreal
05cd4f9b9d3193531eb68ff238d8a447babcb3d2
71641e6c5f8dc87eef9ec3a01cabfb9dd7b0e164
refs/heads/master
2020-04-06T06:43:41.910531
2011-05-30T19:30:09
2011-05-30T19:30:09
1,634,768
0
0
null
null
null
null
UTF-8
C++
false
false
3,120
cpp
#include "errorReporter.h" #include <QtGui/QMessageBox> #include "errorlistwidget.h" #include "../kernel/exception/exception.h" using namespace qReal; using namespace gui; ErrorReporter::ErrorReporter() : mErrorListWidget(NULL) , mErrorList(NULL) { } ErrorReporter::ErrorReporter(ErrorListWidget* const errorListWidget, QDockWidget* const errorList) : mErrorListWidget(errorListWidget) , mErrorList(errorList) { } void ErrorReporter::addInformation(QString const &message, Id const &position) { Error error(message, Error::information, position); mErrors.append(error); showError(error, mErrorListWidget); } void ErrorReporter::addWarning(QString const &message, Id const &position) { Error error(message, Error::warning, position); mErrors.append(error); showError(error, mErrorListWidget); } void ErrorReporter::addError(QString const &message, Id const &position) { Error error(message, Error::error, position); mErrors.append(error); showError(error, mErrorListWidget); } void ErrorReporter::addCritical(QString const &message, Id const &position) { Error error(message, Error::critical, position); mErrors.append(error); showError(error, mErrorListWidget); } bool ErrorReporter::showErrors(ErrorListWidget* const errorListWidget, QDockWidget* const errorList) const { errorListWidget->clear(); if (mErrors.isEmpty()) { errorList->setVisible(false); return true; } errorList->setVisible(true); foreach (Error error, mErrors) showError(error, errorListWidget); return false; } void ErrorReporter::clear() { if (mErrorListWidget) mErrorListWidget->clear(); if (mErrorList) mErrorList->setVisible(false); } void ErrorReporter::clearErrors() { mErrors.clear(); } void ErrorReporter::showError(Error const &error, ErrorListWidget* const errorListWidget) const { if (!errorListWidget) return; if (mErrorList && !mErrorList->isVisible()) mErrorList->setVisible(true); QListWidgetItem* item = new QListWidgetItem(errorListWidget); QString message = severityMessage(error) + " "; message += error.message(); switch (error.severity()) { case Error::information: item->setIcon(QIcon(":/icons/information.png")); break; case Error::warning: item->setIcon(QIcon(":/icons/warning.png")); break; case Error::error: item->setIcon(QIcon(":/icons/error.png")); break; case Error::critical: item->setIcon(QIcon(":/icons/critical.png")); break; default: throw new Exception("Incorrect total severity"); } item->setText(" " + message.trimmed()); item->setTextAlignment(Qt::AlignVCenter); item->setToolTip(error.position().toString()); errorListWidget->addItem(item); } QString ErrorReporter::severityMessage(Error const &error) { switch (error.severity()) { case Error::information: return tr("INFORMATION:"); case Error::warning: return tr("WARNING:"); case Error::error: return tr("ERROR:"); case Error::critical: return tr("CRITICAL:"); default: throw new Exception("Incorrect severity of an error"); } }
[ "[email protected]", "26122006" ]
[ [ [ 1, 71 ], [ 76, 123 ] ], [ [ 72, 75 ] ] ]
117bdda960cc22b2d4f633bc10b07fb9574575b7
ca99bc050dbc58be61a92e04f2a80a4b83cb6000
/Game/src/Entities/Bodie.cpp
6dfe00210b8d4f1f062a333aeb67b9c9a638e13a
[]
no_license
NicolasBeaudrot/angry-tux
e26c619346c63a468ad3711de786e94f5b78a2f1
5a8259f57ba59db9071158a775948d06e424a9a8
refs/heads/master
2021-01-06T20:41:23.705460
2011-04-14T18:28:04
2011-04-14T18:28:04
32,141,181
0
0
null
null
null
null
UTF-8
C++
false
false
93
cpp
#include "Bodie.h" Bodie::Bodie() { //ctor } Bodie::~Bodie() { //dtor }
[ "nicolas.beaudrot@43db0318-7ac6-f280-19a0-2e79116859ad" ]
[ [ [ 1, 11 ] ] ]
416673bf53c75482842412b98eb7a3613aa0c7ce
672d939ad74ccb32afe7ec11b6b99a89c64a6020
/Graph/FloatLevel/Matrix.h
b356dd6f9028749d91907f049906d8eef392b645
[]
no_license
cloudlander/legacy
a073013c69e399744de09d649aaac012e17da325
89acf51531165a29b35e36f360220eeca3b0c1f6
refs/heads/master
2022-04-22T14:55:37.354762
2009-04-11T13:51:56
2009-04-11T13:51:56
256,939,313
1
0
null
null
null
null
UTF-8
C++
false
false
4,615
h
// Matrix.h: interface for the CMatrix class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_MATRIX_H__EC59CE74_977C_430D_9748_1150C145453D__INCLUDED_) #define AFX_MATRIX_H__EC59CE74_977C_430D_9748_1150C145453D__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 template <class T> class CMatrixT { public: CMatrixT(); CMatrixT(int Row_Dim,int Col_Dim); // set Matrix's dimension CMatrixT(CMatrixT<T>&); // CMatrix(Point3D&); virtual ~CMatrixT(); // operations: void Transform(CMatrixT<T>&); void Clear(); // clear all elements void ClearAt(int row,int col); // clear one elements void SetAt(int,int,const T&); // set one elements; // void SetAt(int,int,T); T& GetAt(int,int) const; T GetAt(int,int) ; int GetRowDim(); int GetColDim(); void SetIdentity(); // operation function: CMatrixT<T> operator* (CMatrixT<T>& ); CMatrixT<T>& operator= (CMatrixT<T>&); // CMatrixT<T>& operator= (Point3D&); enum{ DIM=4 }; private: int RowDim,ColDim; int RowCur,ColCur; // @just for debug T **MatrixRow; // Matrix's line T *MatrixCol; // Matrix's Colume void InitMatrix(); }; #ifdef _DEBUG #define new DEBUG_NEW //#undef THIS_FILE //static char THIS_FILE[] = __FILE__; #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// template <class T> CMatrixT<T>::CMatrixT() { RowDim=ColDim=DIM; MatrixCol=NULL; MatrixRow=NULL; InitMatrix(); } template <class T> CMatrixT<T>::CMatrixT(int dimx,int dimy) { RowDim=dimx; ColDim=dimy; InitMatrix(); } template <class T> CMatrixT<T>::CMatrixT(CMatrixT<T>& R_Matrix) { RowDim=R_Matrix.GetRowDim(); ColDim=R_Matrix.GetColDim(); InitMatrix(); *this=R_Matrix; } /* template <class T> CMatrixT<T>::CMatrix(Point3D& point) { xDim=1; yDim=4; type=MATRIX_FLOAT; InitMatrix(type); matrixLine[0][0]=point.x; matrixLine[0][1]=point.y; matrixLine[0][2]=point.z; matrixLine[0][3]=1; } */ template <class T> CMatrixT<T>::~CMatrixT() { if(MatrixRow!=NULL){ for(int i=0;i<RowDim;i++) delete[] MatrixRow[i]; delete[] MatrixRow; } } template <class T> void CMatrixT<T>::InitMatrix() { int i,j; MatrixRow=new T* [RowDim]; for(j=0;j<RowDim;j++) MatrixRow[j]=NULL; for(i=0;i<RowDim;i++) { MatrixCol=new T[ColDim]; for(j=0;j<ColDim;j++) MatrixCol[j]=0; // memset(matrixCol,0,yDim); MatrixRow[i]=MatrixCol; } } template <class T> void CMatrixT<T>::Transform(CMatrixT<T>& left) { int i,j; CMatrixT<T> temp(ColDim,RowDim); for(i=0;i<ColDim;i++) for(j=0;j<RowDim;j++) temp.SetAt(i,j,MatrixRow[j][i]); left= temp; } template <class T> void CMatrixT<T>::Clear() { for(int i=0;i<RowDim;i++) memset(MatrixRow[i],0,ColDim); } template <class T> void CMatrixT<T>::ClearAt(int x,int y) { memset(MatrixRow[x][y],0,1); } template <class T> void CMatrixT<T>::SetAt(int x,int y,const T& elem) { MatrixRow[x][y]=(T)elem; } /* template <class T> void CMatrixT<T>::SetAt(int x,int y,T elem) { MatrixRow[x][y]=(T)elem; } */ template <class T> T& CMatrixT<T>::GetAt(int x,int y) const { return MatrixRow[x][y]; } template <class T> T CMatrixT<T>::GetAt(int x,int y) { return MatrixRow[x][y]; } template <class T> int CMatrixT<T>::GetRowDim() { return RowDim; } template <class T> int CMatrixT<T>::GetColDim() { return ColDim; } template <class T> CMatrixT<T> CMatrixT<T>::operator*(CMatrixT<T>& right) { int i,j,k; T s=0; CMatrixT<T> temp(RowDim,ColDim); for(i=0;i<RowDim;i++) { for(j=0;j<ColDim;j++) { for(s=0,k=0;k<ColDim;k++) { s+=MatrixRow[i][k]*right.GetAt(k,j); } temp.SetAt(i,j,s); } } return CMatrixT<T>(temp); } template <class T> CMatrixT<T>& CMatrixT<T>::operator=(CMatrixT<T>& right) { int i,j; for(i=0;i<RowDim;i++) for(j=0;j<ColDim;j++) MatrixRow[i][j]=right.GetAt(i,j); return *this; } /* template <class T> CMatrix& CMatrix::operator=(Point3D& point) { ASSERT(xDim==1&&yDim==4); matrixLine[0][0]=point.x; matrixLine[0][1]=point.y; matrixLine[0][2]=point.z; matrixLine[0][3]=1; return *this; } */ template <class T> void CMatrixT<T>::SetIdentity() { if(RowDim!=ColDim) return; for(int i=0;i<RowDim;i++) MatrixRow[i][i]=1; } #endif // !defined(AFX_MATRIX_H__EC59CE74_977C_430D_9748_1150C145453D__INCLUDED_)
[ "xmzhang@5428276e-be0b-f542-9301-ee418ed919ad" ]
[ [ [ 1, 243 ] ] ]