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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7edf0ba413fd35b2128220810948601964746d03 | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2005-10-27/pcbnew/class_text_mod.cpp | 46c76a219bb75a4285134fd2d5133f662a467b5f | []
| 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 | ISO-8859-1 | C++ | false | false | 7,328 | cpp | /****************************************************/
/* class_module.cpp : fonctions de la classe MODULE */
/****************************************************/
#include "fctsys.h"
#include "gr_basic.h"
#include "wxstruct.h"
#include "common.h"
#include "pcbnew.h"
#include "trigo.h"
#ifdef PCBNEW
#include "autorout.h"
#include "drag.h"
#endif
#ifdef CVPCB
#include "cvpcb.h"
#endif
#include "protos.h"
/************************************************************************/
/* Class TEXTE_MODULE classe de base des elements type Texte sur module */
/************************************************************************/
/* Constructeur de TEXTE_MODULE */
TEXTE_MODULE::TEXTE_MODULE(MODULE * parent, int text_type ):
EDA_BaseStruct( parent, TYPETEXTEMODULE)
{
MODULE * Module = (MODULE*) m_Parent;
m_NoShow = 0; /* visible */
m_Type = text_type; /* Reference */
if( (m_Type != TEXT_is_REFERENCE) && (m_Type != TEXT_is_VALUE) )
m_Type = TEXT_is_DIVERS;
m_Size.x = m_Size.y = 400; m_Width = 120; /* dimensions raisonnables par defaut */
m_Orient = 0; /* en 1/10 degre */
m_Miroir = 1; // Mode normal (pas de miroir)
m_Unused = 0;
m_Layer = SILKSCREEN_N_CMP;
if( Module && (Module->m_StructType == TYPEMODULE) )
{
m_Pos = Module->m_Pos;
m_Layer = Module->m_Layer;
if( Module->m_Layer == CUIVRE_N) m_Layer = SILKSCREEN_N_CU;
if(Module->m_Layer == CMP_N) m_Layer = SILKSCREEN_N_CMP;
if((Module->m_Layer == SILKSCREEN_N_CU) ||
(Module->m_Layer == ADHESIVE_N_CU) || (Module->m_Layer == CUIVRE_N))
m_Miroir = 0;
}
}
TEXTE_MODULE:: ~TEXTE_MODULE(void)
{
}
void TEXTE_MODULE::Copy(TEXTE_MODULE * source) // copy structure
{
if (source == NULL) return;
m_Pos = source->m_Pos;
m_Layer = source->m_Layer;
m_Miroir = source->m_Miroir; // vue normale / miroir
m_NoShow = source->m_NoShow; // 0: visible 1: invisible
m_Type = source->m_Type; // 0: ref,1: val, autre = 2..255
m_Orient = source->m_Orient; // orientation en 1/10 degre
m_Pos0 = source->m_Pos0; // coord du debut du texte /ancre, orient 0
m_Size = source->m_Size;
m_Width = source->m_Width;
m_Text = source->m_Text;
}
/* supprime du chainage la structure Struct
les structures arrieres et avant sont chainees directement
*/
void TEXTE_MODULE::UnLink( void )
{
/* Modification du chainage arriere */
if( Pback )
{
if( Pback->m_StructType != TYPEMODULE)
{
Pback->Pnext = Pnext;
}
else /* Le chainage arriere pointe sur la structure "Pere" */
{
((MODULE*)Pback)->m_Drawings = Pnext;
}
}
/* Modification du chainage avant */
if( Pnext) Pnext->Pback = Pback;
Pnext = Pback = NULL;
}
/******************************************/
const char * TEXTE_MODULE:: GetText(void)
/******************************************/
{
return m_Text.GetData();
}
/******************************************/
int TEXTE_MODULE:: GetLength(void)
/******************************************/
{
return m_Text.Len();
}
/******************************************/
void TEXTE_MODULE:: SetWidth(int new_width)
/******************************************/
{
m_Width = new_width;
}
// mise a jour des coordonnées absolues pour affichage
void TEXTE_MODULE:: SetDrawCoord(void)
{
MODULE * Module = (MODULE *) m_Parent;
m_Pos = m_Pos0;
if ( Module == NULL ) return;
int angle = Module->m_Orient;
NORMALIZE_ANGLE_POS(angle);
RotatePoint( &m_Pos.x, &m_Pos.y, angle);
m_Pos.x += Module->m_Pos.x;
m_Pos.y += Module->m_Pos.y;
}
// mise a jour des coordonnées relatives au module
void TEXTE_MODULE:: SetLocalCoord(void)
{
MODULE * Module = (MODULE *) m_Parent;
if ( Module == NULL ) return;
m_Pos0.x = m_Pos.x - Module->m_Pos.x;
m_Pos0.y = m_Pos.y - Module->m_Pos.y;
int angle = Module->m_Orient;
NORMALIZE_ANGLE_POS(angle);
RotatePoint( &m_Pos0.x, &m_Pos0.y, -angle);
}
/* locate functions */
int TEXTE_MODULE:: Locate(const wxPoint & posref)
{
int mX, mY, dx, dy;
MODULE * Module = (MODULE *) m_Parent;
int angle = m_Orient;
if (Module) angle += Module->m_Orient;
dx = (m_Size.x * GetLength()) /2;
dy = m_Size.y / 2 ;
dx = ((dx * 10) / 9) + m_Width; /* Facteur de forme des lettres : 10/9 */
/* le point de reference est tourné de - angle
pour se ramener a un rectangle de reference horizontal */
mX = posref.x - m_Pos.x; mY = posref.y - m_Pos.y;
RotatePoint(&mX, &mY, - angle);
/* le point de reference est-il dans ce rectangle */
if( ( abs(mX) <= abs(dx) ) && ( abs(mY) <= abs(dy)) )
{
return 1;
}
return 0;
}
/******************************************************************************************/
void TEXTE_MODULE::Draw(WinEDA_DrawPanel * panel, wxDC * DC, wxPoint offset, int draw_mode)
/******************************************************************************************/
/* trace 1 texte de module
Utilise la police definie dans grfonte.h
(Se reporter a ce fichier pour les explications complementaires)
offset = offset de trace ( reference au centre du texte)
draw_mode = GR_OR, GR_XOR..
*/
{
int zoom;
int width, color, orient, miroir;
wxSize size;
const char * ptr;
wxPoint pos; // Centre du texte
PCB_SCREEN * screen;
WinEDA_BasePcbFrame * frame;
MODULE * Module = (MODULE *) m_Parent;
if ( panel == NULL ) return;
screen = (PCB_SCREEN *) panel->GetScreen();
frame = screen->GetParentPcbFrame();
zoom = screen->GetZoom();
pos.x = m_Pos.x - offset.x;
pos.y = m_Pos.y - offset.y;
size = m_Size;
orient = GetDrawRotation();
miroir = m_Miroir & 1 ; // = 0 si vu en miroir
ptr = GetText() ; /* ptr pointe 1er caractere du texte */
width = m_Width;
if( (frame->m_DisplayModText == FILAIRE) || ( (width/zoom) < L_MIN_DESSIN) )
width = 0;
GRSetDrawMode(DC, draw_mode);
/* trace du centre du texte */
if((g_AnchorColor & ITEM_NOT_SHOW) == 0 )
{
GRLine(&panel->m_ClipBox, DC,
pos.x - (2*zoom), pos.y,
pos.x + (2*zoom), pos.y, g_AnchorColor);
GRLine(&panel->m_ClipBox, DC,
pos.x, pos.y - (2*zoom),
pos.x, pos.y + (2*zoom), g_AnchorColor);
}
color = g_DesignSettings.m_LayerColor[Module->m_Layer];
if( Module && Module->m_Layer == CUIVRE_N) color = g_ModuleTextCUColor;
if( Module && Module->m_Layer == CMP_N) color = g_ModuleTextCMPColor;
if(m_NoShow) color = g_ModuleTextNOVColor;
/* Si le texte doit etre mis en miroir: modif des parametres */
if( miroir == 0 ) size.x = - size.x;
/* Trace du texte */
DrawGraphicText(panel, DC, pos , color, ptr,
orient, size, GR_TEXT_HJUSTIFY_CENTER, GR_TEXT_VJUSTIFY_CENTER, width);
}
/******************************************/
int TEXTE_MODULE::GetDrawRotation(void)
/******************************************/
/* Return text rotation for drawings and plotting
*/
{
int rotation;
MODULE * Module = (MODULE *) m_Parent;
rotation = m_Orient;
if ( Module ) rotation += Module->m_Orient;
NORMALIZE_ANGLE_POS(rotation);
// if( (rotation > 900 ) && (rotation < 2700 ) ) rotation -= 1800; // For angle = 0 .. 180 deg
while ( rotation > 900 ) rotation -= 1800; // For angle = -90 .. 90 deg
return rotation;
}
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
]
| [
[
[
1,
275
]
]
]
|
cc7fec331f82081b77de73e2d93e59f5789ef723 | 5fb3e802fbd84cdccc8fbd57f787b14d761fce90 | /Encoder.h | 1350467445e54ed444413adbb7f6b09e3c5a86dc | []
| no_license | adasta/AIRobot-Scanner | 4ede66ed7484cf1b36ee2d3424bb04157468d9c3 | 2e4edc8a9f37aad580024695341810cc3b1c874e | refs/heads/master | 2021-01-23T03:59:22.043860 | 2009-12-14T01:04:18 | 2009-12-14T01:04:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 368 | h | /*
* Encoder.h
*
* Created on: Dec 2, 2009
* Author: asher
*/
#ifndef ENCODER_H_
#define ENCODER_H_
class Encoder {
public:
Encoder();
int count();
void clearCount();
void update(char channelA, char channelB);
~Encoder();
private:
int priorA; //prior A value
int priorB;
int encoderCount;
};
#endif /* ENCODER_H_ */
| [
"asher@asher-mbp.(none)"
]
| [
[
[
1,
25
]
]
]
|
096ff49ad166f842f6f74e6d39642371e3a80098 | 16ba4fade5a6aa7f3f7c4bd73874df7ebed4477e | /examples/hp/calculator/src/arithmachine.h | e8d0d73f8c1044f5cab8c273e5e3f82681053a7f | []
| no_license | jleahred/maiquel-toolkit-cpp | f31304307d7da9af5ddeed73ffc8fcc0eceb926e | f19415a48a0d06ebe21b31aacc95da174c02d14f | refs/heads/master | 2020-05-01T14:11:48.263204 | 2011-02-09T22:01:00 | 2011-02-09T22:01:00 | 37,780,586 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,785 | h | #ifndef ARITHMACHINE_H
#define ARITHMACHINE_H
#include <string>
#include <vector>
#include <stack>
#include <map>
#include "support/signalslot.hpp"
#include "support/mtk_double.h"
/*
A r i t h M a c h i n e
______________________________
* Trabaja con datos tipo Double
* Puede trabajar por valor o por referencia
* Tiene una pila donde se pueden añadir los valores o referencias
* El montículo se accede por un string con el nombre de la variable
* Tiene un método para modificar de forma eficiente el montículo
* Cuando se escriba una referencia en el montículo y esta no exista
se asignará un espacio automáticamente.
No es necesaria ni permitida la reserva explícita previa
*/
// -----------------------------------
// D a t a
// -----------------------------------
struct Data
{
enum enDataType { dtValue, dtReference };
enDataType dataType ;
mtk::Double value ;
std::string reference ;
Data();
Data(const mtk::Double& val);
Data(const std::string& ref);
};
// -----------------------------------
// I n s t r u c t i o n
// -----------------------------------
enum enOperatorCode { ocPush
, ocFunct1
, ocFunct2
, ocCopyStackTop2Heap // copia el valor top del la pila en el montículo, no saca de la pila
};
struct Instruction
{
enOperatorCode operatorCode;
Data data;
Instruction(enOperatorCode _opcode, const Data& _data)
: operatorCode (_opcode), data(_data) {};
};
typedef std::vector<Instruction> t_program;
// -----------------------------------
// A r i t h M a c h i n e
// -----------------------------------
class ArithMachine : public mtk::SignalReceptor
{
typedef mtk::Signal<
const mtk::Double& /*param 1 */,
const mtk::Double& /*param 2 */,
mtk::Double& /*result */>
t_signalFunction2arity;
typedef mtk::Signal<
const mtk::Double& /*param 1 */,
mtk::Double& /*result */>
t_signalFunction1arity;
public:
void ResetMachine(void);
void PartialReset(void); // no borra el montículo
// para añadir instrucciones directamente
void AddInstruction (const Instruction& instruction );
void AddProgram (const t_program& _program);
// escribir directamente en la memoria
void WriteValueOnStack (const std::string& refName, const mtk::Double& val);
mtk::Double Eval(void);
void Run (void);
mtk::CountPtr<t_signalFunction1arity> RegisterFunction1Arity (const std::string& name);
mtk::CountPtr<t_signalFunction2arity> RegisterFunction2Arity (const std::string& name);
// se permite el acceso directo (externo) a la memoria por rendimiento y sencillez
mtk::Double GetValueFromHeap(const std::string& refName) const;
void SetValueInHeap (const std::string& refName, const mtk::Double& val);
private:
std::vector<Instruction> program ;
std::stack<Data> stack ;
std::map<std::string, mtk::Double> heap ;
std::map<std::string, mtk::CountPtr<t_signalFunction1arity> > functions1 ;
std::map<std::string, mtk::CountPtr<t_signalFunction2arity> > functions2 ;
mtk::Double StackTop(void); // si es una referencia, la resuelve y devuelve siempre un dato
mtk::Double StackPop(void); // además de devolver el dato, lo elimina de la pila
};
// -----------------------------------
// F u n c t i o n s _ B a s i c
// -----------------------------------
class Functions_Basic : public mtk::SignalReceptor
{
public:
Functions_Basic(ArithMachine& am);
private:
void UnnaryMinus( const mtk::Double& par,
mtk::Double& result);
void Add ( const mtk::Double& par1,
const mtk::Double& par2,
mtk::Double& result);
void Minus ( const mtk::Double& par1,
const mtk::Double& par2,
mtk::Double& result);
void Multiply ( const mtk::Double& par1,
const mtk::Double& par2,
mtk::Double& result);
void Divide ( const mtk::Double& par1,
const mtk::Double& par2,
mtk::Double& result);
};
// ------------------------------------------------
// A M _ A s e m b l e r
// * Le pasamos en una cadena de texto, o varias,
// el programa parcialmente compilado
//
// * Esta entrada es la salida de humbleParser (1er paso compilación)
//
// * Traduce cada línea de texto a una sentencia de ArithMachine
//
// * Lanza una señal con el programa generado para ArithMachine
// ------------------------------------------------
class AM_Asembler
{
public:
void Compile(std::string& code);
mtk::Signal<const t_program&> signalCompiledProgram;
private:
Instruction Compile(const std::string& code, const std::string& data) const;
};
#endif // ARITHMACHINE_H
| [
"none"
]
| [
[
[
1,
226
]
]
]
|
f37aa660e26143feaf03e42077e4ed95892dd97c | 6fd162d2cade2db745e68f11d7e9722a3855f033 | /Source/Common/S3UT/S3UTCameraManager.cpp | eaea002f2ed91938cad2c2d03ce120f207912a1c | []
| no_license | SenichiFSeiei/oursavsm | 8f418325bc9883bcb245e139dbd0249e72c18d78 | 379e77cab67b3b1423a4c6f480b664f79b03afa9 | refs/heads/master | 2021-01-10T21:00:52.797565 | 2010-04-27T13:18:19 | 2010-04-27T13:18:19 | 41,737,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,215 | cpp | //----------------------------------------------------------------------------------
// File: S3UTCameraManager.cpp
// Author: Baoguang Yang
//
// Copyright (c) 2009 _COMPANYNAME_ Corporation. All rights reserved.
//
//----------------------------------------------------------------------------------
#include <Winnls.h>
#include <DXUT.h>
#include "S3UTcamera.h"
#include "S3UTCameraManager.h"
#include <algorithm>
//#include <assert.h>
#define assert
void S3UTCameraManager::ConfigCameras( char *fileName )
{
char sCameraName[100];
char sCameraType[100];
memset( sCameraName, 0, sizeof(sCameraName) );
memset( sCameraType, 0, sizeof(sCameraType) );
FILE *fp = fopen(fileName,"r");
if( !fp )
printf("Fail to open %s and cameras could not be initialized, please double check if it exists.", fileName);
while( fscanf( fp, "%s %s", sCameraName, sCameraType ) > 0 )
{
char sPropertyName[100];
S3UTCamera *pCamera = new S3UTCamera();
if( strcmp( sCameraType, "light" ) == 0 )
pCamera->SetCamType( S3UTCamera::eLight );
else if( strcmp( sCameraType, "eye" ) == 0 )
pCamera->SetCamType( S3UTCamera::eEye );
else
pCamera->SetCamType( S3UTCamera::eUnknown );
pCamera->SetCamName( sCameraName );
int nCastShadow = 0;
assert(fscanf(fp,"%s %d", sPropertyName, &nCastShadow));
pCamera->SetCastShadow( nCastShadow == 1?true:false );
D3DXVECTOR3 vPosition;
D3DXVECTOR3 vLookAt;
assert(fscanf(fp,"%s %f %f %f", sPropertyName, &vPosition.x, &vPosition.y, &vPosition.z));
assert(fscanf(fp,"%s %f %f %f", sPropertyName, &vLookAt.x, &vLookAt.y, &vLookAt.z));
pCamera->SetViewParams(&vPosition, &vLookAt);
float lightSize = 0;
assert(fscanf(fp,"%s %f", sPropertyName, &lightSize));
pCamera->SetLightSize(lightSize);
float zNear = 0;
assert(fscanf(fp,"%s %f", sPropertyName, &zNear));
float zFar = 0;
assert(fscanf(fp,"%s %f", sPropertyName, &zFar));
float fieldOfView = 0;
assert(fscanf(fp,"%s %f", sPropertyName, &fieldOfView));
float aspectRatio = 0;
assert(fscanf(fp,"%s %f", sPropertyName, &aspectRatio));
pCamera->SetProjParams(fieldOfView, aspectRatio, zNear, zFar);
m_aPtrCameras.push_back(pCamera);
}
fclose(fp);
}
class DumpSingleCameraStatus
{
public:
DumpSingleCameraStatus( FILE *fp ) : m_pFile( fp ) {};
void operator() ( S3UTCamera *pCamera ) const
{
assert(fprintf(m_pFile,"%s\t",pCamera->GetCamName().c_str()));
if( pCamera->GetCamType() == S3UTCamera::eLight )
assert(fprintf(m_pFile,"light\n"));
else if( pCamera->GetCamType() == S3UTCamera::eEye )
assert(fprintf(m_pFile,"eye\n"));
else
assert(fprintf(m_pFile,"unknown\n"));
assert(fprintf(m_pFile,"CastShadow\t%d\n",pCamera->IsCastShadow()?1:0));
D3DXVECTOR3 vPosition = *pCamera->GetEyePt();
assert(fprintf(m_pFile,"Position\t%f %f %f\n",vPosition.x,vPosition.y,vPosition.z));
D3DXVECTOR3 vLookAt = *pCamera->GetLookAtPt();
assert(fprintf(m_pFile,"AtPosition\t%f %f %f\n",vLookAt.x,vLookAt.y,vLookAt.z));
float lightSize = pCamera->GetLightSize();
assert(fprintf(m_pFile,"Size\t%f\n",lightSize));
float zNear = pCamera->GetNearClip();
assert(fprintf(m_pFile,"ZNear\t%f\n",zNear));
float zFar = pCamera->GetFarClip();
assert(fprintf(m_pFile,"ZFar\t%f\n",zFar));
float fieldOfView = pCamera->GetFOV();
assert(fprintf(m_pFile,"FieldOfView\t%f\n",fieldOfView));
float aspectRatio = pCamera->GetAspectRatio();
assert(fprintf(m_pFile,"AspectRatio\t%f\n\n",aspectRatio));
}
private:
FILE *m_pFile;
};
void S3UTCameraManager::DumpCameraStatus( char *fileName ) const
{
char sCameraName[100];
char sCameraType[100];
memset( sCameraName, 0, sizeof(sCameraName) );
memset( sCameraType, 0, sizeof(sCameraType) );
FILE *fp = fopen(fileName,"w");
if( !fp )
printf("Fail to open %s and camera status could not be dumped, please double check if it exists.", fileName);
vector<S3UTCamera *>::const_iterator iter_begin = m_aPtrCameras.begin(), iter_end = m_aPtrCameras.end();
for_each(iter_begin,iter_end,DumpSingleCameraStatus(fp));
fclose(fp);
}
void S3UTCameraManager::Clear()
{
vector<S3UTCamera *>::const_iterator iter = m_aPtrCameras.begin(), iter_end = m_aPtrCameras.end();
for(;iter!=iter_end;++iter)
{
if( *iter )
delete (*iter);
}
}
S3UTCameraManager::~S3UTCameraManager()
{
Clear();
}
S3UTCamera* S3UTCameraManager::Eye( int num )
{
vector<S3UTCamera *>::const_iterator iter = m_aPtrCameras.begin(), iter_end = m_aPtrCameras.end();
int lightIdx = -1;
for(;iter!=iter_end;++iter)
{
if( (*iter)->GetCamType() == S3UTCamera::eEye )
{
++lightIdx;
if( num == lightIdx )
{
printf("Find the %d eye!\n", num);
return (*iter);
}
}
}
printf("Does not find the required eye, there are only %d eye(s) available, please double check the data file!\n", lightIdx+1);
return NULL;
}
class IsACameraOf
{
public:
IsACameraOf( S3UTCamera::CameraType camType ):m_tCamType(camType){};
bool operator() ( S3UTCamera *pCam ) const
{
return pCam->GetCamType() == m_tCamType;
}
private:
S3UTCamera::CameraType m_tCamType;
};
class IsAnActiveCameraOf
{
public:
IsAnActiveCameraOf( S3UTCamera::CameraType camType ):m_tCamType(camType){};
bool operator() ( S3UTCamera *pCam ) const
{
IsACameraOf isSuchCam( m_tCamType );
return isSuchCam( pCam )&&pCam->IsActive();
}
private:
S3UTCamera::CameraType m_tCamType;
};
S3UTCamera *S3UTCameraManager::ActiveEye()//the 1st active eye camera.
{
vector<S3UTCamera *>::iterator iter = find_if( m_aPtrCameras.begin(),m_aPtrCameras.end(),IsAnActiveCameraOf(S3UTCamera::eEye));
if( iter == m_aPtrCameras.end() )
iter = find_if( m_aPtrCameras.begin(),m_aPtrCameras.end(),IsACameraOf(S3UTCamera::eEye));
return (*iter);
}
void S3UTCameraManager::OnD3D10SwapChainResized( ID3D10Device* pDev10, IDXGISwapChain *pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
{
vector<S3UTCamera *>::const_iterator iter = m_aPtrCameras.begin(), iter_end = m_aPtrCameras.end();
for(;iter!=iter_end;++iter)
{
//this is not absolutely right. since, lights should have there own width and height,
//but it's OK, SetWindow only affects the mouse interaction with UI
( *iter )-> SetWindow(pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height);
}
}
S3UTCamera *S3UTCameraManager::Camera( int num )
{
if( num<0 || num>CameraCount() )
{
printf( "Invalid camera index, should be from 0 to %d.\n",CameraCount() );
return 0;
}
return m_aPtrCameras[num];
}
void S3UTCameraManager::SetupCameraUI( CDXUTDialog &camUI ) const
{
int charWidth = 5;
int textHeight = 22;
int colSpace = 10;
int fixItemCnt = 3;
D3DXCOLOR fontColor( 0.3f, 0.7f, 0.1f, 1.0f );
camUI.AddStatic(8, L"Light UI", 0, 0, 200, 22);
camUI.GetControl(8)->SetTextColor( fontColor );
camUI.AddCheckBox( 9, L"Dump Camera Settings", 80, 22, 200, 22, false);
camUI.GetControl(9)->SetTextColor( fontColor );
int camIdx = 0;
vector<S3UTCamera *>::const_iterator iter = m_aPtrCameras.begin(), iter_end = m_aPtrCameras.end();
for(;iter!=iter_end;++iter)
{
int textCursorX = 0;
int len = strlen((*iter)->GetCamName().c_str()) + 1;
int nwLen = MultiByteToWideChar(CP_ACP,0,(*iter)->GetCamName().c_str(),len,NULL,0);
TCHAR lpszCamName[256];
MultiByteToWideChar(CP_ACP,0,(*iter)->GetCamName().c_str(),len,lpszCamName,nwLen);
camUI.AddStatic( HANDLE_BASE+camIdx, lpszCamName, textCursorX*charWidth, (camIdx+fixItemCnt)*textHeight, 200, 22 );
camUI.GetControl(HANDLE_BASE+camIdx)->SetTextColor( fontColor );
textCursorX += colSpace;
if( (*iter)->GetCamType() == S3UTCamera::eEye )
camUI.AddStatic( HANDLE_BASE+camIdx, L"Eye", textCursorX*charWidth, (camIdx+fixItemCnt)*textHeight, 200, 22 );
else if( (*iter)->GetCamType() == S3UTCamera::eLight )
camUI.AddStatic( HANDLE_BASE+camIdx, L"Light", textCursorX*charWidth, (camIdx+fixItemCnt)*textHeight, 200, 22 );
camUI.GetControl(HANDLE_BASE+camIdx)->SetTextColor( fontColor );
textCursorX += 3*colSpace;
camUI.AddCheckBox( HANDLE_BASE+CameraCount()+camIdx, L"Active", textCursorX*charWidth, (camIdx+fixItemCnt)*textHeight, 100, 22, (*iter)->IsActive());
textCursorX += 2*colSpace;
camUI.AddCheckBox( HANDLE_BASE+2*CameraCount()+camIdx, L"Controllable", textCursorX*charWidth, (camIdx+fixItemCnt)*textHeight, 100, 22, (*iter)->IsControllable());
++camIdx;
}
}
void S3UTCameraManager::SyncToCameraUI(CDXUTDialog &camUI)
{
int camIdx = 0;
vector<S3UTCamera *>::iterator iter = m_aPtrCameras.begin(), iter_end = m_aPtrCameras.end();
for(;iter!=iter_end;++iter)
{
bool isActive = camUI.GetCheckBox( HANDLE_BASE+CameraCount()+camIdx )->GetChecked();
bool isControllable = camUI.GetCheckBox( HANDLE_BASE+2*CameraCount()+camIdx )->GetChecked();
(*iter)->SetActive( isActive );
(*iter)->SetControllable( isControllable );
++camIdx;
}
if( camUI.GetCheckBox( 9 )->GetChecked() )
DumpCameraStatus("DumpedCamStatus.txt");
}
void S3UTCameraManager::OnFrameMove( double fTime, float fElapsedTime, void* pUserContext )
{
vector<S3UTCamera *>::iterator iter = m_aPtrCameras.begin(), iter_end = m_aPtrCameras.end();
for(;iter!=iter_end;++iter)
{
if((*iter)->IsControllable())
(*iter)->FrameMove( fElapsedTime );
}
}
void S3UTCameraManager::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
vector<S3UTCamera *>::iterator iter = m_aPtrCameras.begin(), iter_end = m_aPtrCameras.end();
for(;iter!=iter_end;++iter)
{
if((*iter)->IsControllable())
(*iter)->HandleMessages( hWnd, uMsg, wParam, lParam );
}
}
void S3UTCameraManager::OnKeyboard(UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext)
{
vector<S3UTCamera *>::iterator iter = m_aPtrCameras.begin(), iter_end = m_aPtrCameras.end();
for(;iter!=iter_end;++iter)
{
if((*iter)->IsControllable())
(*iter)->OnKeyboard(nChar, bKeyDown, bAltDown, pUserContext);
}
}
//remember to write a *CORRECT* destructor
| [
"[email protected]"
]
| [
[
[
1,
305
]
]
]
|
e35e7872f2c6aa1760602804ff08d22a6d864df0 | be2e23022d2eadb59a3ac3932180a1d9c9dee9c2 | /AiModule/source/AiCenter.h | b15629f264b571c192f4274d34e4e069fe2211e0 | []
| 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 | GB18030 | C++ | false | false | 3,324 | h | #pragma once
#include "mycom.h"
#include "define.h"
#include "windows.h"
#include "i_mydb.h"
#include "autoptr.h"
#include "I_AiCenter.h"
#include "AiData.h"
enum NPCACTION{
// common
NPCACTION_TALK,
NPCACTION_DO_EMOTION,
NPCACTION_CHANGE_DIR,
// move
NPCACTION_CLOSE_TARGET,
NPCACTION_LEAVE_TARGET,
// buy
NPCACTION_CHGMAP_SHOP,
NPCACTION_FULL_ITEM,
NPCACTION_USE_ITEM,
// reborn
NPCACTION_REBORN,
// team
NPCACTION_TEAM_ALLY_JOIN,
NPCACTION_TEAM_ACCEPT_INVITE,
NPCACTION_TEAM_LEAVE,
NPCACTION_TEAM_CLOSE_LEADER,
// fight
NPCACTION_ATTACK_TARGET,
};
enum NPCEVENT{
NPCEVENT_TALK,
NPCEVENT_LOOK,
NPCEVENT_LEADER_LEAVE,
NPCEVENT_INVITE,
NPCEVENT_FOUND_LEADER,
NPCEVENT_NEED_CURE,
NPCEVENT_NEED_BUY_ITEM,
NPCEVENT_ITEM_EMPTY,
NPCEVENT_ATTACK_TARGET,
NPCEVENT_KILL_TARGET,
NPCEVENT_FOUND_MONSTER,
NPCEVENT_USER_CURE,
};
// 首次调用Create()时,可初始化nTimeOfLife为0。每次存盘时保存GetTimeOfLife()值供下次调用。
class CAiCenter : IAiCenter
{
NO_COPY(CAiCenter)
protected:
CAiCenter();
virtual ~CAiCenter();
public: // interface
static IAiCenter* CreateNew() { return new CAiCenter; }
protected:
virtual void Release() { delete this; }
virtual bool Create(IAiCenterOwner* pOwner, IDatabase* pDb, const Array<String>& setGameFunction, const Array<String>& setGameAction, int nTimeOfLife);
virtual void OnTimer();
virtual void Persistent(IDatabase* pDb);
virtual void AddFact(StringRef strFact, int nPriority);
virtual bool FetchAction(int* pidxAction, VarTypeSet* psetParam);
virtual int GetTimeOfLife() const { return m_nNow; }
// virtual bool MatchParam(VarTypeSetRef setFactParam, VarTypeSetRef setRuleParam, ARGUMENT_SET* psetArgument);
virtual int Now() const { return m_nNow; }
protected:
void ClearInvalidRule();
void Thinking(int nStep);
bool ProcessRule(const CRuleObj* pRule);
bool ProcessRuleNest(bool bLogicNot, OBJID idFact, VarTypeSetRef setParam, ARGUMENT_SET& setArgument, const CRuleObj* pRule, CFactArray::ConstIterator iterFact);
bool CallFunction(OBJID idFact, VarTypeSetRef setParam, ARGUMENT_SET* psetArgument);
public: // const
void ClearAlikeAction(CFactRef cPattern);
bool ProcessResult(CFactRef result, CFactRef pattern, int nPriority, ARGUMENT_SET_REF setArgument);
CSymbolTable* QuerySymbolTable() { return m_pSymbolTable; }
IAiCenterOwner* QueryAgent() { return m_pOwner; }
protected:
bool IsFunction(OBJID idFact) { return idFact >= SYSTEM_FUNCTION_ID_BEGIN && idFact < SYSTEM_FUNCTION_ID_END; }
bool IsFactFunction(OBJID idFact) { return idFact >= GAME_FUNCTION_ID_BEGIN && idFact < GAME_FUNCTION_ID_END; }
bool IsAction(OBJID idFact) { return idFact >= GAME_ACTION_ID_BEGIN && idFact < GAME_ACTION_ID_END; }
protected: // attr
bool InsteadParam(VarTypeSet* pParam, ARGUMENT_SET_REF setArgument);
CJavaObj<CRuleSet> m_pRuleSet;
CJavaObj<CFactSet> m_pFactSet;
CFactArray m_setAction;
IAiCenterOwner* m_pOwner;
int m_nNow;
CJavaObj<CSymbolTable> m_pSymbolTable;
protected: // ctrl
bool m_bDumpRule; // for debug
int m_nNewPriority; enum { PRIORITY_NONE = -1 }; // PRIORITY_NONE for invalid
}; | [
"rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1"
]
| [
[
[
1,
108
]
]
]
|
e438a4348d178eec15882f86a818326c80dbda3a | a7ead79a090d7d83eabc22d7ec633368de06b989 | /qUAck/qUAck-win32.cpp | 116ecfbc1d136be7d6f26d8cbbaa34c5ee143c42 | []
| no_license | rjp/qUAck | 0fd7a189c41cb30363bea5947816c9c234f40169 | 78216295097806938c792466eab509460f9cf33a | refs/heads/master | 2020-06-06T14:34:41.579463 | 2010-08-25T11:01:29 | 2010-08-25T11:01:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,444 | cpp | /*
** UNaXcess Conferencing System
** (c) 1998 Michael Wood ([email protected])
**
** Concepts based on Bradford UNaXcess (c) 1984-87 Brandon S Allbery
** Extensions (c) 1989, 1990 Andrew G Minter
** Manchester UNaXcess extensions by Rob Partington, Gryn Davies,
** Michael Wood, Andrew Armitage, Francis Cook, Brian Widdas
**
** The look and feel was reproduced. No code taken from the original
** UA was someone else's inspiration. Copyright and 'nuff respect due
**
** CmdIO-win32.cpp: Implementation of Windows specific I/O functions
*/
#include <winsock2.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <process.h>
#include "EDF/EDF.h"
#include "Conn/EDFConn.h"
#include "CmdIO.h"
#include "CmdIO-common.h"
#include "CmdInput.h"
#include "CmdMenu.h"
#include "qUAck.h"
#define MAX_EVENTS 200
#define ISRETURN(x) (x == '\r' || x == '\n' ? '-' : x)
// char *m_szClientName = NULL;
// char m_szClientName[64];
UINT m_iConsoleOutput = 0;
int m_iDefBackground = 0, m_iBackground = m_iDefBackground, m_iDefForeground = FOREGROUND_INTENSITY + FOREGROUND_RED + FOREGROUND_GREEN + FOREGROUND_BLUE, m_iForeground = m_iDefForeground;
char *m_szBrowser = NULL;
bool m_bBrowserWait = false;
// char *m_szEditor = NULL;
CmdInput *CmdInputLoop(int iMenuStatus, CmdInput *pInput, byte *pcInput, byte **pszInput);
/* char *CLIENT_NAME()
{
// if(m_szClientName == NULL)
{
// m_szClientName = new char[20];
sprintf(m_szClientName, "%s v%s (Win32)", CLIENT_BASE, CLIENT_VERSION);
}
return m_szClientName;
} */
char *CLIENT_SUFFIX()
{
return "";
}
char *CLIENT_PLATFORM()
{
return " (Win32)";
}
void CmdStartup(int iSignal)
{
BOOL bResult = 0;
m_iConsoleOutput = GetConsoleOutputCP();
bResult = SetConsoleOutputCP(CP_UTF8);
if(bResult == 0)
{
debug("CmdStartup code page set failed %d\n", GetLastError());
}
CmdReset(0);
}
void CmdReset(int iSignal)
{
// COORD sCoords;
// sCoords = GetLargestConsoleWindowSize(GetStdHandle(STD_OUTPUT_HANDLE));
// debug("CliWindow window size %d %d\n", sCoords.X, sCoords.Y);
CONSOLE_SCREEN_BUFFER_INFO sWindow;
if(GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &sWindow) != 0)
{
// debug("CliWindow buffer size %d %d\n", sWindow.dwSize.X, sWindow.dwSize.Y);
CmdWidth(sWindow.dwSize.X);
CmdHeight(sWindow.dwSize.Y);
m_iDefBackground = (sWindow.wAttributes & BACKGROUND_BLUE)
+ (sWindow.wAttributes & BACKGROUND_GREEN)
+ (sWindow.wAttributes & BACKGROUND_RED)
+ (sWindow.wAttributes & BACKGROUND_INTENSITY);
m_iBackground = m_iDefBackground;
m_iForeground = (sWindow.wAttributes & FOREGROUND_BLUE)
+ (sWindow.wAttributes & FOREGROUND_GREEN)
+ (sWindow.wAttributes & FOREGROUND_RED)
+ (sWindow.wAttributes & FOREGROUND_INTENSITY);
m_iDefForeground = m_iForeground;
// printf("CmdIOStartup default colours fg=%d,bg=%d\n", m_iForeground, m_iBackground);
}
}
void CmdShutdown(int iSignal)
{
BOOL bResult = 0;
bResult = SetConsoleOutputCP(m_iConsoleOutput);
if(bResult == 0)
{
debug("CmdShutdown code page set failed %d\n", GetLastError());
}
}
int CmdType()
{
return 0;
}
bool CmdLocal()
{
return true;
}
char *CmdUsername()
{
return NULL;
}
// Input functions
int CmdInputGet(byte **pCurrBuffer, int iBufferLen)
{
STACKTRACE
int iEventNum = 0, iCharNum = 0;
double dTick = 0;
DWORD dwNumEvents = 0, dwReadEvents = 0;
byte cReturn = '\0', *pBuffer = NULL;
INPUT_RECORD *pEvents = NULL;
if(WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 50) != WAIT_OBJECT_0)
{
return iBufferLen;
}
// Count waiting events
while(GetNumberOfConsoleInputEvents(GetStdHandle(STD_INPUT_HANDLE), &dwNumEvents) != 0 && dwNumEvents > 0)
{
dTick = gettick();
// Check event type
if(dwNumEvents >= MAX_EVENTS)
{
debug(DEBUGLEVEL_WARN, "CmdInput %d console input events, resizing\n", dwNumEvents);
dwNumEvents = MAX_EVENTS;
}
pEvents = new INPUT_RECORD[dwNumEvents];
if(ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE), pEvents, dwNumEvents, &dwReadEvents) != 0)
{
if(iBufferLen > 0)
{
// memprint(debugfile(), "CmdInput sub-total buffer", m_pBuffer, m_iBufferLen, -1, false, -1, 50, false);
pBuffer = new byte[iBufferLen + dwReadEvents];
memcpy(pBuffer, (*pCurrBuffer), iBufferLen);
delete[] (*pCurrBuffer);
// debug("CmdInputGet check %d events at offset %d\n", dwReadEvents, m_iBufferLen);
}
else
{
pBuffer = new byte[dwReadEvents];
}
*pCurrBuffer = pBuffer;
/* if(m_iBufferLen > 0)
{
debug("CmdInputGet put %d events at offset %d\n", dwReadEvents, m_iBufferLen);
} */
for(iEventNum = 0; iEventNum < dwReadEvents; iEventNum++)
{
if(pEvents[iEventNum].EventType == KEY_EVENT)
{
if(pEvents[iEventNum].Event.KeyEvent.bKeyDown == TRUE)
{
if(mask(pEvents[iEventNum].Event.KeyEvent.dwControlKeyState, ENHANCED_KEY) == true)
{
if(pEvents[iEventNum].Event.KeyEvent.wVirtualKeyCode == VK_RETURN)
{
pBuffer[iBufferLen++] = '\r';
iCharNum++;
}
if(pEvents[iEventNum].Event.KeyEvent.wVirtualKeyCode == VK_NEXT)
{
pBuffer[iBufferLen++] = '\004';
iCharNum++;
}
if(pEvents[iEventNum].Event.KeyEvent.wVirtualKeyCode == VK_END)
{
pBuffer[iBufferLen++] = '\005';
iCharNum++;
}
if(pEvents[iEventNum].Event.KeyEvent.wVirtualKeyCode == VK_HOME)
{
pBuffer[iBufferLen++] = '\001';
iCharNum++;
}
if(pEvents[iEventNum].Event.KeyEvent.wVirtualKeyCode == VK_LEFT)
{
pBuffer[iBufferLen++] = '\002';
iCharNum++;
}
if(pEvents[iEventNum].Event.KeyEvent.wVirtualKeyCode == VK_UP)
{
pBuffer[iBufferLen++] = '\020';
iCharNum++;
}
if(pEvents[iEventNum].Event.KeyEvent.wVirtualKeyCode == VK_RIGHT)
{
pBuffer[iBufferLen++] = '\006';
iCharNum++;
}
if(pEvents[iEventNum].Event.KeyEvent.wVirtualKeyCode == VK_DOWN)
{
pBuffer[iBufferLen++] = '\016';
iCharNum++;
}
else if(pEvents[iEventNum].Event.KeyEvent.wVirtualKeyCode == VK_DELETE)
{
pBuffer[iBufferLen++] = '\004';
iCharNum++;
}
else
{
debug(DEBUGLEVEL_INFO, "CmdInputGet enhanced key %d\n", pEvents[iEventNum].Event.KeyEvent.wVirtualKeyCode);
}
}
else if(mask(pEvents[iEventNum].Event.KeyEvent.dwControlKeyState, LEFT_ALT_PRESSED) == false &&
mask(pEvents[iEventNum].Event.KeyEvent.dwControlKeyState, RIGHT_ALT_PRESSED) == false)
{
debug(DEBUGLEVEL_DEBUG, "CmdInputGet character %c [%d]\n", pEvents[iEventNum].Event.KeyEvent.uChar.UnicodeChar, pEvents[iEventNum].Event.KeyEvent.uChar.UnicodeChar);
if(pEvents[iEventNum].Event.KeyEvent.uChar.AsciiChar > 0)
{
debug(DEBUGLEVEL_DEBUG, "CmdInputGet ASCII character '%c'\n", ISRETURN(pEvents[iEventNum].Event.KeyEvent.uChar.AsciiChar));
pBuffer[iBufferLen++] = pEvents[iEventNum].Event.KeyEvent.uChar.AsciiChar;
iCharNum++;
}
else
{
debug(DEBUGLEVEL_DEBUG, "CmdInputGet unicode character '%c' [%d]\n", ISRETURN(pEvents[iEventNum].Event.KeyEvent.uChar.UnicodeChar), pEvents[iEventNum].Event.KeyEvent.uChar.UnicodeChar);
}
}
else
{
debug(DEBUGLEVEL_DEBUG, "CmdInputGet ALT character '%c' [%d]\n", ISRETURN(pEvents[iEventNum].Event.KeyEvent.uChar.UnicodeChar), pEvents[iEventNum].Event.KeyEvent.uChar.UnicodeChar);
}
}
else
{
// debug(DEBUGLEVEL_DEBUG, "CmdInputGet key up character '%c' [%d]\n", ISRETURN(pEvents[iEventNum].Event.KeyEvent.uChar.UnicodeChar), pEvents[iEventNum].Event.KeyEvent.uChar.UnicodeChar);
}
}
}
/* if(iCharNum > 0)
{
debug(DEBUGLEVEL_DEBUG, "CmdInputGet added %d characters from %d events in %ld ms\n", iCharNum, dwReadEvents, tickdiff(dTick));
} */
}
else
{
// debug(DEBUGLEVEL_ERROR, "CmdInputGet read console failed, %d\n", GetLastError());
MsgError("CmdInputGet read console failed");
}
delete[] pEvents;
}
return iBufferLen;
}
bool CmdInputCheck(byte cOption)
{
return true;
}
// Output functions
int CmdOutput(const byte *pData, int iDataLen, bool bSingleChar, bool bUTF8)
{
int iDataPos = 0;
DWORD dWritten = 0;
if(iDataLen == 0)
{
return 0;
}
// memprint(debugfile(), "CmdOutput", pData, iDataLen);
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), pData, iDataLen, &dWritten, NULL);
for(iDataPos = 0; iDataPos < iDataLen; iDataPos++)
{
if(pData[iDataPos] != '\007' && pData[iDataPos] != '\013')
{
// WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), pData + iDataPos, 1, &dWritten, NULL);
}
}
return iDataLen;
}
// Other functions
void CmdRedraw(bool bFull)
{
}
void CmdBack(int iNumChars)
{
CONSOLE_SCREEN_BUFFER_INFO cBufferInfo;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cBufferInfo);
// debug("CmdBack was %d, %d", cBufferInfo.dwCursorPosition.X, cBufferInfo.dwCursorPosition.Y);
if(iNumChars > cBufferInfo.dwCursorPosition.X)
{
cBufferInfo.dwCursorPosition.X = 0;
}
else
{
cBufferInfo.dwCursorPosition.X -= iNumChars;
}
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cBufferInfo.dwCursorPosition);
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cBufferInfo);
// debug(". now %d, %d\n", cBufferInfo.dwCursorPosition.X, cBufferInfo.dwCursorPosition.Y);
}
void CmdReturn()
{
CONSOLE_SCREEN_BUFFER_INFO cBufferInfo;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cBufferInfo);
// debug("CmdReturn was %d, %d / %d x %d", cBufferInfo.dwCursorPosition.X, cBufferInfo.dwCursorPosition.Y, cBufferInfo.dwSize.X, cBufferInfo.dwSize.Y);
// printf("**");
cBufferInfo.dwCursorPosition.X = 0;
if(cBufferInfo.dwCursorPosition.Y == cBufferInfo.dwSize.Y - 1)
{
// printf("||");
// debug(", scroll");
SMALL_RECT srctScrollRect, srctClipRect;
CHAR_INFO chiFill;
COORD coordDest;
// The scrolling rectangle is the bottom 15 rows of the screen buffer
srctScrollRect.Top = cBufferInfo.dwSize.Y - cBufferInfo.dwSize.Y + 1;
srctScrollRect.Bottom = cBufferInfo.dwSize.Y - 1;
srctScrollRect.Left = 0;
srctScrollRect.Right = cBufferInfo.dwSize.X - 1;
// The destination for the scroll rectangle is one row up.
coordDest.X = 0;
coordDest.Y = cBufferInfo.dwSize.Y - cBufferInfo.dwSize.Y;
// The clipping rectangle is the same as the scrolling rectangle.
// The destination row is left unchanged.
srctClipRect = srctScrollRect;
// Fill the bottom row with green blanks.
chiFill.Attributes = m_iBackground;
chiFill.Char.AsciiChar = ' ';
// Scroll up one line.
ScrollConsoleScreenBuffer(
GetStdHandle(STD_OUTPUT_HANDLE), // screen buffer handle
&srctScrollRect, // scrolling rectangle
&srctClipRect, // clipping rectangle
coordDest, // top left destination cell
&chiFill); // fill character and color
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cBufferInfo.dwCursorPosition);
}
else
{
cBufferInfo.dwCursorPosition.Y++;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cBufferInfo.dwCursorPosition);
}
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cBufferInfo);
// debug(". now %d, %d\n", cBufferInfo.dwCursorPosition.X, cBufferInfo.dwCursorPosition.Y);
// printf("**");
}
void CmdAttr(char cColour)
{
int iAttr = 0;
if(cColour == '0')
{
iAttr = m_iForeground;
}
else if(cColour == '1')
{
iAttr = m_iForeground + FOREGROUND_INTENSITY;
}
else
{
switch(cColour)
{
case 'a':
case 'A':
iAttr = 0;
break;
case 'r':
case 'R':
iAttr = FOREGROUND_RED;
break;
case 'g':
case 'G':
iAttr = FOREGROUND_GREEN;
break;
case 'y':
case 'Y':
iAttr = FOREGROUND_RED | FOREGROUND_GREEN;
break;
case 'b':
case 'B':
iAttr = FOREGROUND_BLUE;
break;
case 'm':
case 'M':
iAttr = FOREGROUND_RED | FOREGROUND_BLUE;
break;
case 'c':
case 'C':
iAttr = FOREGROUND_GREEN | FOREGROUND_BLUE;
break;
case 'w':
case 'W':
iAttr = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
}
if(isupper(cColour))
{
iAttr += FOREGROUND_INTENSITY;
}
}
iAttr += m_iBackground;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), iAttr);
}
void CmdForeground(char cColour)
{
// printf("CmdForeground %c\n", cColour);
switch(cColour)
{
case '\0':
m_iForeground = m_iDefForeground;
break;
case 'a':
m_iForeground = 0;
break;
case 'r':
case 'R':
m_iForeground = FOREGROUND_RED;
break;
case 'g':
case 'G':
m_iForeground = FOREGROUND_GREEN;
break;
case 'y':
case 'Y':
m_iForeground = FOREGROUND_RED | FOREGROUND_GREEN;
break;
case 'b':
case 'B':
m_iForeground = FOREGROUND_BLUE;
break;
case 'm':
case 'M':
m_iForeground = FOREGROUND_RED | FOREGROUND_BLUE;
break;
case 'c':
case 'C':
m_iForeground = FOREGROUND_GREEN | FOREGROUND_BLUE;
break;
case 'w':
case 'W':
m_iForeground = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
}
if(isupper(cColour))
{
m_iForeground += FOREGROUND_INTENSITY;
}
}
void CmdBackground(char cColour)
{
// printf("CmdBackground %c\n", cColour);
switch(cColour)
{
case '\0':
m_iBackground = m_iDefBackground;
break;
case 'a':
m_iBackground = 0;
break;
case 'r':
case 'R':
m_iBackground = BACKGROUND_RED;
break;
case 'g':
case 'G':
m_iBackground = BACKGROUND_GREEN;
break;
case 'y':
case 'Y':
m_iBackground = BACKGROUND_RED | BACKGROUND_GREEN;
break;
case 'b':
case 'B':
m_iBackground = BACKGROUND_BLUE;
break;
case 'm':
case 'M':
m_iBackground = BACKGROUND_RED | BACKGROUND_BLUE;
break;
case 'c':
case 'C':
m_iBackground = BACKGROUND_GREEN | BACKGROUND_BLUE;
break;
case 'w':
case 'W':
m_iBackground = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE;
}
if(isupper(cColour))
{
m_iBackground += BACKGROUND_INTENSITY;
}
}
void CmdBeep()
{
MessageBeep(MB_ICONQUESTION);
}
void CmdWait()
{
Sleep(200);
}
bool ProxyHost(EDF *pEDF)
{
return false;
}
void CmdRun(const char *szProgram, bool bWait, const char *szArgs)
{
char szError[500];
long lRet;
lRet = (long)ShellExecute(GetFocus(), NULL, szProgram, szArgs, NULL, SW_SHOWNORMAL);
if(lRet <= 32)
{
wsprintf(szError, "CmdRun error %d executing %s (URI %s)", lRet, szProgram, szArgs);
MessageBox(GetFocus(), szError, "qUAck", MB_ICONSTOP | MB_OK);
}
}
int CmdPID()
{
return getpid();
}
bool CmdBrowser(char *szBrowser, bool bWait)
{
m_bBrowserWait = bWait;
char szFileType[10];
char szCommandLine[100];
long lSize = 0;
HKEY hRegKey = NULL;
if(szBrowser != NULL)
{
m_szBrowser = strmk(szBrowser);
}
if(RegOpenKey(HKEY_CLASSES_ROOT, ".htm", &hRegKey) != ERROR_SUCCESS)
{
if(szBrowser != NULL)
{
szBrowser[0] = '\0';
}
return false;
}
lSize = sizeof(szFileType);
RegQueryValue(hRegKey, NULL, szFileType, &lSize);
RegCloseKey(hRegKey);
if(RegOpenKey(HKEY_CLASSES_ROOT, szFileType, &hRegKey) != ERROR_SUCCESS)
{
if(szBrowser != NULL)
{
szBrowser[0] = '\0';
}
return false;
}
lSize = sizeof(szCommandLine);
RegQueryValue(hRegKey, "shell\\open\\command", szCommandLine, &lSize);
RegCloseKey(hRegKey);
m_szBrowser = new char[strlen(szCommandLine)];
int iCommandLine = 0, iBrowser = 0;
if(szCommandLine[0] == '"')
{
iCommandLine++;
while(szCommandLine[iCommandLine] != '\0' && szCommandLine[iCommandLine] != '"')
{
m_szBrowser[iBrowser] = szCommandLine[iCommandLine];
iCommandLine++;
iBrowser++;
}
}
else
{
while(szCommandLine[iCommandLine] != 0 && szCommandLine[iCommandLine] != ' ')
{
if(szCommandLine[iCommandLine] != '\"' && szCommandLine[iCommandLine] != '\'')
{
m_szBrowser[iBrowser] = szCommandLine[iCommandLine];
iBrowser++;
}
iCommandLine++;
}
}
m_szBrowser[iBrowser] = '\0';
return true;
}
char *CmdBrowser()
{
return m_szBrowser;
}
bool CmdBrowse(const char *szURI)
{
CmdRun(m_szBrowser, m_bBrowserWait, szURI);
return true;
}
bool CmdOpen(const char *szFilename)
{
char szError[500];
long lRet;
if(CmdYesNo("Open now", true) == true)
{
lRet = (long)ShellExecute(GetFocus(), NULL, szFilename, NULL, NULL, SW_SHOWNORMAL);
if(lRet <= 32)
{
wsprintf(szError, "Error %d opening %s", lRet, szFilename);
MessageBox(GetFocus(), szError, "qUAck", MB_ICONSTOP | MB_OK);
return false;
}
}
return true;
}
char CmdDirSep()
{
return '\\';
}
char *CmdText(int iOptions, const char *szInit, CMDFIELDSFUNC pFieldsFunc, EDF *pData)
{
STACKTRACE
char *szInput = NULL, *szTempFile = NULL;
FILE *fFile = NULL;
int iFile = 0;
CmdInput *pInput = NULL;
int iFork = 0, iReturn = -1;
if(CmdEditor() != NULL && mask(iOptions, CMD_LINE_EDITOR) == true)
{
szTempFile = tempnam("c:\\", "qUAck");
// debug("CmdText temp file %s\n", szTempFile);
fFile = fopen(szTempFile, "w");
if(fFile != NULL)
{
fclose(fFile);
/* szFile = (char *)FileRead(szTempFile);
debug("CmdText temp file '%s'\n", szFile);
delete[] szFile; */
// debug("CmdText spawning %s [%s]\n", m_szEditor, szTempFile);
iReturn = spawnl(_P_WAIT, CmdEditor(), CmdEditor(), szTempFile, NULL);
if(iReturn != -1)
{
debug(DEBUGLEVEL_DEBUG, "CmdText spawn return %d\n", iReturn);
}
else
{
debug(DEBUGLEVEL_ERR, "CmdText spawn error, %s\n", strerror(errno));
}
}
STACKTRACEUPDATE
if(iReturn != -1)
{
if(CmdYesNo("Send message", true) == true)
{
szInput = (char *)FileRead(szTempFile);
debug(DEBUGLEVEL_DEBUG, "CmdText temp file '%s'\n", szInput);
}
}
}
if(iReturn == -1)
{
STACKTRACEUPDATE
if(pFieldsFunc != NULL)
{
debug(DEBUGLEVEL_DEBUG, "CmdText fields %p %p\n", pFieldsFunc, pData);
pInput = new CmdInput(pFieldsFunc, pData);
}
else
{
pInput = new CmdInput(NULL, CmdWidth(), CMD_LINE_MULTI | iOptions, szInit);
}
CmdInputLoop(-1, pInput, NULL, (byte **)&szInput);
delete pInput;
}
return szInput;
}
| [
"[email protected]"
]
| [
[
[
1,
793
]
]
]
|
28c7930925ad40868082cd20cece0bf8a0938845 | f8b364974573f652d7916c3a830e1d8773751277 | /emulator/allegrex/instructions/VCMOVF.h | 489dd2828e3a84221f8aec8bbcca64cecee0b810 | []
| no_license | lemmore22/pspe4all | 7a234aece25340c99f49eac280780e08e4f8ef49 | 77ad0acf0fcb7eda137fdfcb1e93a36428badfd0 | refs/heads/master | 2021-01-10T08:39:45.222505 | 2009-08-02T11:58:07 | 2009-08-02T11:58:07 | 55,047,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,049 | h | template< > struct AllegrexInstructionTemplate< 0xd2a80000, 0xfff80000 > : AllegrexInstructionUnknown
{
static AllegrexInstructionTemplate &self()
{
static AllegrexInstructionTemplate insn;
return insn;
}
static AllegrexInstruction *get_instance()
{
return &AllegrexInstructionTemplate::self();
}
virtual AllegrexInstruction *instruction(u32 opcode)
{
return this;
}
virtual char const *opcode_name()
{
return "VCMOVF";
}
virtual void interpret(Processor &processor, u32 opcode);
virtual void disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment);
protected:
AllegrexInstructionTemplate() {}
};
typedef AllegrexInstructionTemplate< 0xd2a80000, 0xfff80000 >
AllegrexInstruction_VCMOVF;
namespace Allegrex
{
extern AllegrexInstruction_VCMOVF &VCMOVF;
}
#ifdef IMPLEMENT_INSTRUCTION
AllegrexInstruction_VCMOVF &Allegrex::VCMOVF =
AllegrexInstruction_VCMOVF::self();
#endif
| [
"[email protected]"
]
| [
[
[
1,
41
]
]
]
|
a54d7515e3785fa1560360c850d626f620d9d626 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/OggVorbisLib/symbian/tremor/synthesis.cpp | 8d7520489371047cde8eb5943168f258a4e5b0a7 | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,528 | cpp | /********************************************************************
* *
* THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. *
* *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2003 *
* BY THE Xiph.Org FOUNDATION http://www.xiph.org/ *
* *
********************************************************************
function: single-block PCM synthesis
********************************************************************/
#include "ogg.h"
#include <stdio.h>
#include "ivorbiscodec.h"
#include "codec_internal.h"
#include "registry.h"
#include "misc.h"
#include "os.h"
#include "block.h"
int vorbis_synthesis(vorbis_block *vb,ogg_packet *op,int decodep){
vorbis_dsp_state *vd=vb->vd;
private_state *b=(private_state *)vd->backend_state;
vorbis_info *vi=vd->vi;
codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
oggpack_buffer *opb=&vb->opb;
int type,mode,i;
/* first things first. Make sure decode is ready */
_vorbis_block_ripcord(vb);
oggpack_readinit(opb,op->packet);
/* Check the packet type */
if(oggpack_read(opb,1)!=0){
/* Oops. This is not an audio data packet */
return(OV_ENOTAUDIO);
}
/* read our mode and pre/post windowsize */
mode=oggpack_read(opb,b->modebits);
if(mode==-1)return(OV_EBADPACKET);
vb->mode=mode;
vb->W=ci->mode_param[mode]->blockflag;
if(vb->W){
vb->lW=oggpack_read(opb,1);
vb->nW=oggpack_read(opb,1);
if(vb->nW==-1) return(OV_EBADPACKET);
}else{
vb->lW=0;
vb->nW=0;
}
/* more setup */
vb->granulepos=op->granulepos;
vb->sequence=op->packetno-3; /* first block is third packet */
vb->eofflag=op->e_o_s;
if(decodep){
/* alloc pcm passback storage */
vb->pcmend=ci->blocksizes[vb->W];
vb->pcm=(ogg_int32_t **)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
for(i=0;i<vi->channels;i++)
vb->pcm[i]=(ogg_int32_t *)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
/* unpack_header enforces range checking */
type=ci->map_type[ci->mode_param[mode]->mapping];
return(_mapping_P[type]->inverse(vb,b->mode[mode]));
}else{
/* no pcm */
vb->pcmend=0;
vb->pcm=NULL;
return(0);
}
}
long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
oggpack_buffer opb;
int mode;
oggpack_readinit(&opb,op->packet);
/* Check the packet type */
if(oggpack_read(&opb,1)!=0){
/* Oops. This is not an audio data packet */
return(OV_ENOTAUDIO);
}
{
int modebits=0;
int v=ci->modes;
while(v>1){
modebits++;
v>>=1;
}
/* read our mode and pre/post windowsize */
mode=oggpack_read(&opb,modebits);
}
if(mode==-1)return(OV_EBADPACKET);
return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
}
| [
"[email protected]"
]
| [
[
[
1,
113
]
]
]
|
721c9a7271098ffd2e1207cce03684ca70e42fdc | 74e7667ad65cbdaa869c6e384fdd8dc7e94aca34 | /MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/corlib_native_System_Threading_Thread_mshl.cpp | 710c92ed9053a85b48f0cc518a454e407abd2e01 | [
"BSD-3-Clause",
"OpenSSL",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | gezidan/NETMF-LPC | 5093ab223eb9d7f42396344ea316cbe50a2f784b | db1880a03108db6c7f611e6de6dbc45ce9b9adce | refs/heads/master | 2021-01-18T10:59:42.467549 | 2011-06-28T08:11:24 | 2011-06-28T08:11:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,048 | cpp | //-----------------------------------------------------------------------------
//
// ** DO NOT EDIT THIS FILE! **
// This file was generated by a tool
// re-running the tool will overwrite this file.
//
//-----------------------------------------------------------------------------
#include "corlib_native.h"
#include "corlib_native_System_Threading_Thread.h"
using namespace System::Threading;
HRESULT Library_corlib_native_System_Threading_Thread::_ctor___VOID__SystemThreadingThreadStart( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack );
FAULT_ON_NULL(pMngObj);
UNSUPPORTED_TYPE param0;
TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 1, param0 ) );
Thread::_ctor( pMngObj, param0, hr );
TINYCLR_CHECK_HRESULT( hr );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Threading_Thread::Start___VOID( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack );
FAULT_ON_NULL(pMngObj);
Thread::Start( pMngObj, hr );
TINYCLR_CHECK_HRESULT( hr );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Threading_Thread::Abort___VOID( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack );
FAULT_ON_NULL(pMngObj);
Thread::Abort( pMngObj, hr );
TINYCLR_CHECK_HRESULT( hr );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Threading_Thread::Suspend___VOID( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack );
FAULT_ON_NULL(pMngObj);
Thread::Suspend( pMngObj, hr );
TINYCLR_CHECK_HRESULT( hr );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Threading_Thread::Resume___VOID( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack );
FAULT_ON_NULL(pMngObj);
Thread::Resume( pMngObj, hr );
TINYCLR_CHECK_HRESULT( hr );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Threading_Thread::get_Priority___SystemThreadingThreadPriority( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack );
FAULT_ON_NULL(pMngObj);
INT32 retVal = Thread::get_Priority( pMngObj, hr );
TINYCLR_CHECK_HRESULT( hr );
SetResult_INT32( stack, retVal );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Threading_Thread::set_Priority___VOID__SystemThreadingThreadPriority( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack );
FAULT_ON_NULL(pMngObj);
INT32 param0;
TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 1, param0 ) );
Thread::set_Priority( pMngObj, param0, hr );
TINYCLR_CHECK_HRESULT( hr );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Threading_Thread::get_IsAlive___BOOLEAN( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack );
FAULT_ON_NULL(pMngObj);
INT8 retVal = Thread::get_IsAlive( pMngObj, hr );
TINYCLR_CHECK_HRESULT( hr );
SetResult_INT8( stack, retVal );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Threading_Thread::Join___VOID( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack );
FAULT_ON_NULL(pMngObj);
Thread::Join( pMngObj, hr );
TINYCLR_CHECK_HRESULT( hr );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Threading_Thread::Join___BOOLEAN__I4( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack );
FAULT_ON_NULL(pMngObj);
INT32 param0;
TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 1, param0 ) );
INT8 retVal = Thread::Join( pMngObj, param0, hr );
TINYCLR_CHECK_HRESULT( hr );
SetResult_INT8( stack, retVal );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Threading_Thread::Join___BOOLEAN__SystemTimeSpan( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack );
FAULT_ON_NULL(pMngObj);
UNSUPPORTED_TYPE param0;
TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 1, param0 ) );
INT8 retVal = Thread::Join( pMngObj, param0, hr );
TINYCLR_CHECK_HRESULT( hr );
SetResult_INT8( stack, retVal );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Threading_Thread::get_ThreadState___SystemThreadingThreadState( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack );
FAULT_ON_NULL(pMngObj);
INT32 retVal = Thread::get_ThreadState( pMngObj, hr );
TINYCLR_CHECK_HRESULT( hr );
SetResult_INT32( stack, retVal );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Threading_Thread::Sleep___STATIC__VOID__I4( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
INT32 param0;
TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 0, param0 ) );
Thread::Sleep( param0, hr );
TINYCLR_CHECK_HRESULT( hr );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Threading_Thread::get_CurrentThread___STATIC__SystemThreadingThread( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
UNSUPPORTED_TYPE retVal = Thread::get_CurrentThread( hr );
TINYCLR_CHECK_HRESULT( hr );
SetResult_UNSUPPORTED_TYPE( stack, retVal );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Threading_Thread::GetDomain___STATIC__SystemAppDomain( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
UNSUPPORTED_TYPE retVal = Thread::GetDomain( hr );
TINYCLR_CHECK_HRESULT( hr );
SetResult_UNSUPPORTED_TYPE( stack, retVal );
}
TINYCLR_NOCLEANUP();
}
| [
"[email protected]"
]
| [
[
[
1,
241
]
]
]
|
69b945ad5942a9224af441e053943f76d124e3ff | b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a | /Code/TootleReflection/TAssetTree.h | bf9c72002ef44248d455f7b23870bef8c3430b9a | []
| no_license | SoylentGraham/Tootle | 4ae4e8352f3e778e3743e9167e9b59664d83b9cb | 17002da0936a7af1f9b8d1699d6f3e41bab05137 | refs/heads/master | 2021-01-24T22:44:04.484538 | 2010-11-03T22:53:17 | 2010-11-03T22:53:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,941 | h | /*
Tree which shows our loaded assets
*/
#pragma once
#include <TootleGui/TWindow.h>
#include <TootleGui/TMenu.h>
#include <TootleGui/TTree.h>
#include <TootleCore/TGraphBase.h>
#include <TootleCore/TLMessaging.h>
#include <TootleGame/TMenuController.h> // gr: including game lib file :( see about moving the menu handling system to the core?
namespace TLReflection
{
class TAssetTreeItem; // item for a TLGui::Tree which maps items to assets and vice versa
class TAssetTree; // window which contains a tree which shows all our assets
}
//---------------------------------------------------------
//
//---------------------------------------------------------
class TLReflection::TAssetTreeItem : public TLGui::TTreeItem, public TLMessaging::TSubscriber
{
public:
TAssetTreeItem(); // root constructor
TAssetTreeItem(TTypedRef AssetRef); // child constructor
virtual TRefRef GetSubscriberRef() const { return m_Asset.GetRef(); }
const TTypedRef& GetAssetRef() const { return m_Asset; }
// gr: these are overloaded so we can update the node->item index
virtual bool AddChild(TPtr<TTreeItem>& pChildItem); // add child item and notify owner
protected:
virtual void ProcessMessage(TLMessaging::TMessage& Message); // catch changes to the node we're associated with
virtual void GetData(TString& DataString,TRefRef DataRef);
virtual bool IsDataMutable(TRefRef DataRef);
virtual bool SetData(const TString& DataString,TRefRef DataRef);
virtual void CreateChildren(); // create child items
protected:
TTypedRef m_Asset;
};
//--------------------------------------------------------------
// window which contains a tree displaying the contents of the assets
//--------------------------------------------------------------
class TLReflection::TAssetTree : public TLMenu::TMenuController
{
friend class TLReflection::TAssetTreeItem;
public:
TAssetTree();
virtual TRefRef GetSubscriberRef() const { static TRef Ref("AssetTree"); return Ref; }
bool IsValid() const { return (m_pWindow && m_pTree); } // did this init/construct okay and is usable?
protected:
virtual void ProcessMessage(TLMessaging::TMessage& Message);
TPtr<TLAsset::TMenu> CreateNodePopupMenu(TRefRef MenuRef,const TArray<TRef>& Nodes); // create menu for the node-popup for these nodes
protected:
TPtr<TLGui::TWindow> m_pWindow;
TPtr<TLGui::TTree> m_pTree; // todo: don't store this, make the owner control (m_pWindow in this case) be responsible for destruction (as this is what wx does). In theory the smart pointer should still be good but I think as wx explicitly deletes the control this will break the smart pointers
TPtr<TLGui::TMenuWrapper> m_pMenuWrapper; // menu wrapper
THeapArray<TRef> m_PopupMenuNodes; // our hacky method of customising the node popup menu...
};
| [
"[email protected]"
]
| [
[
[
1,
78
]
]
]
|
879e801b2d647bdd5878354abac28c99f6ee121e | a70f708a62feb4d1b6f80d0a471b47ac584ea82b | / arxlss --username quangvinh.ph/VLSS/Ex02Dlg.cpp | e56c8ec90303b34a8e55d8efdea663f47bb5c528 | []
| no_license | presscad/arxlss | ae8a41acba416d20a1ec2aa4485d142912e6787d | d6d201bfc98b0d442c77b37b10ca5ac7ea5efcbb | refs/heads/master | 2021-04-01T22:38:06.710239 | 2009-11-07T02:47:17 | 2009-11-07T02:47:17 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,949 | cpp | // Ex02Dlg.cpp : 実装ファイル
//
#include "stdafx.h"
#include "Ex02Dlg.h"
// CEx02Dlg ダイアログ
IMPLEMENT_DYNAMIC(CEx02Dlg, CAcUiDialog)
CEx02Dlg::CEx02Dlg(CWnd* pParent /*=NULL*/)
: CAcUiDialog(CEx02Dlg::IDD, pParent)
, m_strFileName(_T(""))
{
CLogger::Print(L"*Construct: CEx02Dlg");
}
CEx02Dlg::~CEx02Dlg()
{
CLogger::Print(L"*Destruct: CEx02Dlg");
}
void CEx02Dlg::DoDataExchange(CDataExchange* pDX)
{
CAcUiDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT_FILENAME, m_strFileName);
DDX_Control(pDX, IDC_BITMAP, m_stcBitmap);
}
BEGIN_MESSAGE_MAP(CEx02Dlg, CAcUiDialog)
ON_BN_CLICKED(IDC_BTN_BROWSE, &CEx02Dlg::on_btnBrowse_clicked)
ON_BN_CLICKED(IDCANCEL, &CEx02Dlg::on_btnCancle_clicked)
END_MESSAGE_MAP()
// CEx02Dlg メッセージ ハンドラ
void CEx02Dlg::on_btnBrowse_clicked()
{
CLogger::Print(L"*Call: on_btnBrowse_clicked()");
//------------
// Open a dialog to select bitmap file.
CFileDialog dlgOpenFile(TRUE, NULL, NULL, OFN_FILEMUSTEXIST
, L"Bitmap file (*.bmp)|*.bmp||", this);
if (IDOK == dlgOpenFile.DoModal()) {
//------------
// After selected file, update the file path string into text box.
// Then load bitmap into picture box.
m_strFileName = dlgOpenFile.GetPathName();
UpdateData(FALSE);
// Load the bitmap from file.
HBITMAP hBitmap = (HBITMAP) LoadImage(NULL, m_strFileName
, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
if (hBitmap != NULL) {
m_stcBitmap.SetBitmap(hBitmap);
} else {
CLogger::Print(L"Warn: Fail to load image!");
}
} else {
CLogger::Print(L"Warn: Have not choice any bimap file!");
}
CLogger::Print(L"*Exit: on_btnBrowse_clicked()");
}
void CEx02Dlg::RunMe(void)
{
CLogger::Print(L"--------------------| START LOGGING DIALOG 02 |--------------------");
CEx02Dlg dlg;
dlg.DoModal();
}
void CEx02Dlg::on_btnCancle_clicked()
{
OnCancel();
}
| [
"quangvinh.ph@29354a60-911c-11de-8f34-01a6ee357387"
]
| [
[
[
1,
82
]
]
]
|
6d089701c90a49eba125f6049f26eb96e1abe71f | 1736474d707f5c6c3622f1cd370ce31ac8217c12 | /PseudoUnitTest/TestNew.hpp | 698bb17e83e7d842b5c59a23babdb1bec1c46b42 | []
| no_license | arlm/pseudo | 6d7450696672b167dd1aceec6446b8ce137591c0 | 27153e50003faff31a3212452b1aec88831d8103 | refs/heads/master | 2022-11-05T23:38:08.214807 | 2011-02-18T23:18:36 | 2011-02-18T23:18:36 | 275,132,368 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | hpp | #include <Pseudo\New.hpp>
using namespace Pseudo;
BEGIN_TEST_CLASS(TestNew)
BEGIN_TEST_METHODS
TEST_METHOD(Test)
END_TEST_METHODS
class A
{
public: A(int a, int b)
{
this->a = a;
this->b = b;
}
public: ~A()
{
a = b = 0;
}
public: int a;
public: int b;
};
void Test()
{
A* pA = PSEUDO_NEW A(1, 2);
TEST_ASSERT(pA->a == 1 && pA->b == 2, L"A() constructor not called correctly");
// TODO-johnls-2/7/2008: Check allocator to see if one new object is around
delete pA;
// TODO-johnls-2/7/2008: Check allocator to see if one new object is gone
}
END_TEST_CLASS
| [
"[email protected]"
]
| [
[
[
1,
39
]
]
]
|
149ca5ed9b9e286890534c91e19b2fba2d53d873 | 324524076ba7b05d9d8cf5b65f4cd84072c2f771 | /Checkers/Libraries/MarqueeBox/Public/MarqueeBox.cpp | b870031ce787f27e79363ab52373575b3c8acc38 | [
"BSD-2-Clause"
]
| permissive | joeyespo-archive/checkers-c | 3bf9ff11f5f1dee4c17cd62fb8af9ba79246e1c3 | 477521eb0221b747e93245830698d01fafd2bd66 | refs/heads/master | 2021-01-01T05:32:45.964978 | 2011-03-13T04:53:08 | 2011-03-13T04:53:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,552 | cpp | // MarqueeBox.cpp - MarqueeBox
// MarqueeBox Library Implementation File
// By Joe Esposito
#pragma once
// Public Functions
// -----------------
// Registers the MarqueeBox windows class
BOOL WINAPI RegisterMarqueeBox (HINSTANCE hInstance)
{
WNDCLASSEX wcex;
// Set internal info
if (m_MarqueeBoxInfo == NULL) {
if ((m_MarqueeBoxInfo = new MARQUEEBOXCLASSINFO) == NULL) return FALSE;
// Set info
m_MarqueeBoxInfo->uRegisterCount = 0; // Register count starts at 0
}
// Set MarqueeBox window info
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.lpszClassName = ID_MARQUEEBOX_CLASSNAME;
wcex.hInstance = hInstance;
wcex.style = (0);
wcex.hIcon = NULL;
wcex.hIconSm = NULL;
wcex.hCursor = (HCURSOR)LoadCursor(NULL, (LPSTR)IDC_ARROW);
wcex.lpfnWndProc = (WNDPROC)_MarqueeBoxProc;
wcex.cbClsExtra = 0; wcex.cbWndExtra = 4;
wcex.hbrBackground = NULL;
wcex.lpszMenuName = NULL;
// Register window class
if (RegisterClassEx(&wcex) != NULL) {
m_MarqueeBoxInfo->uRegisterCount++;
return TRUE;
}
return FALSE;
}
// Unregisters the MarqueeBox windows class
BOOL WINAPI UnregisterMarqueeBox (HINSTANCE hInstance)
{
if (!m_MarqueeBoxInfo) return FALSE;
// Decrease register count, and unregister if last decrement
if ((--m_MarqueeBoxInfo->uRegisterCount) == 0) {
if (!UnregisterClass(ID_MARQUEEBOX_CLASSNAME, hInstance))
{ m_MarqueeBoxInfo->uRegisterCount++; return FALSE; }
delete m_MarqueeBoxInfo;
m_MarqueeBoxInfo = NULL;
}
return TRUE;
}
| [
"[email protected]"
]
| [
[
[
1,
64
]
]
]
|
acfcf71c90beaf45aa4b7fee6a2601d520903575 | 67491e4817498baa0bd55165fed7807f6f68a716 | /lib/examples/T01_MpiConstructs.cc | cc28e4bd4135b4c57d18dfad6a04bb1524ce0d2c | []
| no_license | blacksqr/sclc | 073b33635f4f48b12565c6198fb8d77f2783ebce | 1a371809b6b88dee01e8676a50753688d1746bde | refs/heads/master | 2021-01-10T14:14:34.376262 | 2011-05-24T14:39:48 | 2011-05-24T14:39:48 | 48,481,465 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,786 | cc | // This file has 136 source lines of code (SLOC).
// This file has 6 comment lines of code (CLOC).
// It calls 7 MPI routines: Status=1, Init=1, Comm_size=1, Comm_rank=1,
// Abort=2, Wtime=2, Finalize=1
// It calls 2 MPI global variables: COMM_WORLD=4, SUCCESS=1
// All together, file contains 9 unique MPI constructs.
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <math.h>
#include "mpi.h"
#include "point.h"
#include "topology.h"
#define X_COORD_LOAD 5
#define Y_COORD_LOAD 2
#define X_COORD_UPPER 0
#define Y_COORD_UPPER 5
#define X_COORD_LOWER 0
#define Y_COORD_LOWER 0
#define MAX_X X_COORD_LOAD
#define MAX_Y Y_COORD_UPPER
#define TOTAL_ROWS MAX_Y + 1
#define MASTER 0
#define FROM_MASTER 1
#define FROM_WORKER 2
double numTopologies = 0;
double numTest(0.0 + 0.0);
string IntToString(int num) {
ostringstream myStream;
myStream << num << flush;
return(myStream.str());
}
void permuteUpperTruss(int x, vector<Point> &path,
vector< vector<Point> > &allPaths,
int &startY, int &endY, const int isFirst) {
vector<Point> prevPath(path);
if (x >= MAX_X) {
if (path.size() > 1) {
path.push_back(Point(X_COORD_LOAD, Y_COORD_LOAD));
allPaths.push_back(path);
}
return;
}
permuteUpperTruss(x + 1, path, allPaths, startY, endY, isFirst);
int firstY = isFirst ? startY : Y_COORD_LOWER;
int lastY = isFirst ? endY : TOTAL_ROWS;
for (int y = firstY; y < lastY; y++) {
path = prevPath;
path.push_back(Point(x, y));
permuteUpperTruss(x + 1, path, allPaths, startY, endY, 0);
}
}
void permuteLowerTruss(int x, vector<Point> &upperPath,
vector<Point> &lowerPath,
vector<Topology> &topologies) {
vector<Point> prevPath(lowerPath);
if (x >= MAX_X) {
lowerPath.push_back(Point(X_COORD_LOAD, Y_COORD_LOAD));
numTopologies += 1;
return;
}
permuteLowerTruss(x + 1, upperPath, lowerPath, topologies);
for (int y = 0; y < TOTAL_ROWS; y++) {
lowerPath = prevPath;
lowerPath.push_back(Point(x, y));
permuteLowerTruss(x + 1, upperPath, lowerPath, topologies);
}
}
void generateAllTopologies(Point &upperAttachment, Point &lowerAttachment,
Point &load, vector<Topology> &topologies,
int &startY, int &endY) {
vector< vector<Point> > allUpperTrusses;
vector<Point> upperTruss;
vector<Point> lowerTruss;
upperTruss.push_back(upperAttachment);
permuteUpperTruss(1, upperTruss, allUpperTrusses, startY, endY, 1);
for (int i = 0; i < allUpperTrusses.size(); i++) {
lowerTruss.clear();
lowerTruss.push_back(lowerAttachment);
permuteLowerTruss(1, allUpperTrusses[i], lowerTruss, topologies);
}
}
int main(int argc, char* argv[]) {
int i, j, k, fileIndex(0),
pathLength,
minimumPosition(-1),
numtasks,
taskid,
numworkers,
averow,
startRow,
endRow,
source,
dest,
mtype,
rc;
double div1, div2, result, startTime, finishTime, generationTime, solveTime;
MPI_Status status;
rc = MPI_Init(&argc, &argv);
rc|= MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
rc|= MPI_Comm_rank(MPI_COMM_WORLD, &taskid);
if (rc != MPI_SUCCESS) {
cout << "Error initializing MPI and obtaining task ID information.\n";
MPI_Abort(MPI_COMM_WORLD, rc);
}
startTime = MPI_Wtime();
vector <Topology> allTopologies;
vector <Point> path;
Point upperAttach(X_COORD_UPPER, Y_COORD_UPPER);
Point lowerAttach(X_COORD_LOWER, Y_COORD_LOWER);
Point load(X_COORD_LOAD, Y_COORD_LOAD);
numworkers = numtasks - 1;
div1 = TOTAL_ROWS;
div2 = numworkers;
result = div1 / div2;
averow = (int)floor(result);
if (numworkers > TOTAL_ROWS) {
cout << "A " << TOTAL_ROWS << " row mesh can not be solved by more than "
<< TOTAL_ROWS << " worker processors (1 row per processor).\n";
MPI_Abort(MPI_COMM_WORLD, rc);
}
if (numtasks == 1) {
startRow = 0;
endRow = TOTAL_ROWS;
}
else {
startRow = (taskid == MASTER) ? averow * numworkers : (taskid-1) * averow;
endRow = (taskid == MASTER) ? TOTAL_ROWS : startRow + averow;
}
if (startRow != endRow) {
generateAllTopologies(upperAttach, lowerAttach, load, allTopologies,
startRow, endRow);
}
generationTime = MPI_Wtime();
if (taskid > MASTER) {
cout << "P" << taskid << ": Topology generation time: "
<< generationTime - startTime << endl;
cout << "Number of topologies generated = " << numTopologies << endl;
}
MPI_Finalize();
}
| [
"jsakuda@11d02305-463e-0410-b2c7-e1fe0421d87c"
]
| [
[
[
1,
168
]
]
]
|
0e63929c59e4ce0a0e1eedb431b5972109600799 | f90b1358325d5a4cfbc25fa6cccea56cbc40410c | /src/GUI/proRataDTASelect.h | 0dfe0b7d0312ec53cc54bc4a48f408807f7e8940 | []
| no_license | ipodyaco/prorata | bd52105499c3fad25781d91952def89a9079b864 | 1f17015d304f204bd5f72b92d711a02490527fe6 | refs/heads/master | 2021-01-10T09:48:25.454887 | 2010-05-11T19:19:40 | 2010-05-11T19:19:40 | 48,766,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,043 | h | #ifndef PRORATADTASELECT_H
#define PRORATADTASELECT_H
#include <QWidget>
#include <QPushButton>
#include <QGroupBox>
#include <QLineEdit>
#include <QLabel>
#include <QLayout>
#include <QToolTip>
#include <QWhatsThis>
#include <QFileDialog>
#include <QSizePolicy>
#include "proRataPreProcess.h"
class ProRataPreProcessWizard;
class ProRataDTASelect : public QWidget
{
Q_OBJECT
public:
ProRataDTASelect( QWidget* parent = 0, Qt::WFlags fl = 0 );
~ProRataDTASelect();
const QString & getResultFile()
{ return qsResults; }
bool isValid()
{ return bValidity; }
public slots:
void getDTAResultsFile();
void validate();
protected:
void buildUI();
QWidget *qwParent;
QGroupBox* qgbInputBox;
QLabel* qlResultFile;
QLineEdit* qleResultFile;
QPushButton* qpbResultFileBrowser;
QVBoxLayout* qvbMainLayout;
QGridLayout* qgbInputBoxLayout;
QString qsResults;
bool bValidity;
friend class ProRataPreProcessWizard;
};
#endif // PRORATADTASELECT_H
| [
"chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a"
]
| [
[
[
1,
55
]
]
]
|
cc5c60fa7b3ef139159a8616a0ad5f728b0d17c9 | 2d4221efb0beb3d28118d065261791d431f4518a | /O界面描述语言/source/OFL/WndInterface/windows/OWI_ScrollBar.cpp | 8bbb5258e8fe961dd1be5c0efb7c1c13168c6110 | []
| no_license | ophyos/olanguage | 3ea9304da44f54110297a5abe31b051a13330db3 | 38d89352e48c2e687fd9410ffc59636f2431f006 | refs/heads/master | 2021-01-10T05:54:10.604301 | 2010-03-23T11:38:51 | 2010-03-23T11:38:51 | 48,682,489 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,678 | cpp |
#include "OWI_ScrollBar.h"
#include "../../CreateWnd/windows/OFControl.h"
OFL_API int _stdcall ScrollBar_GetRangeMin(void* pScrollBar)
{
return ((WinScrollBar*)pScrollBar)->GetRangeMin();
}
OFL_API int _stdcall ScrollBar_GetRangeMax(void* pScrollBar)
{
return ((WinScrollBar*)pScrollBar)->GetRangeMax();
}
OFL_API void _stdcall ScrollBar_SetPosition(void* pScrollBar,int pos)
{
((WinScrollBar*)pScrollBar)->SetPosition(pos);
}
OFL_API int _stdcall ScrollBar_GetPosition(void* pScrollBar)
{
return ((WinScrollBar*)pScrollBar)->GetPosition();
}
OFL_API void _stdcall ScrollBar_SetPageSize(void* pScrollBar,int page)
{
((WinScrollBar*)pScrollBar)->SetPageSize(page);
}
OFL_API int _stdcall ScrollBar_GetPageSize(void* pScrollBar)
{
return ((WinScrollBar*)pScrollBar)->GetPageSize();
}
OFL_API void _stdcall ScrollBar_EnableLeftArrow(void* pScrollBar,bool leftarrow)
{
((WinScrollBar*)pScrollBar)->EnableLeftArrow(leftarrow);
}
OFL_API bool _stdcall ScrollBar_GetLeftArrowEnabled(void* pScrollBar)
{
return ((WinScrollBar*)pScrollBar)->GetLeftArrowEnabled();
}
OFL_API void _stdcall ScrollBar_EnableRightArrow(void* pScrollBar,bool rightarrow)
{
((WinScrollBar*)pScrollBar)->EnableRightArrow(rightarrow);
}
OFL_API bool _stdcall ScrollBar_GetRightArrowEnabled(void* pScrollBar)
{
return ((WinScrollBar*)pScrollBar)->GetRightArrowEnabled();
}
OFL_API void _stdcall ScrollBar_EnableUpArrow(void* pScrollBar,bool uparrow)
{
((WinScrollBar*)pScrollBar)->EnableUpArrow(uparrow);
}
OFL_API bool _stdcall ScrollBar_GetUpArrowEnabled(void* pScrollBar)
{
return ((WinScrollBar*)pScrollBar)->GetUpArrowEnabled();
}
OFL_API void _stdcall ScrollBar_EnableDownArrow(void* pScrollBar,bool downarrow)
{
((WinScrollBar*)pScrollBar)->EnableDownArrow(downarrow);
}
OFL_API bool _stdcall ScrollBar_GetDownArrowEnabled(void* pScrollBar)
{
return ((WinScrollBar*)pScrollBar)->GetDownArrowEnabled();
}
//设置滚动条的滚动范围到【min,max】
OFL_API void _stdcall ScrollBar_SetRange(void* pScrollBar,int min, int max)
{
((WinScrollBar*)pScrollBar)->SetRange(min,max);
}
OFL_API void _stdcall ScrollBar_DestroyControl(void* pScrollBar)
{
((WinScrollBar*)pScrollBar)->DestroyControl();
}
OFL_API char* _stdcall ScrollBar_GetClass(void* pScrollBar)
{
return (char*)((WinScrollBar*)pScrollBar)->GetClass();
}
OFL_API char* _stdcall ScrollBar_GetCaption(void* pScrollBar)
{
return (char*)((WinScrollBar*)pScrollBar)->GetCaption();
}
OFL_API void _stdcall ScrollBar_SetCaption(void* pScrollBar,char* string)
{
((WinScrollBar*)pScrollBar)->SetCaption(string);
}
| [
"[email protected]"
]
| [
[
[
1,
100
]
]
]
|
3a6f65b22077af910854e6e434527558de8f4c69 | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/homedata.h | 3a2fa2efc9aed20753b39fd36a8b2f320375d1f3 | []
| no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,870 | h |
class homedata_state : public driver_device
{
public:
homedata_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
/* memory pointers */
UINT8 * m_vreg;
UINT8 * m_videoram;
/* video-related */
tilemap_t *m_bg_tilemap[2][4];
int m_visible_page;
int m_priority;
UINT8 m_reikaids_which;
int m_flipscreen;
UINT8 m_gfx_bank[2]; // pteacher only uses the first one
UINT8 m_blitter_bank;
int m_blitter_param_count;
UINT8 m_blitter_param[4]; /* buffers last 4 writes to 0x8006 */
/* misc */
int m_vblank;
int m_sndbank;
int m_keyb;
int m_snd_command;
int m_upd7807_porta;
int m_upd7807_portc;
int m_to_cpu;
int m_from_cpu;
/* device */
device_t *m_maincpu;
device_t *m_audiocpu;
device_t *m_dac;
device_t *m_ym;
device_t *m_sn;
UINT8 m_prot_data;
};
/*----------- defined in video/homedata.c -----------*/
WRITE8_HANDLER( mrokumei_videoram_w );
WRITE8_HANDLER( reikaids_videoram_w );
WRITE8_HANDLER( reikaids_gfx_bank_w );
WRITE8_HANDLER( pteacher_gfx_bank_w );
WRITE8_HANDLER( homedata_blitter_param_w );
WRITE8_HANDLER( mrokumei_blitter_bank_w );
WRITE8_HANDLER( reikaids_blitter_bank_w );
WRITE8_HANDLER( pteacher_blitter_bank_w );
WRITE8_HANDLER( mrokumei_blitter_start_w );
WRITE8_HANDLER( reikaids_blitter_start_w );
WRITE8_HANDLER( pteacher_blitter_start_w );
PALETTE_INIT( mrokumei );
PALETTE_INIT( reikaids );
PALETTE_INIT( pteacher );
PALETTE_INIT( mirderby );
VIDEO_START( mrokumei );
VIDEO_START( reikaids );
VIDEO_START( pteacher );
VIDEO_START( lemnangl );
VIDEO_START( mirderby );
SCREEN_UPDATE( mrokumei );
SCREEN_UPDATE( reikaids );
SCREEN_UPDATE( pteacher );
SCREEN_UPDATE( mirderby );
SCREEN_EOF( homedata );
| [
"Mike@localhost"
]
| [
[
[
1,
73
]
]
]
|
7d5712b542aac3179395a55ee03afc5b4449643d | a0dd6df2a43bfd422c7bfea85fe34293e8642634 | /Projet POLY/Parser.hpp | 7b4927fb08fc2a4e91e51e425ffcf81dd3c20d66 | []
| no_license | juliensnz/machinepolyarchi | 45a1f14f39cbf232aa0b7865e6dbe5aa1ef316fe | 233e878b42d48a6419fa2685aae466e02240aba6 | refs/heads/master | 2020-04-11T04:24:39.458916 | 2009-12-16T18:13:07 | 2009-12-16T18:13:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,251 | hpp | #ifndef PARSER_HPP
#define PARSER_HPP
#include <string>
/* La fonction parseText permet de parser une chaine d'instruction,
* et d'en récuperer les elements via les arguments.
* La chaine instruction passée en argument est détruite par l'opération.
*/
void parseText(std::string *instruction,
std::string *etiquette,
std::string *commande,
std::string *ri,
std::string *rj,
std::string *rk,
std::string *nc);
/* De manière analogue à la fonction parseText, la fonction parseHexa extrait les
* differents paramètres d'une instruction codée sous forme d'un entier hexadecimal.
*/
void parseHexa(int inst,
int *opcode,
int *ri,
int *rj,
int *rk,
int *nc);
/* La fonction getToken renvoie soit la sous-chaine délimitée par 0 et separator,
* soit ""
* Si une sous-chaine est trouvée, on la retire de la ligne passée en argument
* Ex: getToken("aaaa,bbb", &token, ',')
* aura pour resultat token == "aaaa" et line == "bbb"
* Si le separateur est '\0', on renvoie toute la ligne
*/
void getToken(std::string *line, std::string *token, char separator);
/* Adaptation réduite de la fonction parse, qui ne récupere que l'etiquette
*/
void getEtiq(std::string *line, std::string *etiquette);
/* Fonction dédiée à la suppression des eventuels commentaires
* Si on trouve un ';', on renvoie la sous chaine délimitée par
* le début et le ';'. Si la méthode find renvoie string::npos,
* le caractère ';' n'est pas dans la chaine et on renvoie alors
* toute la chaine.
*/
void unComment(std::string *line);
/* Fonction dédiée à la suppression des espaces supperflus en début
* et en fin de chaine.
* Par espaces, on entend les espaces, les tabulations, ...
* On renvoie la sous-chaine délimitée par le premier non-espace
* et le dernier non-espace. Les espaces à l'intérieur de la chaine
* ne sont pas concernés.
*/
void trim(std::string *line);
/* Cette fonction renvoie True si la chaine contient un entier (relatif)
* False sinon. On travaille sur une copie de la chaine, elle n'est donc pas
* altérée par l'opération.
*/
bool isInt(std::string *s);
#endif // PARSER_HPP
| [
"Maxime.Bury@f9af527e-e11e-11de-9fd5-4be1c9d5bc18"
]
| [
[
[
1,
59
]
]
]
|
ba20c02b94cdf6126334ecdac7cba071857f1d49 | e618b452106f251f3ac7cf929da9c79256c3aace | /src/lib/cpp/util/draw_utils.h | aec58887607a2f3210deba5b6192ffeaad666d2d | []
| no_license | dlinsin/yfrog | 714957669da86deff3a093a7714e7d800c9260d8 | 513e0d64a0ff749e902e797524ad4a521ead37f8 | refs/heads/master | 2020-12-25T15:40:54.751312 | 2010-04-13T16:31:15 | 2010-04-13T16:31:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,832 | h | #pragma once
/**
* Select object helper class.
*/
class CSelectObject
{
HDC m_hDC;
HGDIOBJ m_hObject;
HGDIOBJ m_hPrevObject;
public:
CSelectObject(HDC hDC, HGDIOBJ hObject)
: m_hDC(hDC)
, m_hObject(hObject)
{
m_hPrevObject = ::SelectObject(m_hDC, hObject);
}
HGDIOBJ operator = (HGDIOBJ hObject)
{
return ::SelectObject(m_hDC, m_hObject = hObject);
}
~CSelectObject()
{
if (m_hDC) ::SelectObject(m_hDC, m_hPrevObject);
}
operator HGDIOBJ()
{
return m_hObject;
}
};
/**
* Map Mode helper class.
*/
class CSetMapMode
{
HDC m_hDC;
INT m_nPrev;
public:
CSetMapMode(HDC hDC, INT nMapMode)
: m_hDC(hDC)
, m_nPrev(0)
{
_ASSERT(m_hDC);
if (m_hDC) m_nPrev = SetMapMode(nMapMode);
}
INT SetMapMode(INT nMapMode)
{
_ASSERT(m_hDC);
return m_hDC ? ::SetMapMode(m_hDC, nMapMode) : 0;
}
INT operator = (INT nMapMode)
{
return SetMapMode(nMapMode);
}
~CSetMapMode()
{
SetMapMode(m_nPrev);
}
};
/**
* BkMode helper class.
*/
class CSetBkMode
{
HDC m_hDC;
INT m_nPrev;
public:
CSetBkMode(HDC hDC, INT nBkMode)
: m_hDC(hDC)
, m_nPrev(0)
{
_ASSERT(m_hDC);
if (m_hDC) m_nPrev = SetBkMode(nBkMode);
}
INT SetBkMode(INT nBkMode)
{
_ASSERT(m_hDC);
return m_hDC ? ::SetBkMode(m_hDC, nBkMode) : 0;
}
INT operator = (INT nBkMode)
{
return SetBkMode(nBkMode);
}
~CSetBkMode()
{
SetBkMode(m_nPrev);
}
};
/**
* Text Color helper class.
*/
class CSetTextColor
{
protected:
HDC m_hDC;
COLORREF m_clrTextColor;
COLORREF m_clrPrevTextColor;
public:
CSetTextColor(HDC hDC, COLORREF clrTextColor)
: m_hDC(hDC)
, m_clrPrevTextColor(0)
{
_ASSERT(m_hDC);
if (m_hDC) m_clrPrevTextColor = SetTextColor(clrTextColor);
}
COLORREF SetTextColor(COLORREF clrTextColor)
{
_ASSERT(m_hDC);
return m_hDC ? ::SetTextColor(m_hDC, m_clrTextColor = clrTextColor) : 0;
}
COLORREF operator = (COLORREF clrTextColor)
{
return SetTextColor(clrTextColor);
}
~CSetTextColor()
{
SetTextColor(m_clrPrevTextColor);
}
operator COLORREF()
{
return m_clrTextColor;
}
};
////////////////////////////////////////////////////////////////////////////////////////////////
inline void Line(CDC *pDC, int x1, int y1, int x2, int y2)
{
pDC->MoveTo(x1,y1);
pDC->LineTo(x2,y2);
}
inline void HorizLine(CDC *pDC, int x1, int x2, int y)
{
pDC->MoveTo(x1,y);
pDC->LineTo(x2,y);
}
inline void VertLine(CDC *pDC, int x, int y1, int y2)
{
pDC->MoveTo(x,y1);
pDC->LineTo(x,y2);
}
////////////////////////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
]
| [
[
[
1,
162
]
]
]
|
1b3b70f44829707601203a71a0510960ff35bf3d | 76b182d8b622a4fffaec0f9c5339a48c0d4f55c8 | /map editor/tileditmap.cpp | 20cdca03825a52b3e2669bb08e650d78af5c2524 | []
| no_license | bobbobbio/Erapr | e83c1429dcb5ba0d03c8a668716c2d43103d94ef | 6cbc662c9a068e192ac6d6498d5b377a9f53124b | refs/heads/master | 2020-06-05T03:59:38.627694 | 2011-03-12T20:40:01 | 2011-03-12T20:40:01 | 1,472,608 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,676 | cpp | /*
* erapr
* ERAPR Really Ain't Playable, Right?
*
* Created by Remi Bernotavicius
* Copyright (c) 2009 Remi Bernotavicius. All rights reserved.
*/
#include "tileedit.h"
#include <iostream>
#include <cmath>
void dither(BITMAP* bmp) {
for (int c = 0; c < bmp->w; c++) {
if(c % 2 == 0)
putpixel(bmp, c, 0, makecol(0, 0, 0));
}
blit(bmp, bmp, 0, 0, 1, 1, bmp->w - 1, 1);
for (int r = 2; r < bmp->h; r*=2) {
blit(bmp, bmp, 0, 0, 0, r, bmp->w, r);
}
}
void redraw_map()
{
set_palette((RGB*)data[MAIN_PAL].dat);
clear_to_color(back_mapBuffer, 0);
clear_to_color(front_mapBuffer, 0);
clear_to_color(solid_mapBuffer, 0);
clear_to_color(event_mapBuffer, 0);
CM->draw_all(back_mapBuffer, BACK);
CM->draw_all(front_mapBuffer, FRONT);
CM->draw_event_all(event_mapBuffer);
CM->draw_solid_all(solid_mapBuffer);
}
void draw_all()
{
set_palette((RGB*)data[MAIN_PAL].dat);
clear_to_color(Buffer, makecol(255,0,255));
clear_to_color(CT, 0);
//we always draw the back layer
draw_sprite(Buffer, back_mapBuffer, scrollX, scrollY);
switch(M)
{
case TILE:
{
CM->drawtile(CT, CN, 0, 0);
//cursor
rect(CT, 0, 0, TILESIZE-1, TILESIZE-1, makecol(255,0,0));
}break;
case SOLID:
{
CM->drawsolid(CT, CN, 0, 0);
//only show solids in solid mode
draw_sprite(Buffer, solid_mapBuffer, scrollX, scrollY);
}break;
case EVENT:
{
CM->drawevent(CT, CN, 0, 0);
//only show events in event mode
draw_sprite(Buffer, event_mapBuffer, scrollX, scrollY);
}break;
case SPRITE:
{
CM->drawSprite(CT, CN, 0, -(itTS->tileHeight - TILESIZE));
textprintf_ex(CT, font, 0, 0, makecol(255, 255, 255), 0, "%d", CN);
//draw_sprite(CT, b, -1 * (CN - 1) * 34, TILESIZE - SPRITE_H);
}break;
case FRONTL:
{
//shade the screen
draw_sprite(Buffer, shaded, 0, 0);
CM->drawtile(CT, CN, 0, 0);
rect(CT, 0, 0, TILESIZE-1, TILESIZE-1, makecol(0,0,255));
}break;
case PLAYER_POSITION:
{
draw_sprite(CT, p, 0, TILESIZE - p->h);
}break;
}
BITMAP* temp = create_bitmap(itTS->tileWidth, itTS->tileHeight);
clear_to_color(temp, 0); //fill temp with blank pixels
blit(p, temp, 0, 0, 0, 0, itTS->tileWidth, itTS->tileHeight);
//draw player
draw_sprite(Buffer, temp, scrollX + CM->playerStart.x, scrollY + CM->playerStart.y);
//draw sprites
for(int i = 0; i < (int)CM->sprites->size(); i++) {
CM->drawSprite(temp, CM->sprites->at(i).type, 0, 0);
draw_sprite(Buffer, temp, scrollX + CM->sprites->at(i).position.x, scrollY + CM->sprites->at(i).position.y);
}
delete temp;
//we always draw the front tiles
draw_sprite(Buffer, front_mapBuffer, scrollX, scrollY);
draw_sprite(Buffer, CT, CM->tileContainingPoint(mouse_x)*TILESIZE, CM->tileContainingPoint(mouse_y)*TILESIZE);
rect(Buffer, mouse_x, mouse_y, mouse_x+4, mouse_y+4, makecol(0,255,0));
}
void AddTile()
{
int nx,ny;
nx = (CM->tileContainingPoint(mouse_x)*TILESIZE-scrollX)/TILESIZE;
ny = (CM->tileContainingPoint(mouse_y)*TILESIZE-scrollY)/TILESIZE;
//std::cout << "\n" << nx << ", " << ny;
switch(M)
{
case SOLID:
{
CM->ALLCELLS[nx][ny].solid = CN;
CM->drawsolid(solid_mapBuffer, CN, nx * TILESIZE, ny * TILESIZE);
}break;
case EVENT:
{
CM->ALLCELLS[nx][ny]._event = CN;
CM->drawevent(event_mapBuffer, CN, nx * TILESIZE, ny * TILESIZE);
}break;
case FRONTL:
{
CM->ALLCELLS[nx][ny].front_tile = CN;
CM->drawtile(front_mapBuffer, CN, nx * TILESIZE, ny * TILESIZE);
}break;
case SPRITE:
{
if(CN == 0){
for (int i = 0; i < (int)CM->sprites->size(); i++) {
rectangle bounds = rectangle(CM->sprites->at(i).position.x, CM->sprites->at(i).position.y, 32, 42);
if (bounds.containsPoint(nx * TILESIZE + (TILESIZE / 2), ny * TILESIZE + (TILESIZE / 2))) {
CM->sprites->erase(CM->sprites->begin() + i);
}
}
}else {
//add new enemy only if one doesn't exist at this point
point p = point(nx * TILESIZE, ny * TILESIZE - (itTS->tileHeight - TILESIZE));
bool found = false;
for (int i = 0; i < (int)CM->sprites->size(); i++) {
if (CM->sprites->at(i).position.equals(p)) {
found = true;
break;
}
}
if (!found) {
sprite t = sprite(p, CN);
CM->sprites->push_back(t);
//std::cout << "adding emeny";
}
}
}break;
case TILE:
{
CM->ALLCELLS[nx][ny].back_tile = CN;
CM->drawtile(back_mapBuffer, CN, nx * TILESIZE, ny * TILESIZE);
//make default tile solid
CM->ALLCELLS[nx][ny].solid = (CN != 0);
CM->drawsolid(solid_mapBuffer, CM->ALLCELLS[nx][ny].solid, nx * TILESIZE, ny * TILESIZE);
}break;
case PLAYER_POSITION:
{
CM->playerStart.x = nx * TILESIZE;
CM->playerStart.y = (ny + 1) * TILESIZE - p->h;
}break;
}
}
void PickUpTile()
{
int nx,ny;
nx = (CM->tileContainingPoint(mouse_x)*TILESIZE-scrollX)/TILESIZE;
ny = (CM->tileContainingPoint(mouse_y)*TILESIZE-scrollY)/TILESIZE;
switch(M)
{
case SOLID:
{
CN = CM->ALLCELLS[nx][ny].solid;
}break;
case EVENT:
{
CN = CM->ALLCELLS[nx][ny]._event;
}break;
case TILE:
{
CN = CM->ALLCELLS[nx][ny].back_tile;
}break;
case FRONTL:
{
CN = CM->ALLCELLS[nx][ny].front_tile;
}break;
}
}
void ScrollUpdate()
{
if(mouse_y < 20)
scrollY+=TILESIZE;
if(mouse_y < 10)
scrollY+=TILESIZE;
if(mouse_y > SCREEN_H-20)
scrollY-=TILESIZE;
if(mouse_y > SCREEN_H-10)
scrollY-=TILESIZE;
if(mouse_x < 20)
scrollX+=TILESIZE;
if(mouse_x < 10)
scrollX+=TILESIZE;
if(mouse_x > SCREEN_W-20)
scrollX-=TILESIZE;
if(mouse_x > SCREEN_W-10)
scrollX-=TILESIZE;
if(scrollX > 0)
scrollX=0;
if(scrollY > 0)
scrollY=0;
int tempx = ((CM->worldWidth()*TILESIZE)-SCREEN_W)*(-1);
int tempy = ((CM->worldHeight()*TILESIZE)-SCREEN_H)*(-1);
if(scrollX < tempx)
scrollX = tempx;
if(scrollY < tempy)
scrollY = tempy;
}
void NewMap()
{
scrollX=0;
scrollY=0;
CN=1;
delete CM;
point sz = mapsize();
std::cout << "map created";
CM = new Map(sz.x, sz.y, bgTS, itTS);
destroy_bitmap(back_mapBuffer);
destroy_bitmap(front_mapBuffer);
destroy_bitmap(solid_mapBuffer);
destroy_bitmap(event_mapBuffer);
back_mapBuffer = create_bitmap(CM->worldWidth()*TILESIZE, CM->worldHeight()*TILESIZE);
front_mapBuffer = create_bitmap(CM->worldWidth()*TILESIZE, CM->worldHeight()*TILESIZE);
event_mapBuffer = create_bitmap(CM->worldWidth()*TILESIZE, CM->worldHeight()*TILESIZE);
solid_mapBuffer = create_bitmap(CM->worldWidth()*TILESIZE, CM->worldHeight()*TILESIZE);
shaded = create_bitmap(CM->worldWidth()*TILESIZE, CM->worldHeight()*TILESIZE);
dither(shaded);
redraw_map();
}
void loadmap()
{
char path[480] = "";
if(file_select_ex("Choose a map file to open", path, "map", 480,400, 200) != 0)
{
delete CM;
CM = new Map(path, bgTS, itTS);
CN=1;
scrollX=0;
scrollY=0;
destroy_bitmap(back_mapBuffer);
destroy_bitmap(front_mapBuffer);
destroy_bitmap(solid_mapBuffer);
destroy_bitmap(event_mapBuffer);
back_mapBuffer = create_bitmap(CM->worldWidth()*TILESIZE, CM->worldHeight()*TILESIZE);
front_mapBuffer = create_bitmap(CM->worldWidth()*TILESIZE, CM->worldHeight()*TILESIZE);
event_mapBuffer = create_bitmap(CM->worldWidth()*TILESIZE, CM->worldHeight()*TILESIZE);
solid_mapBuffer = create_bitmap(CM->worldWidth()*TILESIZE, CM->worldHeight()*TILESIZE);
shaded = create_bitmap(CM->worldWidth()*TILESIZE, CM->worldHeight()*TILESIZE);
dither(shaded);
redraw_map();
}
}
void savemap()
{
char path[480] = "newmap.map";
if(file_select_ex("Choose where to save", path, "map", 480,400, 200) != 0)
{
CM->saveToFile(path);
}
}
int quit() {
cont = false;
return D_CLOSE;
}
//code taken from the allegro example file exgui.c
int my_button_proc(int msg, DIALOG *d, int c)
{
int ret = d_button_proc(msg, d, c);
if (ret == D_CLOSE && d->dp3)
return ((int (*)(void))d->dp3)();
return ret;
}
point mapsize()
{
set_palette((RGB*)data[MAIN_PAL].dat);
char width[(32 + 1) * 4] = "40";
char height[(32 + 1) * 4] = "30";
DIALOG the_dialog[] = {
{ d_clear_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL},
{ d_shadow_box_proc, 0, 0, 220, 100, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL },
{ d_ctext_proc, 10, 10, 160, 8, 0, 0, 0, 0, 0, 0, (void*)"Set Map Size", NULL, NULL},
{ d_text_proc, 10, 30, 0, 0, 0, 0, 0, 0, 0, 0, (void*)"width:", NULL, NULL},
{ d_edit_proc, 70, 30, 100, 8, 0, 0, 0, 0, 32, 0, width, NULL, NULL} ,
{ d_text_proc, 10, 40, 0, 0, 0, 0, 0, 0, 0, 0, (void*)"height:", NULL, NULL},
{ d_edit_proc, 70, 40, 100, 8, 0, 0, 0, 0, 32, 0, height, NULL, NULL} ,
{ d_button_proc, 10, 60, 80, 20, 0, 0, 'c', D_EXIT, 0, 0, (void*)"&Create", NULL, NULL},
{ my_button_proc, 130, 60, 80, 20, 0, 0, 'e', D_EXIT, 0, 0, (void*)"&Exit", NULL, (void*)quit},
{ d_keyboard_proc, 0, 0, 0, 0, 0, 0, 0, 0, KEY_ESC, 0, (void*)quit, NULL, NULL},
{ NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }
};
//set_dialog_color(the_dialog, gui_fg_color, gui_bg_color);
for (int i = 0; the_dialog[i].proc; i++) {
the_dialog[i].fg = makecol(0, 0, 0);
the_dialog[i].bg = makecol(255, 255, 255);
}
centre_dialog(the_dialog);
popup_dialog(the_dialog, -1);
int minw = (int) ceil((double)SCREEN_W / TILESIZE);
int minh = (int) ceil((double)SCREEN_H / TILESIZE);
return point(std::max(atoi(width), minw), std::max(atoi(height), minh));
} | [
"[email protected]"
]
| [
[
[
1,
342
]
]
]
|
16da4ce881e12592b41101eb9e40abc3293a0fc1 | 99e0dc29b82ed0af51ab94b3384d70f76c02ed72 | /jni/highlyadvanced/windows_orig/VBA/Sound.cpp | 10afb745102978bead08a6df7f0b708890674caa | []
| no_license | neko68k/ManyChip | 7f706cb61d2c6fcd480450faf0c7934645f37137 | d29019f8eca826c3fd27e0af9347efc4f01f740d | refs/heads/master | 2016-09-07T11:02:27.276243 | 2011-12-22T08:52:16 | 2011-12-22T08:52:16 | 3,032,725 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,790 | cpp | // VisualBoyAdvance - Nintendo Gameboy/GameboyAdvance (TM) emulator.
// Copyright (C) 1999-2003 Forgotten
// Copyright (C) 2004 Forgotten and the VBA development team
// 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 this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include <memory.h>
//#include <windows.h>
#include <unistd.h>
//#include "in2.h"
#include "GBA.h"
#include "Globals.h"
#include "Sound.h"
#include "Util.h"
#include "snd_interp.h"
#define USE_TICKS_AS 380
#define SOUND_MAGIC 0x60000000
#define SOUND_MAGIC_2 0x30000000
#define NOISE_MAGIC 5
extern bool stopState;
u8 soundWavePattern[4][32] = {
{0x01,0x01,0x01,0x01,
0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff},
{0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,
0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff},
{0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,
0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff},
{0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,
0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff}
};
int soundFreqRatio[8] = {
1048576, // 0
524288, // 1
262144, // 2
174763, // 3
131072, // 4
104858, // 5
87381, // 6
74898 // 7
};
int soundShiftClock[16]= {
2, // 0
4, // 1
8, // 2
16, // 3
32, // 4
64, // 5
128, // 6
256, // 7
512, // 8
1024, // 9
2048, // 10
4096, // 11
8192, // 12
16384, // 13
1, // 14
1 // 15
};
extern "C"
{
int soundVolume = 0;
#ifndef NO_INTERPOLATION
u8 soundBuffer[4][735];
u16 directBuffer[2][735];
#else
u8 soundBuffer[6][735];
#endif
//u16 soundFinalWave[1470];
u16 soundFinalWave[2304];
int soundBufferLen = 576;
int soundBufferTotalLen = 14700;
int soundQuality = 1;
#ifndef NO_INTERPOLATION
int soundInterpolation = 4;
#else
int soundInterpolation = 0;
#endif
int soundPaused = 1;
int soundPlay = 0;
int soundTicks = soundQuality * USE_TICKS_AS;
int SOUND_CLOCK_TICKS = soundQuality * USE_TICKS_AS;
u32 soundNextPosition = 0;
int soundLevel1 = 0;
int soundLevel2 = 0;
int soundBalance = 0;
int soundMasterOn = 0;
int soundIndex = 0;
int soundBufferIndex = 0;
int soundDebug = 0;
bool soundOffFlag = false;
int sound1On = 0;
int sound1ATL = 0;
int sound1Skip = 0;
int sound1Index = 0;
int sound1Continue = 0;
int sound1EnvelopeVolume = 0;
int sound1EnvelopeATL = 0;
int sound1EnvelopeUpDown = 0;
int sound1EnvelopeATLReload = 0;
int sound1SweepATL = 0;
int sound1SweepATLReload = 0;
int sound1SweepSteps = 0;
int sound1SweepUpDown = 0;
int sound1SweepStep = 0;
u8 *sound1Wave = soundWavePattern[2];
int sound2On = 0;
int sound2ATL = 0;
int sound2Skip = 0;
int sound2Index = 0;
int sound2Continue = 0;
int sound2EnvelopeVolume = 0;
int sound2EnvelopeATL = 0;
int sound2EnvelopeUpDown = 0;
int sound2EnvelopeATLReload = 0;
u8 *sound2Wave = soundWavePattern[2];
int sound3On = 0;
int sound3ATL = 0;
int sound3Skip = 0;
int sound3Index = 0;
int sound3Continue = 0;
int sound3OutputLevel = 0;
int sound3Last = 0;
u8 sound3WaveRam[0x20];
int sound3Bank = 0;
int sound3DataSize = 0;
int sound3ForcedOutput = 0;
int sound4On = 0;
int sound4Clock = 0;
int sound4ATL = 0;
int sound4Skip = 0;
int sound4Index = 0;
int sound4ShiftRight = 0x7f;
int sound4ShiftSkip = 0;
int sound4ShiftIndex = 0;
int sound4NSteps = 0;
int sound4CountDown = 0;
int sound4Continue = 0;
int sound4EnvelopeVolume = 0;
int sound4EnvelopeATL = 0;
int sound4EnvelopeUpDown = 0;
int sound4EnvelopeATLReload = 0;
int soundControl = 0;
int soundDSFifoAIndex = 0;
int soundDSFifoACount = 0;
int soundDSFifoAWriteIndex = 0;
bool soundDSAEnabled = false;
int soundDSATimer = 0;
u8 soundDSFifoA[32];
u8 soundDSAValue = 0;
int soundDSFifoBIndex = 0;
int soundDSFifoBCount = 0;
int soundDSFifoBWriteIndex = 0;
bool soundDSBEnabled = false;
int soundDSBTimer = 0;
u8 soundDSFifoB[32];
u8 soundDSBValue = 0;
int soundEnableFlag = 0x3ff;
s16 soundFilter[4000];
s16 soundRight[5] = { 0, 0, 0, 0, 0 };
s16 soundLeft[5] = { 0, 0, 0, 0, 0 };
int soundEchoIndex = 0;
char soundEcho = false;
char soundLowPass = false;
char soundReverse = false;
}
variable_desc soundSaveStruct[] = {
{ &soundPaused, sizeof(int) },
{ &soundPlay, sizeof(int) },
{ &soundTicks, sizeof(int) },
{ &SOUND_CLOCK_TICKS, sizeof(int) },
{ &soundLevel1, sizeof(int) },
{ &soundLevel2, sizeof(int) },
{ &soundBalance, sizeof(int) },
{ &soundMasterOn, sizeof(int) },
{ &soundIndex, sizeof(int) },
{ &sound1On, sizeof(int) },
{ &sound1ATL, sizeof(int) },
{ &sound1Skip, sizeof(int) },
{ &sound1Index, sizeof(int) },
{ &sound1Continue, sizeof(int) },
{ &sound1EnvelopeVolume, sizeof(int) },
{ &sound1EnvelopeATL, sizeof(int) },
{ &sound1EnvelopeATLReload, sizeof(int) },
{ &sound1EnvelopeUpDown, sizeof(int) },
{ &sound1SweepATL, sizeof(int) },
{ &sound1SweepATLReload, sizeof(int) },
{ &sound1SweepSteps, sizeof(int) },
{ &sound1SweepUpDown, sizeof(int) },
{ &sound1SweepStep, sizeof(int) },
{ &sound2On, sizeof(int) },
{ &sound2ATL, sizeof(int) },
{ &sound2Skip, sizeof(int) },
{ &sound2Index, sizeof(int) },
{ &sound2Continue, sizeof(int) },
{ &sound2EnvelopeVolume, sizeof(int) },
{ &sound2EnvelopeATL, sizeof(int) },
{ &sound2EnvelopeATLReload, sizeof(int) },
{ &sound2EnvelopeUpDown, sizeof(int) },
{ &sound3On, sizeof(int) },
{ &sound3ATL, sizeof(int) },
{ &sound3Skip, sizeof(int) },
{ &sound3Index, sizeof(int) },
{ &sound3Continue, sizeof(int) },
{ &sound3OutputLevel, sizeof(int) },
{ &sound4On, sizeof(int) },
{ &sound4ATL, sizeof(int) },
{ &sound4Skip, sizeof(int) },
{ &sound4Index, sizeof(int) },
{ &sound4Clock, sizeof(int) },
{ &sound4ShiftRight, sizeof(int) },
{ &sound4ShiftSkip, sizeof(int) },
{ &sound4ShiftIndex, sizeof(int) },
{ &sound4NSteps, sizeof(int) },
{ &sound4CountDown, sizeof(int) },
{ &sound4Continue, sizeof(int) },
{ &sound4EnvelopeVolume, sizeof(int) },
{ &sound4EnvelopeATL, sizeof(int) },
{ &sound4EnvelopeATLReload, sizeof(int) },
{ &sound4EnvelopeUpDown, sizeof(int) },
{ &soundEnableFlag, sizeof(int) },
{ &soundControl, sizeof(int) },
{ &soundDSFifoAIndex, sizeof(int) },
{ &soundDSFifoACount, sizeof(int) },
{ &soundDSFifoAWriteIndex, sizeof(int) },
{ &soundDSAEnabled, sizeof(bool) },
{ &soundDSATimer, sizeof(int) },
{ &soundDSFifoA[0], 32 },
{ &soundDSAValue, sizeof(u8) },
{ &soundDSFifoBIndex, sizeof(int) },
{ &soundDSFifoBCount, sizeof(int) },
{ &soundDSFifoBWriteIndex, sizeof(int) },
{ &soundDSBEnabled, sizeof(int) },
{ &soundDSBTimer, sizeof(int) },
{ &soundDSFifoB[0], 32 },
{ &soundDSBValue, sizeof(int) },
#ifndef NO_INTERPOLATION
{ &soundBuffer[0][0], 4*735 },
{ &directBuffer[0][0], 2*2*735 },
#else
{ &soundBuffer[0][0], 6*735 },
#endif
{ &soundFinalWave[0], 2*735 },
{ NULL, 0 }
};
variable_desc soundSaveStructV2[] = {
{ &sound3WaveRam[0], 0x20 },
{ &sound3Bank, sizeof(int) },
{ &sound3DataSize, sizeof(int) },
{ &sound3ForcedOutput, sizeof(int) },
{ NULL, 0 }
};
void soundEvent(u32 address, u8 data)
{
int freq = 0;
switch(address) {
case NR10:
data &= 0x7f;
sound1SweepATL = sound1SweepATLReload = 344 * ((data >> 4) & 7);
sound1SweepSteps = data & 7;
sound1SweepUpDown = data & 0x08;
sound1SweepStep = 0;
ioMem[address] = data;
break;
case NR11:
sound1Wave = soundWavePattern[data >> 6];
sound1ATL = 172 * (64 - (data & 0x3f));
ioMem[address] = data;
break;
case NR12:
sound1EnvelopeUpDown = data & 0x08;
sound1EnvelopeATLReload = 689 * (data & 7);
if((data & 0xF8) == 0)
sound1EnvelopeVolume = 0;
ioMem[address] = data;
break;
case NR13:
freq = (((int)(ioMem[NR14] & 7)) << 8) | data;
sound1ATL = 172 * (64 - (ioMem[NR11] & 0x3f));
freq = 2048 - freq;
if(freq) {
sound1Skip = SOUND_MAGIC / freq;
} else
sound1Skip = 0;
ioMem[address] = data;
break;
case NR14:
data &= 0xC7;
freq = (((int)(data&7) << 8) | ioMem[NR13]);
freq = 2048 - freq;
sound1ATL = 172 * (64 - (ioMem[NR11] & 0x3f));
sound1Continue = data & 0x40;
if(freq) {
sound1Skip = SOUND_MAGIC / freq;
} else
sound1Skip = 0;
if(data & 0x80) {
ioMem[NR52] |= 1;
sound1EnvelopeVolume = ioMem[NR12] >> 4;
sound1EnvelopeUpDown = ioMem[NR12] & 0x08;
sound1ATL = 172 * (64 - (ioMem[NR11] & 0x3f));
sound1EnvelopeATLReload = sound1EnvelopeATL = 689 * (ioMem[NR12] & 7);
sound1SweepATL = sound1SweepATLReload = 344 * ((ioMem[NR10] >> 4) & 7);
sound1SweepSteps = ioMem[NR10] & 7;
sound1SweepUpDown = ioMem[NR10] & 0x08;
sound1SweepStep = 0;
sound1Index = 0;
sound1On = 1;
}
ioMem[address] = data;
break;
case NR21:
sound2Wave = soundWavePattern[data >> 6];
sound2ATL = 172 * (64 - (data & 0x3f));
ioMem[address] = data;
break;
case NR22:
sound2EnvelopeUpDown = data & 0x08;
sound2EnvelopeATLReload = 689 * (data & 7);
if((data & 0xF8) == 0)
sound2EnvelopeVolume = 0;
ioMem[address] = data;
break;
case NR23:
freq = (((int)(ioMem[NR24] & 7)) << 8) | data;
sound2ATL = 172 * (64 - (ioMem[NR21] & 0x3f));
freq = 2048 - freq;
if(freq) {
sound2Skip = SOUND_MAGIC / freq;
} else
sound2Skip = 0;
ioMem[address] = data;
break;
case NR24:
data &= 0xC7;
freq = (((int)(data&7) << 8) | ioMem[NR23]);
freq = 2048 - freq;
sound2ATL = 172 * (64 - (ioMem[NR21] & 0x3f));
sound2Continue = data & 0x40;
if(freq) {
sound2Skip = SOUND_MAGIC / freq;
} else
sound2Skip = 0;
if(data & 0x80) {
ioMem[NR52] |= 2;
sound2EnvelopeVolume = ioMem[NR22] >> 4;
sound2EnvelopeUpDown = ioMem[NR22] & 0x08;
sound2ATL = 172 * (64 - (ioMem[NR21] & 0x3f));
sound2EnvelopeATLReload = sound2EnvelopeATL = 689 * (ioMem[NR22] & 7);
sound2Index = 0;
sound2On = 1;
}
break;
ioMem[address] = data;
case NR30:
data &= 0xe0;
if(!(data & 0x80)) {
ioMem[NR52] &= 0xfb;
sound3On = 0;
}
if(((data >> 6) & 1) != sound3Bank)
memcpy(&ioMem[0x90], &sound3WaveRam[(((data >> 6) & 1) * 0x10)^0x10],
0x10);
sound3Bank = (data >> 6) & 1;
sound3DataSize = (data >> 5) & 1;
ioMem[address] = data;
break;
case NR31:
sound3ATL = 172 * (256-data);
ioMem[address] = data;
break;
case NR32:
data &= 0xe0;
sound3OutputLevel = (data >> 5) & 3;
sound3ForcedOutput = (data >> 7) & 1;
ioMem[address] = data;
break;
case NR33:
freq = 2048 - (((int)(ioMem[NR34]&7) << 8) | data);
if(freq) {
sound3Skip = SOUND_MAGIC_2 / freq;
} else
sound3Skip = 0;
ioMem[address] = data;
break;
case NR34:
data &= 0xc7;
freq = 2048 - (((data &7) << 8) | (int)ioMem[NR33]);
if(freq) {
sound3Skip = SOUND_MAGIC_2 / freq;
} else {
sound3Skip = 0;
}
sound3Continue = data & 0x40;
if((data & 0x80) && (ioMem[NR30] & 0x80)) {
ioMem[NR52] |= 4;
sound3ATL = 172 * (256 - ioMem[NR31]);
sound3Index = 0;
sound3On = 1;
}
ioMem[address] = data;
break;
case NR41:
data &= 0x3f;
sound4ATL = 172 * (64 - (data & 0x3f));
ioMem[address] = data;
break;
case NR42:
sound4EnvelopeUpDown = data & 0x08;
sound4EnvelopeATLReload = 689 * (data & 7);
if((data & 0xF8) == 0)
sound4EnvelopeVolume = 0;
ioMem[address] = data;
break;
case NR43:
freq = soundFreqRatio[data & 7];
sound4NSteps = data & 0x08;
sound4Skip = (freq << 8) / NOISE_MAGIC;
sound4Clock = data >> 4;
freq = freq / soundShiftClock[sound4Clock];
sound4ShiftSkip = (freq << 8) / NOISE_MAGIC;
ioMem[address] = data;
break;
case NR44:
data &= 0xc0;
sound4Continue = data & 0x40;
if(data & 0x80) {
ioMem[NR52] |= 8;
sound4EnvelopeVolume = ioMem[NR42] >> 4;
sound4EnvelopeUpDown = ioMem[NR42] & 0x08;
sound4ATL = 172 * (64 - (ioMem[NR41] & 0x3f));
sound4EnvelopeATLReload = sound4EnvelopeATL = 689 * (ioMem[NR42] & 7);
sound4On = 1;
sound4Index = 0;
sound4ShiftIndex = 0;
freq = soundFreqRatio[ioMem[NR43] & 7];
sound4Skip = (freq << 8) / NOISE_MAGIC;
sound4NSteps = ioMem[NR43] & 0x08;
freq = freq / soundShiftClock[ioMem[NR43] >> 4];
sound4ShiftSkip = (freq << 8) / NOISE_MAGIC;
if(sound4NSteps)
sound4ShiftRight = 0x7fff;
else
sound4ShiftRight = 0x7f;
}
ioMem[address] = data;
break;
case NR50:
data &= 0x77;
soundLevel1 = data & 7;
soundLevel2 = (data >> 4) & 7;
ioMem[address] = data;
break;
case NR51:
soundBalance = (data & soundEnableFlag);
ioMem[address] = data;
break;
case NR52:
data &= 0x80;
data |= ioMem[NR52] & 15;
soundMasterOn = data & 0x80;
if(!(data & 0x80)) {
sound1On = 0;
sound2On = 0;
sound3On = 0;
sound4On = 0;
}
ioMem[address] = data;
break;
case 0x90:
case 0x91:
case 0x92:
case 0x93:
case 0x94:
case 0x95:
case 0x96:
case 0x97:
case 0x98:
case 0x99:
case 0x9a:
case 0x9b:
case 0x9c:
case 0x9d:
case 0x9e:
case 0x9f:
sound3WaveRam[(sound3Bank*0x10)^0x10+(address&15)] = data;
break;
}
}
void soundEvent(u32 address, u16 data)
{
switch(address) {
case SGCNT0_H:
data &= 0xFF0F;
soundControl = data & 0x770F;;
/*{
char feh[32];
wsprintf((LPSTR)&feh, "%x - %04x", armNextPC, data);
OutputDebugString((LPCSTR)&feh);
}*/
if(data & 0x0800) {
interp_reset(0);
soundDSFifoAWriteIndex = 0;
soundDSFifoAIndex = 0;
soundDSFifoACount = 0;
soundDSAValue = 0;
memset(soundDSFifoA, 0, 32);
}
soundDSAEnabled = (data & 0x0300) ? true : false;
soundDSATimer = (data & 0x0400) ? 1 : 0;
if(data & 0x8000) {
interp_reset(1);
soundDSFifoBWriteIndex = 0;
soundDSFifoBIndex = 0;
soundDSFifoBCount = 0;
soundDSBValue = 0;
memset(soundDSFifoB, 0, 32);
}
soundDSBEnabled = (data & 0x3000) ? true : false;
soundDSBTimer = (data & 0x4000) ? 1 : 0;
*((u16 *)&ioMem[address]) = data;
break;
case FIFOA_L:
case FIFOA_H:
soundDSFifoA[soundDSFifoAWriteIndex++] = data & 0xFF;
soundDSFifoA[soundDSFifoAWriteIndex++] = data >> 8;
soundDSFifoACount += 2;
soundDSFifoAWriteIndex &= 31;
*((u16 *)&ioMem[address]) = data;
break;
case FIFOB_L:
case FIFOB_H:
soundDSFifoB[soundDSFifoBWriteIndex++] = data & 0xFF;
soundDSFifoB[soundDSFifoBWriteIndex++] = data >> 8;
soundDSFifoBCount += 2;
soundDSFifoBWriteIndex &= 31;
*((u16 *)&ioMem[address]) = data;
break;
case 0x88:
data &= 0xC3FF;
*((u16 *)&ioMem[address]) = data;
break;
case 0x90:
case 0x92:
case 0x94:
case 0x96:
case 0x98:
case 0x9a:
case 0x9c:
case 0x9e:
*((u16 *)&sound3WaveRam[(sound3Bank*0x10)^0x10+(address&14)]) = data;
*((u16 *)&ioMem[address]) = data;
break;
}
}
void soundChannel1()
{
int vol = sound1EnvelopeVolume;
int freq = 0;
int value = 0;
if(sound1On && (sound1ATL || !sound1Continue)) {
sound1Index += soundQuality*sound1Skip;
sound1Index &= 0x1fffffff;
value = ((s8)sound1Wave[sound1Index>>24]) * vol;
}
soundBuffer[0][soundIndex] = value;
if(sound1On) {
if(sound1ATL) {
sound1ATL-=soundQuality;
if(sound1ATL <=0 && sound1Continue) {
ioMem[NR52] &= 0xfe;
sound1On = 0;
}
}
if(sound1EnvelopeATL) {
sound1EnvelopeATL-=soundQuality;
if(sound1EnvelopeATL<=0) {
if(sound1EnvelopeUpDown) {
if(sound1EnvelopeVolume < 15)
sound1EnvelopeVolume++;
} else {
if(sound1EnvelopeVolume)
sound1EnvelopeVolume--;
}
sound1EnvelopeATL += sound1EnvelopeATLReload;
}
}
if(sound1SweepATL) {
sound1SweepATL-=soundQuality;
if(sound1SweepATL<=0) {
freq = (((int)(ioMem[NR14]&7) << 8) | ioMem[NR13]);
int updown = 1;
if(sound1SweepUpDown)
updown = -1;
int newfreq = 0;
if(sound1SweepSteps) {
newfreq = freq + updown * freq / (1 << sound1SweepSteps);
if(newfreq == freq)
newfreq = 0;
} else
newfreq = freq;
if(newfreq < 0) {
sound1SweepATL += sound1SweepATLReload;
} else if(newfreq > 2047) {
sound1SweepATL = 0;
sound1On = 0;
ioMem[NR52] &= 0xfe;
} else {
sound1SweepATL += sound1SweepATLReload;
sound1Skip = SOUND_MAGIC/(2048 - newfreq);
ioMem[NR13] = newfreq & 0xff;
ioMem[NR14] = (ioMem[NR14] & 0xf8) |((newfreq >> 8) & 7);
}
}
}
}
}
void soundChannel2()
{
// int freq = 0;
int vol = sound2EnvelopeVolume;
int value = 0;
if(sound2On && (sound2ATL || !sound2Continue)) {
sound2Index += soundQuality*sound2Skip;
sound2Index &= 0x1fffffff;
value = ((s8)sound2Wave[sound2Index>>24]) * vol;
}
soundBuffer[1][soundIndex] = value;
if(sound2On) {
if(sound2ATL) {
sound2ATL-=soundQuality;
if(sound2ATL <= 0 && sound2Continue) {
ioMem[NR52] &= 0xfd;
sound2On = 0;
}
}
if(sound2EnvelopeATL) {
sound2EnvelopeATL-=soundQuality;
if(sound2EnvelopeATL <= 0) {
if(sound2EnvelopeUpDown) {
if(sound2EnvelopeVolume < 15)
sound2EnvelopeVolume++;
} else {
if(sound2EnvelopeVolume)
sound2EnvelopeVolume--;
}
sound2EnvelopeATL += sound2EnvelopeATLReload;
}
}
}
}
void soundChannel3()
{
int value = sound3Last;
if(sound3On && (sound3ATL || !sound3Continue)) {
sound3Index += soundQuality*sound3Skip;
if(sound3DataSize) {
sound3Index &= 0x3fffffff;
value = sound3WaveRam[sound3Index>>25];
} else {
sound3Index &= 0x1fffffff;
value = sound3WaveRam[sound3Bank*0x10 + (sound3Index>>25)];
}
if( (sound3Index & 0x01000000)) {
value &= 0x0f;
} else {
value >>= 4;
}
value -= 8;
value *= 2;
if(sound3ForcedOutput) {
value = ((value >> 1) + value) >> 1;
} else {
switch(sound3OutputLevel) {
case 0:
value = 0;
break;
case 1:
break;
case 2:
value = (value >> 1);
break;
case 3:
value = (value >> 2);
break;
}
}
sound3Last = value;
}
soundBuffer[2][soundIndex] = value;
if(sound3On) {
if(sound3ATL) {
sound3ATL-=soundQuality;
if(sound3ATL <= 0 && sound3Continue) {
ioMem[NR52] &= 0xfb;
sound3On = 0;
}
}
}
}
void soundChannel4()
{
int vol = sound4EnvelopeVolume;
int value = 0;
if(sound4Clock <= 0x0c) {
if(sound4On && (sound4ATL || !sound4Continue)) {
sound4Index += soundQuality*sound4Skip;
sound4ShiftIndex += soundQuality*sound4ShiftSkip;
if(sound4NSteps) {
while(sound4ShiftIndex > 0x1fffff) {
sound4ShiftRight = (((sound4ShiftRight << 6) ^
(sound4ShiftRight << 5)) & 0x40) |
(sound4ShiftRight >> 1);
sound4ShiftIndex -= 0x200000;
}
} else {
while(sound4ShiftIndex > 0x1fffff) {
sound4ShiftRight = (((sound4ShiftRight << 14) ^
(sound4ShiftRight << 13)) & 0x4000) |
(sound4ShiftRight >> 1);
sound4ShiftIndex -= 0x200000;
}
}
sound4Index &= 0x1fffff;
sound4ShiftIndex &= 0x1fffff;
value = ((sound4ShiftRight & 1)*2-1) * vol;
} else {
value = 0;
}
}
soundBuffer[3][soundIndex] = value;
if(sound4On) {
if(sound4ATL) {
sound4ATL-=soundQuality;
if(sound4ATL <= 0 && sound4Continue) {
ioMem[NR52] &= 0xfd;
sound4On = 0;
}
}
if(sound4EnvelopeATL) {
sound4EnvelopeATL-=soundQuality;
if(sound4EnvelopeATL <= 0) {
if(sound4EnvelopeUpDown) {
if(sound4EnvelopeVolume < 15)
sound4EnvelopeVolume++;
} else {
if(sound4EnvelopeVolume)
sound4EnvelopeVolume--;
}
sound4EnvelopeATL += sound4EnvelopeATLReload;
}
}
}
}
void soundDirectSoundA()
{
#ifndef NO_INTERPOLATION
directBuffer[0][soundIndex] = interp_pop(0, calc_rate(soundDSATimer)); //soundDSAValue;
#else
soundBuffer[4][soundIndex] = soundDSAValue;
#endif
}
void soundDirectSoundATimer()
{
if(soundDSAEnabled) {
if(soundDSFifoACount <= 16) {
CPUCheckDMA(3, 2);
if(soundDSFifoACount <= 16) {
soundEvent(FIFOA_L, (u16)0);
soundEvent(FIFOA_H, (u16)0);
soundEvent(FIFOA_L, (u16)0);
soundEvent(FIFOA_H, (u16)0);
soundEvent(FIFOA_L, (u16)0);
soundEvent(FIFOA_H, (u16)0);
soundEvent(FIFOA_L, (u16)0);
soundEvent(FIFOA_H, (u16)0);
}
}
soundDSAValue = (soundDSFifoA[soundDSFifoAIndex]);
interp_push(0, (s8)soundDSAValue << 8);
soundDSFifoAIndex = (++soundDSFifoAIndex) & 31;
soundDSFifoACount--;
} else
soundDSAValue = 0;
}
void soundDirectSoundB()
{
#ifndef NO_INTERPOLATION
directBuffer[1][soundIndex] = interp_pop(1, calc_rate(soundDSBTimer)); //soundDSBValue;
#else
soundBuffer[5][soundIndex] = soundDSBValue;
#endif
}
void soundDirectSoundBTimer()
{
if(soundDSBEnabled) {
if(soundDSFifoBCount <= 16) {
CPUCheckDMA(3, 4);
if(soundDSFifoBCount <= 16) {
soundEvent(FIFOB_L, (u16)0);
soundEvent(FIFOB_H, (u16)0);
soundEvent(FIFOB_L, (u16)0);
soundEvent(FIFOB_H, (u16)0);
soundEvent(FIFOB_L, (u16)0);
soundEvent(FIFOB_H, (u16)0);
soundEvent(FIFOB_L, (u16)0);
soundEvent(FIFOB_H, (u16)0);
}
}
soundDSBValue = (soundDSFifoB[soundDSFifoBIndex]);
interp_push(1, (s8)soundDSBValue << 8);
soundDSFifoBIndex = (++soundDSFifoBIndex) & 31;
soundDSFifoBCount--;
} else {
soundDSBValue = 0;
}
}
void soundTimerOverflow(int timer)
{
if(soundDSAEnabled && (soundDSATimer == timer)) {
soundDirectSoundATimer();
}
if(soundDSBEnabled && (soundDSBTimer == timer)) {
soundDirectSoundBTimer();
}
}
#ifndef max
#define max(a,b) (a)<(b)?(b):(a)
#endif
extern "C" int relvolume;
#ifndef NO_INTERPOLATION
void soundMix()
{
int res = 0;
int cgbRes = 0;
int ratio = ioMem[0x82] & 3;
int dsaRatio = ioMem[0x82] & 4;
int dsbRatio = ioMem[0x82] & 8;
if(soundBalance & 16) {
cgbRes = ((s8)soundBuffer[0][soundIndex]);
}
if(soundBalance & 32) {
cgbRes += ((s8)soundBuffer[1][soundIndex]);
}
if(soundBalance & 64) {
cgbRes += ((s8)soundBuffer[2][soundIndex]);
}
if(soundBalance & 128) {
cgbRes += ((s8)soundBuffer[3][soundIndex]);
}
if((soundControl & 0x0200) && (soundEnableFlag & 0x100)){
if(!dsaRatio)
res = ((s16)directBuffer[0][soundIndex])>>1;
else
res = ((s16)directBuffer[0][soundIndex]);
}
if((soundControl & 0x2000) && (soundEnableFlag & 0x200)){
if(!dsbRatio)
res += ((s16)directBuffer[1][soundIndex])>>1;
else
res += ((s16)directBuffer[1][soundIndex]);
}
res = (res * 170) >> 8;
cgbRes = (cgbRes * 52 * soundLevel1);
switch(ratio) {
case 0:
case 3: // prohibited, but 25%
cgbRes >>= 2;
break;
case 1:
cgbRes >>= 1;
break;
case 2:
break;
}
res += cgbRes;
if(soundEcho) {
res *= 2;
res += soundFilter[soundEchoIndex];
res /= 2;
soundFilter[soundEchoIndex++] = res;
}
if(soundLowPass) {
soundLeft[4] = soundLeft[3];
soundLeft[3] = soundLeft[2];
soundLeft[2] = soundLeft[1];
soundLeft[1] = soundLeft[0];
soundLeft[0] = res;
res = (soundLeft[4] + 2*soundLeft[3] + 8*soundLeft[2] + 2*soundLeft[1] +
soundLeft[0])/14;
}
switch(soundVolume) {
case 0:
case 1:
case 2:
case 3:
res *= (soundVolume+1);
break;
case 4:
res >>= 2;
break;
case 5:
res >>= 1;
break;
}
res = (float) res * ((float)relvolume / 1000.);
if(res > 32767)
res = 32767;
if(res < -32768)
res = -32768;
if(soundReverse)
soundFinalWave[++soundBufferIndex] = res;
else
soundFinalWave[soundBufferIndex++] = res;
res = 0;
cgbRes = 0;
if(soundBalance & 1) {
cgbRes = ((s8)soundBuffer[0][soundIndex]);
}
if(soundBalance & 2) {
cgbRes += ((s8)soundBuffer[1][soundIndex]);
}
if(soundBalance & 4) {
cgbRes += ((s8)soundBuffer[2][soundIndex]);
}
if(soundBalance & 8) {
cgbRes += ((s8)soundBuffer[3][soundIndex]);
}
if((soundControl & 0x0100) && (soundEnableFlag & 0x100)){
if(!dsaRatio)
res = ((s16)directBuffer[0][soundIndex])>>1;
else
res = ((s16)directBuffer[0][soundIndex]);
}
if((soundControl & 0x1000) && (soundEnableFlag & 0x200)){
if(!dsbRatio)
res += ((s16)directBuffer[1][soundIndex])>>1;
else
res += ((s16)directBuffer[1][soundIndex]);
}
res = (res * 170) >> 8;
cgbRes = (cgbRes * 52 * soundLevel1);
switch(ratio) {
case 0:
case 3: // prohibited, but 25%
cgbRes >>= 2;
break;
case 1:
cgbRes >>= 1;
break;
case 2:
break;
}
res += cgbRes;
if(soundEcho) {
res *= 2;
res += soundFilter[soundEchoIndex];
res /= 2;
soundFilter[soundEchoIndex++] = res;
if(soundEchoIndex >= 4000)
soundEchoIndex = 0;
}
if(soundLowPass) {
soundRight[4] = soundRight[3];
soundRight[3] = soundRight[2];
soundRight[2] = soundRight[1];
soundRight[1] = soundRight[0];
soundRight[0] = res;
res = (soundRight[4] + 2*soundRight[3] + 8*soundRight[2] + 2*soundRight[1] +
soundRight[0])/14;
}
switch(soundVolume) {
case 0:
case 1:
case 2:
case 3:
res *= (soundVolume+1);
break;
case 4:
res >>= 2;
break;
case 5:
res >>= 1;
break;
}
res = (float) res * ((float)relvolume / 1000.);
if(res > 32767)
res = 32767;
if(res < -32768)
res = -32768;
if(soundReverse)
soundFinalWave[-1+soundBufferIndex++] = res;
else
soundFinalWave[soundBufferIndex++] = res;
}
#else
void soundMix()
{
int res = 0;
int cgbRes = 0;
int ratio = ioMem[0x82] & 3;
int dsaRatio = ioMem[0x82] & 4;
int dsbRatio = ioMem[0x82] & 8;
if((soundBalance & 16)) {
cgbRes = ((s8)soundBuffer[0][soundIndex]);
}
if((soundBalance & 32)) {
cgbRes += ((s8)soundBuffer[1][soundIndex]);
}
if((soundBalance & 64)) {
cgbRes += ((s8)soundBuffer[2][soundIndex]);
}
if((soundBalance & 128)) {
cgbRes += ((s8)soundBuffer[3][soundIndex]);
}
if((soundControl & 0x0200) && (soundEnableFlag & 0x100)){
if(!dsaRatio)
res = ((s8)soundBuffer[4][soundIndex])>>1;
else
res = ((s8)soundBuffer[4][soundIndex]);
}
if((soundControl & 0x2000) && (soundEnableFlag & 0x200)){
if(!dsbRatio)
res += ((s8)soundBuffer[5][soundIndex])>>1;
else
res += ((s8)soundBuffer[5][soundIndex]);
}
res = (res * 170);
cgbRes = (cgbRes * 52 * soundLevel1);
switch(ratio) {
case 0:
case 3: // prohibited, but 25%
cgbRes >>= 2;
break;
case 1:
cgbRes >>= 1;
break;
case 2:
break;
}
res += cgbRes;
if(soundEcho) {
res *= 2;
res += soundFilter[soundEchoIndex];
res /= 2;
soundFilter[soundEchoIndex++] = res;
}
if(soundLowPass) {
soundLeft[4] = soundLeft[3];
soundLeft[3] = soundLeft[2];
soundLeft[2] = soundLeft[1];
soundLeft[1] = soundLeft[0];
soundLeft[0] = res;
res = (soundLeft[4] + 2*soundLeft[3] + 8*soundLeft[2] + 2*soundLeft[1] + soundLeft[0])/14;
}
switch(soundVolume) {
case 0:
case 1:
case 2:
case 3:
res *= (soundVolume+1);
break;
case 4:
res >>= 2;
break;
case 5:
res >>= 1;
break;
}
res = (float) res * ((float)relvolume / 1000.);
if(res > 32767)
res = 32767;
if(res < -32768)
res = -32768;
if(soundReverse)
soundFinalWave[++soundBufferIndex] = res;
else
soundFinalWave[soundBufferIndex++] = res;
res = 0;
cgbRes = 0;
if((soundBalance & 1)) {
cgbRes = ((s8)soundBuffer[0][soundIndex]);
}
if((soundBalance & 2)) {
cgbRes += ((s8)soundBuffer[1][soundIndex]);
}
if((soundBalance & 4)) {
cgbRes += ((s8)soundBuffer[2][soundIndex]);
}
if((soundBalance & 8)) {
cgbRes += ((s8)soundBuffer[3][soundIndex]);
}
if((soundControl & 0x0100) && (soundEnableFlag & 0x100)){
if(!dsaRatio)
res = ((s8)soundBuffer[4][soundIndex])>>1;
else
res = ((s8)soundBuffer[4][soundIndex]);
}
if((soundControl & 0x1000) && (soundEnableFlag & 0x200)){
if(!dsbRatio)
res += ((s8)soundBuffer[5][soundIndex])>>1;
else
res += ((s8)soundBuffer[5][soundIndex]);
}
res = (res * 170);
cgbRes = (cgbRes * 52 * soundLevel1);
switch(ratio) {
case 0:
case 3: // prohibited, but 25%
cgbRes >>= 2;
break;
case 1:
cgbRes >>= 1;
break;
case 2:
break;
}
res += cgbRes;
if(soundEcho) {
res *= 2;
res += soundFilter[soundEchoIndex];
res /= 2;
soundFilter[soundEchoIndex++] = res;
if(soundEchoIndex >= 4000)
soundEchoIndex = 0;
}
if(soundLowPass) {
soundRight[4] = soundRight[3];
soundRight[3] = soundRight[2];
soundRight[2] = soundRight[1];
soundRight[1] = soundRight[0];
soundRight[0] = res;
res = (soundRight[4] + 2*soundRight[3] + 8*soundRight[2] + 2*soundRight[1] + soundRight[0])/14;
}
switch(soundVolume) {
case 0:
case 1:
case 2:
case 3:
res *= (soundVolume+1);
break;
case 4:
res >>= 2;
break;
case 5:
res >>= 1;
break;
}
res = (float) res * ((float)relvolume / 1000.);
if(res > 32767)
res = 32767;
if(res < -32768)
res = -32768;
if(soundReverse)
soundFinalWave[-1+soundBufferIndex++] = res;
else
soundFinalWave[soundBufferIndex++] = res;
}
#endif
extern "C" void DisplayError (char * Message, ...);
//int began_seek = 1;
extern "C" double decode_pos_ms;
extern "C" int seek_needed;
extern "C" void end_of_track(void);
extern "C" void _pause(void);
extern "C" int TrackLength;
extern "C" int FadeLength;
extern "C" int IgnoreTrackLength, DefaultLength;
extern "C" int playforever;
extern "C" int TrailingSilence;
extern "C" int DetectSilence, silencedetected, silencelength;
extern "C" int sndSamplesPerSec;
extern "C" int cpupercent, sndSamplesPerSec, sndNumChannels;
//extern "C" In_Module mod;
unsigned short prevsound[2];
int prevtime;
int didseek=false;
double playtime=0;
int outputtimeread=0;
int buffertime;
int decodeposmod;
void soundTick()
{
if (seek_needed == -1) //if no seek is needed
{
//if(systemSoundOn) { //needed? I don't think so
if(soundMasterOn && !stopState) {
soundChannel1();
soundChannel2();
soundChannel3();
soundChannel4();
soundDirectSoundA();
soundDirectSoundB();
if ((decode_pos_ms < TrackLength) || IgnoreTrackLength || playforever)
soundMix();
else
{
soundFinalWave[soundBufferIndex++] = 0;
soundFinalWave[soundBufferIndex++] = 0;
}
//check for silence...
decodeposmod=(int)decode_pos_ms%500;
if(((decodeposmod>=0)&&(decodeposmod<=10))||didseek)
{
if((!outputtimeread)||didseek)
{
//mod.SetInfo(cpupercent,sndSamplesPerSec/1000,sndNumChannels,1);
int outputtime=mod.outMod->GetOutputTime();
int writtentime=mod.outMod->GetWrittenTime();
if(outputtime<0)
outputtime=0;
if(writtentime<0)
writtentime=0;
buffertime = writtentime-outputtime;
if(buffertime<0)
buffertime=0;
playtime = (decode_pos_ms - (buffertime));
outputtimeread=1;
}
else
playtime += (1./44100.)*1000.;
}
else
{
playtime += (1./44100.)*1000.;
outputtimeread=0;
}
if(DetectSilence)
{
if(!silencedetected||decode_pos_ms<100||didseek)
{
/*if(decode_pos_ms<100)
{
//prevtime=(int)(decode_pos_ms - (mod.outMod->GetWrittenTime()-mod.outMod->GetOutputTime()));
//playtime=prevtime;
}
else*/
prevtime=(int)playtime;
didseek=false;
}
//if((soundFinalWave[soundBufferIndex-2] <= 0x200 || soundFinalWave[soundBufferIndex-2] >= 0xFE00) ||
if ((soundFinalWave[soundBufferIndex-2] - prevsound[0]) <= 0x8 )
//|| (prevsound[0] - soundFinalWave[soundBufferIndex-2]) <= 0x8)
{
silencedetected++;
// if((silencedetected%0x100)==81)
// DisplayError("Silence Detected count = %d",silencedetected);
}
else
silencedetected=0;
prevsound[0]=soundFinalWave[soundBufferIndex-2];
//if((soundFinalWave[soundBufferIndex-1] <= 0x200 || soundFinalWave[soundBufferIndex-1] >= 0xFE00) ||
if ((soundFinalWave[soundBufferIndex-1] - prevsound[1]) <= 0x8 )
// (prevsound[1] - soundFinalWave[soundBufferIndex-1]) <= 0x8)
silencedetected++;
else
silencedetected=0;
prevsound[1]=soundFinalWave[soundBufferIndex-1];
//if(silencedetected>(silencelength*2*sndSamplesPerSec))
//if((silencedetected>0)&&((decode_pos_ms - (mod.outMod->GetWrittenTime()-mod.outMod->GetOutputTime())-prevtime) > (silencelength*1000)))
if((silencedetected>0)&&((playtime-prevtime) > ((silencelength*1000)+buffertime)))
{
// DisplayError("%d %d %d", silencedetected,silencelength*2*sndSamplesPerSec,sndSamplesPerSec);
outputtimeread=0;
silencedetected=0;
end_of_track();
}
}
//check for fade...
if ((decode_pos_ms >= TrackLength-FadeLength) && !IgnoreTrackLength && !playforever)
{
//if (decode_pos_ms - (mod.outMod->GetWrittenTime()-mod.outMod->GetOutputTime()) < TrackLength) //if we're in the fade zone
if(playtime < TrackLength)
{
((short *)soundFinalWave)[soundBufferIndex-2] *= (float)(1-((decode_pos_ms-(TrackLength-FadeLength))/FadeLength));
((short *)soundFinalWave)[soundBufferIndex-1] *= (float)(1-((decode_pos_ms-(TrackLength-FadeLength))/FadeLength));
}
else if(playtime < (TrackLength + TrailingSilence))
{
soundFinalWave[soundBufferIndex-2] = 0;
soundFinalWave[soundBufferIndex-1] = 0;
}
else
{
soundFinalWave[soundBufferIndex-2] = 0;
soundFinalWave[soundBufferIndex-1] = 0;
outputtimeread=0;
//DisplayError("playtime=%d, tracklength=%d, decode_pos_ms=%d\nGetOutputTime()=%d, GetWrittenTime=%d",(int)playtime,(int)TrackLength, (int)decode_pos_ms,mod.outMod->GetOutputTime(),mod.outMod->GetWrittenTime());
end_of_track();
}
}
} else {
soundFinalWave[soundBufferIndex++] = 0;
soundFinalWave[soundBufferIndex++] = 0;
}
soundIndex++;
if(2*soundBufferIndex >= soundBufferLen) {
if(systemSoundOn) {
if(soundPaused) {
soundResume();
}
systemWriteDataToSoundBuffer();
}
soundIndex = 0;
soundBufferIndex = 0;
// }
}
}
else
{
//decode_pos_ms += (1. / 44100.) * (double)soundQuality; //0.02267276353518178520905584379325; //mathematically, i couldn't obtain this exact number. Found it from testing. This is an average, but really close.
decode_pos_ms += (1./44100.)*1000.;
didseek=true;
if (decode_pos_ms >= seek_needed)
seek_needed = -1;
}
}
void soundShutdown()
{
systemSoundShutdown();
}
void soundPause()
{
systemSoundPause();
soundPaused = 1;
}
void soundResume()
{
systemSoundResume();
soundPaused = 0;
}
void soundEnable(int channels)
{
int c = channels & 0x0f;
soundEnableFlag |= ((channels & 0x30f) |c | (c << 4));
if(ioMem)
soundBalance = (ioMem[NR51] & soundEnableFlag);
}
void soundDisable(int channels)
{
int c = channels & 0x0f;
soundEnableFlag &= (~((channels & 0x30f)|c|(c<<4)));
if(ioMem)
soundBalance = (ioMem[NR51] & soundEnableFlag);
}
int soundGetEnable()
{
return (soundEnableFlag & 0x30f);
}
void soundReset()
{
systemSoundReset();
soundPaused = 1;
soundPlay = 0;
SOUND_CLOCK_TICKS = soundQuality * USE_TICKS_AS;
soundTicks = SOUND_CLOCK_TICKS;
soundNextPosition = 0;
soundMasterOn = 1;
soundIndex = 0;
soundBufferIndex = 0;
soundLevel1 = 7;
soundLevel2 = 7;
sound1On = 0;
sound1ATL = 0;
sound1Skip = 0;
sound1Index = 0;
sound1Continue = 0;
sound1EnvelopeVolume = 0;
sound1EnvelopeATL = 0;
sound1EnvelopeUpDown = 0;
sound1EnvelopeATLReload = 0;
sound1SweepATL = 0;
sound1SweepATLReload = 0;
sound1SweepSteps = 0;
sound1SweepUpDown = 0;
sound1SweepStep = 0;
sound1Wave = soundWavePattern[2];
sound2On = 0;
sound2ATL = 0;
sound2Skip = 0;
sound2Index = 0;
sound2Continue = 0;
sound2EnvelopeVolume = 0;
sound2EnvelopeATL = 0;
sound2EnvelopeUpDown = 0;
sound2EnvelopeATLReload = 0;
sound2Wave = soundWavePattern[2];
sound3On = 0;
sound3ATL = 0;
sound3Skip = 0;
sound3Index = 0;
sound3Continue = 0;
sound3OutputLevel = 0;
sound3Last = 0;
sound3Bank = 0;
sound3DataSize = 0;
sound3ForcedOutput = 0;
sound4On = 0;
sound4Clock = 0;
sound4ATL = 0;
sound4Skip = 0;
sound4Index = 0;
sound4ShiftRight = 0x7f;
sound4NSteps = 0;
sound4CountDown = 0;
sound4Continue = 0;
sound4EnvelopeVolume = 0;
sound4EnvelopeATL = 0;
sound4EnvelopeUpDown = 0;
sound4EnvelopeATLReload = 0;
sound1On = 0;
sound2On = 0;
sound3On = 0;
sound4On = 0;
int addr = 0x90;
while(addr < 0xA0) {
ioMem[addr++] = 0x00;
ioMem[addr++] = 0xff;
}
addr = 0;
while(addr < 0x20) {
sound3WaveRam[addr++] = 0x00;
sound3WaveRam[addr++] = 0xff;
}
memset(soundFinalWave, 0, soundBufferLen);
memset(soundFilter, 0, sizeof(soundFilter));
soundEchoIndex = 0;
}
extern void setupSound(void);
bool soundInit()
{
setupSound();
memset(soundBuffer[0], 0, 735);
memset(soundBuffer[1], 0, 735);
memset(soundBuffer[2], 0, 735);
memset(soundBuffer[3], 0, 735);
#ifndef NO_INTERPOLATION
memset(directBuffer[0], 0, 735*2);
memset(directBuffer[1], 0, 735*2);
#else
memset(soundBuffer[4], 0, 735);
memset(soundBuffer[5], 0, 735);
#endif
memset(soundFinalWave, 0, soundBufferLen);
soundPaused = true;
return true;
}
void soundSetQuality(int quality)
{
if(soundQuality != quality && systemCanChangeSoundQuality()) {
if(!soundOffFlag)
soundShutdown();
soundQuality = quality;
soundNextPosition = 0;
if(!soundOffFlag)
soundInit();
SOUND_CLOCK_TICKS = USE_TICKS_AS * soundQuality;
soundIndex = 0;
soundBufferIndex = 0;
} else if(soundQuality != quality) {
soundNextPosition = 0;
SOUND_CLOCK_TICKS = USE_TICKS_AS * soundQuality;
soundIndex = 0;
soundBufferIndex = 0;
}
}
void soundSaveGame(gzFile gzFile)
{
utilWriteData(gzFile, soundSaveStruct);
utilWriteData(gzFile, soundSaveStructV2);
utilGzWrite(gzFile, &soundQuality, sizeof(int));
}
void soundReadGame(gzFile gzFile, int version)
{
utilReadData(gzFile, soundSaveStruct);
if(version >= SAVE_GAME_VERSION_3) {
utilReadData(gzFile, soundSaveStructV2);
} else {
sound3Bank = (ioMem[NR30] >> 6) & 1;
sound3DataSize = (ioMem[NR30] >> 5) & 1;
sound3ForcedOutput = (ioMem[NR32] >> 7) & 1;
// nothing better to do here...
memcpy(&sound3WaveRam[0x00], &ioMem[0x90], 0x10);
memcpy(&sound3WaveRam[0x10], &ioMem[0x90], 0x10);
}
soundBufferIndex = soundIndex * 2;
int quality = 1;
utilGzRead(gzFile, &quality, sizeof(int));
soundSetQuality(quality);
sound1Wave = soundWavePattern[ioMem[NR11] >> 6];
sound2Wave = soundWavePattern[ioMem[NR21] >> 6];
}
| [
"[email protected]"
]
| [
[
[
1,
1727
]
]
]
|
e19e233b639a8245239e74189cd0a08d3e25a743 | f9774f8f3c727a0e03c170089096d0118198145e | /传奇mod/mirserver/SelGate/LoginGate.cpp | 67d07002b6e8592385394dcbf2083216182165f1 | []
| no_license | sdfwds4/fjljfatchina | 62a3bcf8085f41d632fdf83ab1fc485abd98c445 | 0503d4aa1907cb9cf47d5d0b5c606df07217c8f6 | refs/heads/master | 2021-01-10T04:10:34.432964 | 2010-03-07T09:43:28 | 2010-03-07T09:43:28 | 48,106,882 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,696 | cpp | // LoginGate.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
// **************************************************************************************
BOOL InitApplication(HANDLE hInstance);
BOOL InitInstance(HANDLE hInstance, int nCmdShow);
LPARAM APIENTRY MainWndProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam);
BOOL jRegSetKey(LPCTSTR pSubKeyName, LPCTSTR pValueName, DWORD dwFlags, LPBYTE pValue, DWORD nValueSize);
BOOL jRegGetKey(LPCTSTR pSubKeyName, LPCTSTR pValueName, LPBYTE pValue);
BOOL CALLBACK ConfigDlgFunc(HWND hWndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
// **************************************************************************************
//
// Global Variables Definition
//
// **************************************************************************************
HINSTANCE g_hInst = NULL; // Application instance
HWND g_hMainWnd = NULL; // Main window handle
HWND g_hLogMsgWnd = NULL;
HWND g_hToolBar = NULL;
HWND g_hStatusBar = NULL;
static WSADATA g_wsd;
//list<CUserInfo> TUserInfoList;
//CUserInfo TUserInfoList[1500];
TBBUTTON tbButtons[] =
{
{ 0, IDM_STARTSERVICE, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0L, 0},
{ 1, IDM_STOPSERVICE, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0L, 0},
{ 0, 0, 0, BTNS_SEP, 0L, 0},
{ 2, IDM_FONTCOLOR, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0L, 0},
{ 3, IDM_BACKCOLOR, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0L, 0},
};
// **************************************************************************************
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
MSG msg;
#ifndef _SOCKET_ASYNC_IO
if (CheckAvailableIOCP())
{
#endif
if (!InitApplication(hInstance))
return (FALSE);
if (!InitInstance(hInstance, nCmdShow))
return (FALSE);
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
#ifndef _SOCKET_ASYNC_IO
}
else
{
TCHAR szMsg[1024];
LoadString(hInstance, IDS_NOTWINNT, szMsg, sizeof(szMsg));
MessageBox(NULL, szMsg, _LOGINGATE_SERVER_TITLE, MB_OK|MB_ICONINFORMATION);
return -1;
}
#endif
return (msg.wParam);
}
// **************************************************************************************
//
//
//
// **************************************************************************************
BOOL InitApplication(HANDLE hInstance)
{
WNDCLASS wc;
wc.style = CS_GLOBALCLASS|CS_HREDRAW|CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC)MainWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hIcon = LoadIcon((HINSTANCE)hInstance, MAKEINTRESOURCE(IDI_MIR2));
wc.hInstance = (HINSTANCE)hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszMenuName = MAKEINTRESOURCE(IDR_MAINMENU);
wc.lpszClassName = _LOGINGATE_SERVER_CLASS;
return RegisterClass(&wc);
}
// **************************************************************************************
//
//
//
// **************************************************************************************
BOOL InitInstance(HANDLE hInstance, int nCmdShow)
{
g_hInst = (HINSTANCE)hInstance;
INITCOMMONCONTROLSEX icex;
icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
icex.dwICC = ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES | ICC_INTERNET_CLASSES;
InitCommonControlsEx(&icex);
g_hMainWnd = CreateWindowEx(0, _LOGINGATE_SERVER_CLASS, _LOGINGATE_SERVER_TITLE,
WS_OVERLAPPEDWINDOW|WS_VISIBLE,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, (HINSTANCE)hInstance, NULL);
g_hToolBar = CreateToolbarEx(g_hMainWnd, WS_CHILD|CCS_TOP|WS_VISIBLE|WS_BORDER,
_IDW_TOOLBAR, sizeof(tbButtons) / sizeof(TBBUTTON), (HINSTANCE)hInstance, IDB_TOOLBAR,
(LPCTBBUTTON)&tbButtons, sizeof(tbButtons) / sizeof(TBBUTTON),
_BMP_CX, _BMP_CY, _BMP_CX, _BMP_CY, sizeof(TBBUTTON));
RECT rcMainWnd, rcToolBar, rcStatusBar;
GetClientRect(g_hMainWnd, &rcMainWnd);
GetWindowRect(g_hToolBar, &rcToolBar);
g_hStatusBar = CreateWindowEx(0L, STATUSCLASSNAME, _TEXT(""), WS_CHILD|WS_BORDER|WS_VISIBLE|SBS_SIZEGRIP,
0, rcMainWnd.bottom - _STATUS_HEIGHT, (rcMainWnd.right - rcMainWnd.left), _STATUS_HEIGHT, g_hMainWnd, (HMENU)_IDW_STATUSBAR, g_hInst, NULL);
int nStatusPartsWidths[_NUMOFMAX_STATUS_PARTS];
int nCnt = 0;
for (int i = _NUMOFMAX_STATUS_PARTS - 1; i >= 0; i--)
nStatusPartsWidths[nCnt++] = (rcMainWnd.right - rcMainWnd.left) - (90 * i);
SendMessage(g_hStatusBar, SB_SETPARTS, _NUMOFMAX_STATUS_PARTS, (LPARAM)nStatusPartsWidths);
SendMessage(g_hStatusBar, SB_SETTEXT, MAKEWORD(1, 0), (LPARAM)_TEXT("Not Connected"));
GetWindowRect(g_hStatusBar, &rcStatusBar);
g_hLogMsgWnd = CreateWindowEx(WS_EX_CLIENTEDGE, WC_LISTVIEW, _TEXT(""),
WS_CHILD|WS_VISIBLE|WS_BORDER|LVS_REPORT|LVS_EDITLABELS,
0, (rcToolBar.bottom - rcToolBar.top), (rcMainWnd.right - rcMainWnd.left),
(rcMainWnd.bottom - rcMainWnd.top) - (rcToolBar.bottom - rcToolBar.top) - (rcStatusBar.bottom - rcStatusBar.top),
g_hMainWnd, NULL, (HINSTANCE)hInstance, NULL);
ListView_SetExtendedListViewStyleEx(g_hLogMsgWnd, 0, LVS_EX_FULLROWSELECT);
LV_COLUMN lvc;
TCHAR szText[64];
lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
lvc.fmt = LVCFMT_LEFT;
lvc.cx = 150;
lvc.pszText = szText;
for (i = 0; i < 3; i++)
{
lvc.iSubItem = i;
LoadString((HINSTANCE)hInstance, IDS_LVS_LABEL1 + i, szText, sizeof(szText));
ListView_InsertColumn(g_hLogMsgWnd, i, &lvc);
}
SendMessage(g_hToolBar, TB_SETSTATE, (WPARAM)IDM_STOPSERVICE, (LPARAM)MAKELONG(TBSTATE_INDETERMINATE, 0));
ShowWindow(g_hMainWnd, SW_SHOW);
UpdateWindow(g_hMainWnd);
if (WSAStartup(MAKEWORD(2, 2), &g_wsd) != 0)
return (FALSE);
//
BYTE btInstalled;
if (!jRegGetKey(_LOGINGATE_SERVER_REGISTRY, _TEXT("Installed"), (LPBYTE)&btInstalled))
DialogBox(g_hInst, MAKEINTRESOURCE(IDD_CONFIGDLG), NULL, (DLGPROC)ConfigDlgFunc);
return TRUE;
}
// **************************************************************************************
//
//
//
// **************************************************************************************
int AddNewLogMsg()
{
LV_ITEM lvi;
TCHAR szText[64];
int nCount = ListView_GetItemCount(g_hLogMsgWnd);
if (nCount >= 50)
{
ListView_DeleteItem(g_hLogMsgWnd, 0);
nCount--;
}
lvi.mask = LVIF_TEXT;
lvi.iItem = nCount;
lvi.iSubItem = 0;
_tstrdate(szText);
lvi.pszText = szText;
ListView_InsertItem(g_hLogMsgWnd, &lvi);
_tstrtime(szText);
ListView_SetItemText(g_hLogMsgWnd, nCount, 1, szText);
return nCount;
}
void InsertLogMsg(UINT nID)
{
TCHAR szText[256];
int nCount = AddNewLogMsg();
LoadString(g_hInst, nID, szText, sizeof(szText));
ListView_SetItemText(g_hLogMsgWnd, nCount, 2, szText);
ListView_Scroll(g_hLogMsgWnd, 0, 8);
}
void InsertLogMsg(LPTSTR lpszMsg)
{
int nCount = AddNewLogMsg();
ListView_SetItemText(g_hLogMsgWnd, nCount, 2, lpszMsg);
ListView_Scroll(g_hLogMsgWnd, 0, 8);
}
/*
void InsertLogPacket(char *pszPacket)
{
LPTGateToSvrHeader lpHdr = (LPTGateToSvrHeader)pszPacket;
TCHAR szMsg[256];
_stprintf(szMsg, "%c%c%d%d%d%s", lpHdr->szPrefix, lpHdr->szID, lpHdr->btGateIndex, lpHdr->nSocket, lpHdr->wDataLength,
(char *)lpHdr + GTS_HEADER_SIZE);
InsertLogMsg(szMsg);
}
*/ | [
"fjljfat@4a88d1ba-22b1-11df-8001-4f4b503b426e"
]
| [
[
[
1,
257
]
]
]
|
fdc20d4d37f2b4506aeaaf9600a27ce02e851ff1 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/samples/Redirect/RedirectHandlers.cpp | d028c8b44ee3606fa11a502bae2b8a38b4cb72e3 | [
"Apache-2.0"
]
| permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,693 | cpp | /*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: RedirectHandlers.cpp,v 1.10 2004/09/08 13:55:33 peiyongz Exp $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUni.hpp>
#include <xercesc/sax/AttributeList.hpp>
#include <xercesc/sax/SAXParseException.hpp>
#include <xercesc/sax/SAXException.hpp>
#include <xercesc/framework/LocalFileInputSource.hpp>
#include "Redirect.hpp"
#include <string.h>
// ---------------------------------------------------------------------------
// Local constant data
//
// gFileToTrap
// This is the file that we are looking for in the entity handler, to
// redirect to another file.
//
// gRedirectToFile
// This is the file that we are going to redirect the parser to.
// ---------------------------------------------------------------------------
static const XMLCh gFileToTrap[] =
{
chLatin_p, chLatin_e, chLatin_r, chLatin_s, chLatin_o, chLatin_n
, chLatin_a, chLatin_l, chPeriod, chLatin_d, chLatin_t, chLatin_d, chNull
};
static const XMLCh gRedirectToFile[] =
{
chLatin_r, chLatin_e, chLatin_d, chLatin_i, chLatin_r, chLatin_e
, chLatin_c, chLatin_t, chPeriod, chLatin_d, chLatin_t, chLatin_d, chNull
};
// ---------------------------------------------------------------------------
// RedirectHandlers: Constructors and Destructor
// ---------------------------------------------------------------------------
RedirectHandlers::RedirectHandlers() :
fElementCount(0)
, fAttrCount(0)
, fCharacterCount(0)
, fSpaceCount(0)
{
}
RedirectHandlers::~RedirectHandlers()
{
}
// ---------------------------------------------------------------------------
// RedirectHandlers: Implementation of the SAX DocumentHandler interface
// ---------------------------------------------------------------------------
void RedirectHandlers::startElement(const XMLCh* const name
, AttributeList& attributes)
{
fElementCount++;
fAttrCount += attributes.getLength();
}
void RedirectHandlers::characters( const XMLCh* const chars
, const unsigned int length)
{
fCharacterCount += length;
}
void RedirectHandlers::ignorableWhitespace( const XMLCh* const chars
, const unsigned int length)
{
fSpaceCount += length;
}
void RedirectHandlers::resetDocument()
{
fAttrCount = 0;
fCharacterCount = 0;
fElementCount = 0;
fSpaceCount = 0;
}
// ---------------------------------------------------------------------------
// RedirectHandlers: Overrides of the SAX ErrorHandler interface
// ---------------------------------------------------------------------------
void RedirectHandlers::error(const SAXParseException& e)
{
XERCES_STD_QUALIFIER cerr << "\nError at (file " << StrX(e.getSystemId())
<< ", line " << e.getLineNumber()
<< ", char " << e.getColumnNumber()
<< "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
}
void RedirectHandlers::fatalError(const SAXParseException& e)
{
XERCES_STD_QUALIFIER cerr << "\nFatal Error at (file " << StrX(e.getSystemId())
<< ", line " << e.getLineNumber()
<< ", char " << e.getColumnNumber()
<< "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
}
void RedirectHandlers::warning(const SAXParseException& e)
{
XERCES_STD_QUALIFIER cerr << "\nWarning at (file " << StrX(e.getSystemId())
<< ", line " << e.getLineNumber()
<< ", char " << e.getColumnNumber()
<< "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
}
// -----------------------------------------------------------------------
// Handlers for the SAX EntityResolver interface
// -----------------------------------------------------------------------
InputSource* RedirectHandlers::resolveEntity(const XMLCh* const publicId
, const XMLCh* const systemId)
{
//
// If its our file, then create a new URL input source for the file that
// we want to really be used. Otherwise, just return zero to let the
// default action occur.
//
// We cannot assume that the XMLCh type is ok to pass to wcscmp(), so
// just do a comparison ourselves.
//
const XMLCh* s1 = gFileToTrap;
const XMLCh* s2 = systemId;
while (true)
{
// Break out on any difference
if (*s1 != *s2)
return 0;
// If one is null, then both were null, so they are equal
if (!*s1)
break;
// Else get the next char
s1++;
s2++;
}
// They were equal, so redirect to our other file
return new LocalFileInputSource(gRedirectToFile);
}
| [
"[email protected]"
]
| [
[
[
1,
169
]
]
]
|
ce3ea48d64fcd29f893ff5d4ffe0f860f26d5800 | 6ad58793dd1f859c10d18356c731b54f935c5e9e | /MYUltilityClass/PSP_ChineseUtil.cpp | baa6c917a57391c2d2367978006c265980ea2460 | []
| no_license | ntchris/kittybookportable | 83f2cf2fbc2cd1243b585f85fb6bc5dd285aa227 | 933a5b096524c24390c32c654ce8624ee35d3835 | refs/heads/master | 2021-01-10T05:49:32.035999 | 2009-06-12T08:50:21 | 2009-06-12T08:50:21 | 45,051,534 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 31,353 | cpp |
//#define __VC__
#ifdef __VC__
#include <conio.h>
#endif
#include <PSP_ChineseUtil.h>
#include <CommonString.h>
#include <PSP_Global.h>
#include <GBKToUnicodeTable.h>
#include <unicodeJISTable.h>
#include <unicodeToGBKTable.h>
#include <PSP_TrueTypeFont.h>
#include <PSP_Window.h>
#ifdef __PSPSDK__
#include <PSP_GRAPHICS.h>
//#define printf pspDebugScreenPrintf
#else
//#include <stdio.h>
#endif
#include <stdio.h>
#include <PSP_AscCnFont.h>
const bool debugCache_cg = true;
//static member for class HanZiCache
HanZi16CachedItem HanZiCache::bufferedHanZi_am [ maxHanZiStorageSize ];
unsigned short HanZiCache::currentSize = 0;
bool HanZiCache::isInited = false;
PSP_TrueTypeFont * pspTrueTypeFont_cgp = new PSP_TrueTypeFont ();
TTF_HanZiCache * TTF_HanZiCache_cgp = new TTF_HanZiCache();// ::getInstance();;
void HanZiCache ::selfTest ( void )
{
unsigned short i,c = HanZiCache::currentSize;
HanZi16CachedItem *p;
for ( i=0;i<c;i++)
{ p = HanZiCache ::getCachedItem ( i );
printf ( " hanzi: %u freq: %u \n", p->hanZi, p->frequency );
}
}
/*
//move the newly increased item forward sort by freq
unsigned short HanZiCache ::sortCachedItem ( unsigned short index )
{
if ( debugCache_cg )
{
printf( "sortCachedItem %u \n", index );
}
if ( index <= 0 )
{ // this is the first item
// no need to sort
return index;
}
HanZiCachedItem *incItem_p, *testItem_p;
incItem_p = getCachedItem( index );
testItem_p = getCachedItem( index - 1 );
// eg 1 1 1 3 make sure find the first index of 1.
unsigned testItemIndex = index -1 , foundIndex = 0;
while( true )
{
testItem_p = getCachedItem( testItemIndex );
if ( testItem_p->frequency >= incItem_p->frequency )
{
// = should not happen, but just in case.
foundIndex = testItemIndex + 1;
break;
}
if ( testItemIndex == 0 )
{
foundIndex = testItemIndex ;
break;
}
testItemIndex --;
}
//switch tempItem_p and incItem_p;
HanZiCachedItem tempSwitch;
testItem_p = getCachedItem( foundIndex );
tempSwitch.frequency = testItem_p->frequency;
tempSwitch.hanZi = testItem_p->hanZi;
memcpy( &tempSwitch.hanZiBitMap,
&testItem_p->hanZiBitMap , oneHanZiUseByte_BMP );
testItem_p->frequency = incItem_p->frequency;
testItem_p->hanZi = incItem_p->hanZi;
memcpy( &testItem_p->hanZiBitMap, &incItem_p->hanZiBitMap, oneHanZiUseByte_BMP );
incItem_p->frequency = tempSwitch.frequency;
incItem_p->hanZi = tempSwitch.hanZi;
memcpy( &incItem_p->hanZiBitMap, &tempSwitch.hanZiBitMap, oneHanZiUseByte_BMP );
return foundIndex;
}
*/
void HanZiCache :: increaseFrequency( HanZi16CachedItem * cacheItem_p )
{
if ( debugCache_cg )
{
printf( "increaseFrequency %u \n", cacheItem_p->hanZi );
}
if( cacheItem_p ->frequency < (0xffff-1 ) )
{
cacheItem_p ->frequency ++;
}
//after increase, the position of this item should be move forward!
//to make the whole item list sorted
}
// before 1st time use, must use HanZiCache ::init() !!!!!!!
HanZi16FontBitMap * HanZiCache :: getHanZiBMP ( const HanZi & hanzi )
{
if ( ! HanZiCache::getIsInited() )
{
HanZiCache::init();
}
HanZi16FontBitMap *temp_hanZiBMP_p = NULL;
HanZi16CachedItem *tempCachedItem_P = NULL;
bool found = false;
unsigned int i = 0;
for(i=0;i<currentSize;i++)
{
tempCachedItem_P = getCachedItem( i );
if( tempCachedItem_P == NULL )
{ //impossible!!!!
return NULL;
}
if ( tempCachedItem_P->hanZi == hanzi.ushort )
{ //increase and resort
increaseFrequency( tempCachedItem_P );
//newIndex = HanZiCache ::sortCachedItem ( i );
//tempCachedItem_P = getCachedItem( newIndex );
temp_hanZiBMP_p = &(tempCachedItem_P->hanZi16BitMap);
found = true;
break;
}
}
if ( found )
{
return temp_hanZiBMP_p;
}
HanZi16FontBitMap *AddhanZiBMP ;
//not found in the cache ???
// let's add it to the cache !!!!!
if( !found )
{
if ( debugCache_cg )
{
printf( "not found in cache hanzi: %u \n", hanzi.ushort );
}
bool r;
unsigned short roomIndex;
roomIndex = HanZiCache::getRoomForNewHanZi( );
tempCachedItem_P = HanZiCache::getCachedItem ( roomIndex );
tempCachedItem_P ->frequency = 0;
tempCachedItem_P ->hanZi = hanzi.ushort;
AddhanZiBMP = & tempCachedItem_P->hanZi16BitMap;
r = PSP_CNFONTS16_16::drawHanZi16ToBMP( hanzi.ushort , *AddhanZiBMP );
if( !r )
{
printf(" HanZiFontBitMap tempAddhanZiBMP size not enough for width*heigh!!\n");
}
}
if ( debugCache_cg )
{
if( found )printf( "found in cache index %u \n", i );
}
return AddhanZiBMP;
}
unsigned short HanZiCache :: getRoomForNewHanZi( void )
{
unsigned short roomIndex;
if ( HanZiCache::currentSize < maxHanZiStorageSize )
{
//There is enough room, let's add one
currentSize ++;
roomIndex = currentSize -1;
}
else
{ // There is NOT enough ROOM, let's find a least freq item to replace
roomIndex = HanZiCache::getLeastFreqIndex( );
}
return roomIndex;
}
unsigned short HanZiCache :: getLeastFreqIndex ( void )
{
unsigned short leastFreq = 0xffff;
unsigned short index = 0;
unsigned short i;
HanZi16CachedItem *tempCachedItem_P = NULL;
for( i =0;i< HanZiCache::currentSize;i++ )
{
tempCachedItem_P = HanZiCache ::getCachedItem(i);
if( tempCachedItem_P == NULL)
{
printf( "impossible ! tempCachedItem_P = NULL !!! \n ");
return 0;
}
if( tempCachedItem_P->frequency < leastFreq )
{
leastFreq = tempCachedItem_P->frequency ;
index = i;
if( tempCachedItem_P->frequency == 0 )
{
// if freq = 0 , that's it.
break;
}
}
}
return index;
}
void HanZiCache :: init ( void )
{
if ( debugCache_cg )
{ printf( "initing \n" );
}
if( HanZiCache::isInited ) return ;
isInited = true;
unsigned short i ;
for ( i=0 ; i< maxHanZiStorageSize ;i++)
{
bufferedHanZi_am[i].frequency = 0;
bufferedHanZi_am[i].hanZi = 0;
}
memset ( bufferedHanZi_am , 0, sizeof( HanZi16CachedItem) * maxHanZiStorageSize ) ;
currentSize = 0;
}
/*
//remove the freq == 0 hanzi bmp if full
unsigned short HanZiCache::addHanZiBMP ( unsigned short hanzi, const HanZiFontBitMap &hanzibmp )
{
unsigned short replaceIndex;
if ( debugCache_cg )
{ printf( "adding %u ", hanzi );
}
unsigned short index ;
if ( HanZiCache::currentSize < maxHanZiStorageSize )
{ //let's add one
currentSize ++;
replaceIndex = currentSize -1;
}
else
{
replaceIndex = HanZiCache::getLeastFreqIndex( void );
}
HanZiFontBitMap *temp_hanZiBMP_p = NULL;
HanZiCachedItem *tempCachedItem_P = NULL;
tempCachedItem_P = HanZiCache::getCachedItem( replaceIndex );
tempCachedItem_P->frequency = 0;
tempCachedItem_P->hanZi = hanzi;
memcpy( tempCachedItem_P->hanZiBitMap.data, hanzibmp.data, oneHanZiUseByte_BMP );
return replaceIndex ;
}
*/
/*
// draw a HanZi to a Window.
static bool PSP_ChineseUtil:: drawHanZi ( ushortBITMAP &windowBitMap,
unsigned short x, unsigned y,
unsigned short hanZi )
{
}
*/
// use cache !
HanZi16FontBitMap * PSP_ChineseUtil::getHanZiBitMap ( const HanZi & hanzi )
{
HanZi16FontBitMap *bmp ;
HanZi hanziNotUnicode;;
if ( hanzi.isUnicode )
{
hanziNotUnicode.ushort = UnicodeToGBK ( hanzi.ushort );
}
else
{
hanziNotUnicode.ushort = hanzi.ushort ;
}
// printf("unicode is %u, ASC code is %u\n" , hanzi.ushort , hanziNotUnicode.ushort);
bmp = HanZiCache :: getHanZiBMP ( hanziNotUnicode );
return bmp ;
}
unsigned short PSP_ChineseUtil:: getTTFSize( void )
{
return pspTrueTypeFont_cgp->getTTFFontSize();
}
void PSP_ChineseUtil:: printBitMapInTextMode ( const HanZi16FontBitMap &hanzibitmap )
{
unsigned xi, yi, xc, yc;
xc = dotFontHanZiFontWidth;
yc = dotFontHanZiFontHeigh;
unsigned index =0;
printf( "\n");
printf( "\n");
for( yi=0; yi< yc ; yi++)
{
for( xi=0; xi< xc ; xi++)
{
if ( hanzibitmap.data[index] )
{
printf("O");
}else
{
printf("_");
}
index ++;
}
printf("\n");
}
}
void PSP_ChineseUtil:: printBitMapInTextMode ( const ucharBitMap &hanzibitmap )
{
unsigned xi, yi, xc, yc;
xc = hanzibitmap.width ;
yc = hanzibitmap.heigh ;
unsigned lineNo = 0 ;
unsigned index =0;
printf( "\n");
printf( "\n");
for( yi=0; yi< yc ; yi++)
{ printf("%2u ", lineNo++ );
for( xi=0; xi< xc ; xi++)
{
if ( hanzibitmap.data_p[index] )
{
printf("W");
}else
{
printf("_");
}
index ++;
}
printf("\n");
}
}
void PSP_ChineseUtil:: printBitMapInTextMode ( unsigned int fontSize, int bearX, int bearY, const ucharBitMap &hanzibitmap )
{
unsigned xi, yi, xc, yc;
xc = hanzibitmap.width ;
yc = hanzibitmap.heigh ;
int baseline=0;
unsigned index =0;
int indent=0;
unsigned lineNo=0;
printf( "\n");
printf( "\n");
printf("fontSize %u, bearX %d , bearY %d \n", fontSize, bearX , bearY );
unsigned emptyLine = 0;
baseline = fontSize*9/10 - 1 ;
printf("baseline: %d \n", baseline );
emptyLine = baseline - bearY ;
for ( yi=0;yi< emptyLine ;yi++)
{
printf("%2u ", lineNo++);
for ( xi=0;xi< xc + bearX ; xi ++)
printf ("_");
printf("\n");
}
for( yi=0; yi< yc ; yi++)
{
printf("%2u ", lineNo++);
for ( indent =0; indent< bearX; indent++)
printf("_");
for( xi=0; xi< xc ; xi++)
{
if ( hanzibitmap.data_p[index] )
{
printf("W");
}else
{
printf("_");
}
index ++;
}
printf("\n");
}
if ( yc + emptyLine < fontSize -1 )
{ unsigned int count;
count = fontSize - yc - emptyLine;
for ( yi=0;yi< count ;yi++)
{
printf("%2u ", lineNo++);
for ( xi=0;xi< xc + bearX ; xi ++)
printf ("_");
printf("\n");
}
}
}
void PSP_ChineseUtil:: printBitMapInTextMode ( const ASCFontBitMap &ascbitmap )
{
unsigned xi, yi, xc, yc;
xc = DotFont16ASCfont_width ;
yc = DotFont16ASCfont_heigh ;
unsigned index =0;
printf( "\n");
printf( "\n");
for( yi=0; yi< yc ; yi++)
{
for( xi=0; xi< xc ; xi++)
{
if ( ascbitmap.data[index] )
{
printf("Z");
}else
{
printf("0 ");
}
index ++;
}
printf("\n");
}
}
#ifdef __PSPSDK__
void PSP_ChineseUtil::printASC_dotMatrix( unsigned short x, unsigned short y,
unsigned short color, char _char)
{
//unsigned short bgcolor = 0;
//PSP_GRAPHICS::graphicPrintChar8_16( x, y, color, bgcolor, _char, true, false, 1 );
}
#endif
bool PSP_ChineseUtil::isThisAHanZi( const unsigned short HZbyte1 )
{
//GB2312的两个字节的最高位都是1。但符合这个条件的码位只有128*128=16384个。
//所以GBK和GB18030的低字节最高位都可能不是1。不过这不影响DBCS字符流的解析:
//在读取DBCS字符流时,只要遇到高位为1的字节,
//就可以将下两个字节作为一个双字节编码,而不用管低字节的高位是什么。
if ( HZbyte1 > 128 )
{
return true;
}else
{
return false;
}
}
#ifdef __PSPSDK__
// return the bitmap size because caller should know the width and heigh
void PSP_ChineseUtil::drawTTFHanzi ( DrawAttribute &drawAtt, unsigned short color,
HanZi hanzi , BitMapSize * bmpsize_p )
{
ucharBitMap *bitmap ;
bitmap = PSP_ChineseUtil:: getHanZiTTFBitMap( hanzi );
PSP_GRAPHICS::drawBitMap ( drawAtt, color , *bitmap );
if( bmpsize_p )
{
bmpsize_p->width = bitmap->width;
bmpsize_p->heigh = bitmap->heigh;
}
}
void PSP_ChineseUtil::drawHanZi16 ( DrawAttribute &drawAtt, unsigned short color,
char * hanZi2Byte )
{
if( hanZi2Byte == NULL )
return;
HanZi hanzi;
hanzi.ch[0] = hanZi2Byte[0];
hanzi.ch[1] = hanZi2Byte[1];
PSP_ChineseUtil:: drawHanZi16 ( drawAtt, color, hanzi );
}
void PSP_ChineseUtil::drawHanZi16Turn ( DrawAttribute &drawAtt, unsigned short color,
const HanZi & hanzi )
{
HanZi16FontBitMap *tempHZbitmap;
tempHZbitmap = PSP_ChineseUtil::getHanZiBitMap ( hanzi );
ucharBitMap ucharbmp;
ucharbmp.data_p = tempHZbitmap->data;
ucharbmp.width = dotFontHanZiFontWidth ;
ucharbmp.heigh = dotFontHanZiFontHeigh ;
PSP_GRAPHICS ::drawBitMapTurn ( drawAtt, color , ucharbmp );
return;
}
#endif //__PSPSDK__
void PSP_ChineseUtil:: drawHanZi16 ( DrawAttribute &drawAtt, unsigned short color,
const HanZi &hanzi )
{
HanZi16FontBitMap *tempHZbitmap;
tempHZbitmap = PSP_ChineseUtil::getHanZiBitMap ( hanzi );
ucharBitMap ucharbmp;
ucharbmp.data_p = tempHZbitmap->data;
ucharbmp.width = dotFontHanZiFontWidth ;
ucharbmp.heigh = dotFontHanZiFontHeigh ;
#ifdef __PSPSDK__
PSP_GRAPHICS::drawBitMap ( drawAtt, color , ucharbmp );
#else
//printBitMapInTextMode ( ucharbmp );
printf( "%c", hanzi.ushort);
#endif
return;
}
//#include <unicodeJIS.h>
//#include <unicodeCJK.h>
//#include <unicodeGBKTable.h>
void PSP_ChineseUtil ::jis2cjk( const unsigned char *jis,unsigned char *cjk)
{
//int iunic;
//unsigned char tmp[2];
int i = 0,len;
HanZi hanzi, jisHanzi;
len= strlen( (const char *)jis );
do
{
if(jis[i]<0x81)
{
cjk[i]=jis[i];
i++;
}
else
{
unsigned short unicodeOfJIS;
jisHanzi.ch[0] = jis[i];
jisHanzi.ch[1] = jis[i+1];
// jis to unicode
unicodeOfJIS = fullJISToUnicode( jisHanzi.ushort);
/*char str[100];
str [0]=0;
sprintf ( str, "jis %u ", jisHanzi.ushort );
PSP_GRAPHICS::graphicPrintAscString ( 0, 0, 0xffff, str );
str [0]=0;
sprintf ( str, "jis unicode %u ", unicodeOfJIS );
PSP_GRAPHICS::graphicPrintAscString ( 0, 20, 0xffff, str );
//
*/
hanzi.ushort = PSP_ChineseUtil ::UnicodeToGBK( unicodeOfJIS );
/* str [0]=0;
sprintf ( str, "hanzi gbk %u ", hanzi.ushort );
PSP_GRAPHICS::graphicPrintAscString ( 0, 40, 0xffff, str );
PSP_GRAPHICS::flipScreenBuffer();
getch();
*/
cjk[i] = hanzi.ch[0];
cjk[i+1] = hanzi.ch[1];
i += 2;
/*if(cjk[i-1]==0x3f && cjk[i]==0)
{
cjk[i-1]=0xa1;
cjk[i]=0xf6;
}*/
}
if ( i >= len ) break;
}while (true);
}
#ifdef __PSPSDK__
void PSP_ChineseUtil::selfTestPSPGraphicMode( void )
{
//printAscHanZiString(0,0, 0xffff, "ABC卧槽!DEK");
//printAscHanZiString(0,0, 0xffff, "ABC");
// ABCDE 中文阅读! 测试1测试2测试3测试4编程楼梯走廊");
}
#endif //
/*
void PSP_ChineseUtil::printHanZiTextMode( unsigned short cn )
{
const unsigned char *cfont; //pointer to font
unsigned long cx,cy;
unsigned long b;
char mx,my;
HanZi hz;
hz.ushort = cn;
unsigned long index = HanZiToHZKLibIndex ( hz );
//if (printChar > 255) return;
Dot_Font_Data cnDotFontData;
//cfont = font + printChar*8;
PSP_CNFONTS16_16::getFontData( index , &cnDotFontData);
//cfont = good_asc_8_16_font + printChar*16;
cfont = cnDotFontData.fontData;
for (cy=0; cy<cnDotFontData.heigh; cy++)
{ const int mag = 1;
for (my=0; my<mag; my++)
{
b=0x80;
for (cx=0; cx<cnDotFontData.width; cx++)
{
//this byte is used up, drawed half a char,
//now use next byte.
if( cx == CnCharDotsPerByte )
{
b = 0x80;
cfont ++;
}
for (mx=0; mx<mag; mx++)
{
if ((*cfont&b)!=0)
{
printf("O");
} else
{
printf(" ");
}
}
b=b>>1;
}
printf("\n");
}
cfont++;
}
printf("\n"); printf("\n");
}
*/
bool PSP_ChineseUtil:: isEmpty( HanZi16FontBitMap *bmpp)
{
int i;
int size = bmpp->size;
for ( i=0; i< size ; i++)
{
if ( bmpp->data[i] !=0 )
{
return false;
}
}
return true;
}
void PSP_ChineseUtil::selfTestTextModeDrawAllHanzi ( void )
{
HanZi16FontBitMap hanzibitmap;
//unsigned short i;
HanZi hanzi;
hanzi.ch[0]= 0;
hanzi.ch[1]= 128;
unsigned int emptyCount = 0;
for ( hanzi.ushort = 63000 ; hanzi.ushort<65535;hanzi.ushort++)
{
PSP_CNFONTS16_16::drawHanZi16ToBMP( hanzi.ushort, hanzibitmap );
printf("hanzi is %u \n", hanzi.ushort);
printBitMapInTextMode ( hanzibitmap );
if ( isEmpty ( &hanzibitmap ) )
{
emptyCount ++ ;
printf ( "so far emptyCount is %u \n", emptyCount );
}
}
}
void PSP_ChineseUtil::selfTestTextModeDrawAllIndex ( void )
{
HanZi16FontBitMap hanzibitmap;
unsigned int i = 6500;
bool r;
do
{
printf ("index: %u", i);
r = PSP_CNFONTS16_16::getBitMapHZKLibIndex ( i , hanzibitmap );
if( !r ) break;
i++ ;
printBitMapInTextMode ( hanzibitmap );
}
while( true );
}
unsigned short PSP_ChineseUtil::fullGBKToUnicode ( unsigned short gbc )
{
unsigned short unicode ;//, index ;
// index = 0;//gbc - GBK_StartFrom;
//if ( index >= GBKunicodeTableSize )
//return 0;
//unicode = GBKunicodeTable[ index ] ;
unicode = GBKunicodeTable[ gbc ] ;
return unicode;
}
/*
unsigned short PSP_ChineseUtil::UnicodeToGBK ( unsigned short unicode )
{
unsigned short gbk , unicodeIndexInUnicodeTable;
unsigned i;
bool found =false;
for ( i =0 ;i< GBKunicodeTableSize ; i++)
{
if ( GBKunicodeTable[i] == unicode )
{
unicodeIndexInUnicodeTable = i;
found = true;
break;
}
//binarySearch ( GBKunicodeTable, GBKunicodeTableSize , unicode );
}
if ( found )
{
gbk = unicodeIndexInUnicodeTable + GBK_StartFrom;
}
else
{
gbk = GBK_StartFrom;
}
return gbk;
}
*/
unsigned short PSP_ChineseUtil::UnicodeToGBK ( unsigned short unicode )
{
return unicodeToGBKTable[ unicode ];
}
// the instance is in the cache.
// get the bitmap from TTF bitmap cache.
ucharBitMap * PSP_ChineseUtil::getHanZiTTFBitMap ( HanZi &hanzi )
{
ucharBitMap * bitmap;
//hanZiTTFCache_cgp
/* if( hanzi.ushort == 36974 )
{
PSP_Window::showMessage(" PSP_ChineseUtil::getHanZiTTFBitMap () unicode:是 ", hanzi.ushort );
if ( hanzi.isUnicode )
{
PSP_Window::showMessage(" PSP_ChineseUtil::getHanZiTTFBitMap () isUnicode正确" );
}else
PSP_Window::showMessage(" PSP_ChineseUtil::getHanZiTTFBitMap () isUnicode不正确 ");
}
*/
bitmap = TTF_HanZiCache_cgp-> getHanZiTTFBitMap ( hanzi );
return bitmap;
//return TTF_Utility::getHanZiTTFBitMap( hanzi );
}
/*
void PSP_ChineseUtil:: setTTFSize ( unsigned short size )
{
pspTrueTypeFont_cgp -> setTTFFontSize ( size );
}
*/
#ifdef __PSPSDK__
void PSP_ChineseUtil:: selfTestTTFGraphicMode( void )
{
//PSP_TrueTypeFont *pspTrueTypeFont_cgp = &(TTF_Utility::ttfFont ) ;
//pspTTF->init();
bool r;
r = pspTrueTypeFont_cgp ->loadFontFile("ms0:/simsun.ttc");
pspTrueTypeFont_cgp ->setTTFFontSize ( 50 );
if( !r )
{
PSP_Window::showMessage( "TrueTypeFont字库文件读取失败 请检查");
PSP_GRAPHICS::flipScreenBuffer( );
getch();
}
//pspTrueTypeFont_cgp ->setTTFFontSize ( 32 );
HanZi hanzi("煋") , hanzi2 ("事"), hanzi3("新"), hanzi4("替");
//pspTrueTypeFont_cgp ->setTTFFontSize ( 2* (i%10) + 25 );
//
DrawAttribute drawAtt;
for ( int i=0;i < 9000 ;i++)
{
PSP_GRAPHICS::fillVRam( i%100 *500 );
drawAtt.x = 0; drawAtt.y = i%5 * 40;
drawTTFHanzi ( drawAtt, 0xffff, hanzi ) ;
drawAtt.x = 100; // drawAtt.y = 0;
drawTTFHanzi ( drawAtt, 0xffff, hanzi2 ) ;
drawAtt.x = 200; //drawAtt.y = 0;
drawTTFHanzi ( drawAtt, 0xffff, hanzi3 ) ;
drawAtt.x = 300; //drawAtt.y = 0;
drawTTFHanzi ( drawAtt, 0xffff, hanzi4 ) ;
PSP_GRAPHICS::flipScreenBuffer( );
wait( 3);
}
getch();
}
#endif
void PSP_ChineseUtil::selfTestTextMode( void )
{
unsigned long hzkIndex ;
// printCN ( 0, 0, 0xffff, ch.i);
hzkIndex = 320;
printf("\n\n\n");
/*for ( i =0;i<10000;i++)
printCNTextMode(i);
*/
HanZi hanzi1, hanzi2, hanzi3, hanzi4, hanzi5;
char h1[]={"一"};
hanzi1.ch[0]= h1[0];
hanzi1.ch[1]= h1[1];
char h2[]={"二"};
hanzi2.ch[0]= h2[0];
hanzi2.ch[1]= h2[1];
char h3[]={"三"};
hanzi3.ch[0]= h3[0];
hanzi3.ch[1]= h3[1];
char h4[]={"四"};
hanzi4.ch[0]= h4[0];
hanzi4.ch[1]= h4[1];
char h5[]={"@"};
hanzi5.ch[0]= h5[0];
hanzi5.ch[1]= h5[1];
// printBitMapInTextMode (
HanZi16FontBitMap *hanzibitmap;
printf( "hanzi : %u \n", hanzi1.ushort );
hanzibitmap = getHanZiBitMap ( hanzi1 );
printBitMapInTextMode( *hanzibitmap );
hanzibitmap = getHanZiBitMap ( hanzi2 );
printBitMapInTextMode( *hanzibitmap );
hanzibitmap = getHanZiBitMap ( hanzi3 );
printBitMapInTextMode( *hanzibitmap );
hanzibitmap = getHanZiBitMap ( hanzi4 );
printBitMapInTextMode( *hanzibitmap );
hanzibitmap = getHanZiBitMap ( hanzi1 );
printBitMapInTextMode( *hanzibitmap );
hanzibitmap = getHanZiBitMap ( hanzi2 );
printBitMapInTextMode( *hanzibitmap );
hanzibitmap = getHanZiBitMap ( hanzi3 );
printBitMapInTextMode( *hanzibitmap );
hanzibitmap = getHanZiBitMap ( hanzi4 );
printBitMapInTextMode( *hanzibitmap );
hanzibitmap = getHanZiBitMap ( hanzi5 );
printBitMapInTextMode( *hanzibitmap );
HanZiCache::selfTest( );
}
#ifdef __PSPSDK__
void PSP_ChineseUtil ::selfTestHanZi ( void )
{
DrawAttribute drawAtt;
drawAtt.x = 0;
drawAtt.y = 0;
drawAtt.enlarge = 1;
PSP_GRAPHICS::setScreenFrameMode( screenModeWriteAndShow_cg );
PSP_GRAPHICS::fillVRam ( 0 );
drawHanZi16 ( drawAtt ,0xff, "惑" );
drawAtt.x = 17;
drawAtt.y = 0;
drawHanZi16 ( drawAtt, 0xff, "煋" );
drawAtt.x=35;
drawAtt.y=0;
drawAtt.enlarge =2;
drawHanZi16 ( drawAtt , 0xff , "湾" );
drawAtt.x =100;
drawAtt.y = 0;
drawAtt.enlarge =4;
drawHanZi16 ( drawAtt , 0xff , "蔼" );
getch();
drawAtt.x =470;
drawHanZi16 ( drawAtt ,0xff , "惑" );
drawAtt.x=17;
drawAtt.y=260;
drawHanZi16 ( drawAtt , 0xff , "煋" );
getch();
PSP_GRAPHICS::fillVRam ( 0 );
drawAtt.x =460;
drawAtt.y = 0;
drawAtt.enlarge =2;
drawHanZi16 ( drawAtt , 0xff, "湾");
drawAtt.x =0;
drawAtt.y = 255;
drawAtt.enlarge =4;
drawHanZi16 ( drawAtt, 0xff ,"蔼" );
getch();
drawAtt.enlarge =1;
PSP_GRAPHICS::fillVRam ( 0 );
HanZi hanzi;
char *p= {"蔼"};
hanzi.ch[0] = p[0];
hanzi.ch[1] = p[1];
drawHanZi16Turn ( drawAtt, 0xff, hanzi );
drawAtt.y = 20;
drawAtt.enlarge =2;
drawHanZi16Turn ( drawAtt, 0xff, hanzi );
getch();
PSP_GRAPHICS::fillVRam ( 0 );
drawAtt.x =0;
drawAtt.y = 10;
drawHanZi16Turn ( drawAtt, 0xff, hanzi);
drawAtt.x =30;
drawAtt.y = 20;
drawAtt.enlarge =4;
drawHanZi16Turn ( drawAtt, 0xff, hanzi );
getch();
}
#endif // __PSPSDK__
void PSP_ChineseUtil:: selfTestTTFTextMode( void )
{
//from 18 to ......
pspTrueTypeFont_cgp ->loadFontFile("c:\\winnt\\fonts\\simsun.ttc");
pspTrueTypeFont_cgp ->setTTFFontSize ( 17 );
// FT_Set_Pixel_Sizes ( face, 0, 10 );
HanZi hanzi("煋") , hanzi2 (","), hanzi3("\""), hanzi4("替");
HanZi hanziYi("一") , hanziMu ("目") , hanziX("~"),
hanziASC1("1"), hanziASC2("_") , hanziASC3(".") , hanziASC4("~") ;
int i;
unsigned char *p;
unsigned size = 1024;
HanZi hanziTest;
hanziTest.isUnicode = true;
ucharBitMap *bitmap ;
// pspTrueTypeFont_cgp ->setTTFFontSize ( 23 );
//hanziTest.ushort = 32871 ;
//bitmap = getHanZiTTFBitMap( hanziTest.ushort );
//problem number 9494 => 23355
int fontsize = 22;
// for ( fontsize= 22; fontsize< 50; fontsize ++)
{
pspTrueTypeFont_cgp ->setTTFFontSize ( fontsize );
//23355 这个字( 或者前面几个) 很有问题! 在GCC和VC都死机.
for ( int i = 0 ;i< 200;i++)//65535;i++)
{
hanziTest.ushort = i;
printf ("testing hanziTest.ushort = %u \n", hanziTest.ushort );
bitmap = getHanZiTTFBitMap( hanziTest );
printBitMapInTextMode ( *bitmap );
}
pspTrueTypeFont_cgp ->setTTFFontSize ( 11 );
for ( int i = 0 ;i< 200;i++)//65535;i++)
{
hanziTest.ushort = i;
printf ("testing hanziTest.ushort = %u \n", hanziTest.ushort );
bitmap = getHanZiTTFBitMap( hanziTest );
printBitMapInTextMode ( *bitmap );
}
}
}
void PSP_ChineseUtil:: convertUnicodeBigEnd ( unsigned short * unicodeTextBuffer, unsigned long UshortSize )
{
unsigned long i ;
unsigned char ch1,ch2;
unsigned short tempUshort;
//unicode has 0 , must not use 0 to end.
//bufferSize = strlen ( unicodeTextBuffer );
for( i = 0;i< UshortSize ;i++ )
{
tempUshort = unicodeTextBuffer [ i ] ;
ch1 = tempUshort / 0x100;
ch2 = tempUshort % 0x100;
unicodeTextBuffer [ i ] = ch2 * 0x100 + ch1;
// printf( "%x %x\n", ch1, ch2 );
// printf( "%x %x\n", ch1, ch2 );
}
}
void PSP_ChineseUtil::drawAscChar8_16( const DrawAttribute &drawAtt, unsigned short color, char ascChar )
{
ucharBitMap bitmap ;
ASCFontBitMap *ascbitmap_p;
ascbitmap_p = PSP_ASCFONTS8_16::getASCBmp( ascChar );
bitmap.width = PSP_ASCFONTS8_16::width;
bitmap.heigh = PSP_ASCFONTS8_16::heigh ;
bitmap.data_p = ascbitmap_p->data;
#ifdef __PSPSDK__
PSP_GRAPHICS::drawBitMap ( drawAtt, color , bitmap );
#else
//PSP_ChineseUtil:: printBitMapInTextMode ( bitmap );
printf("%c", ascChar);
#endif
}
| [
"ntchris0623@05aa5984-5704-11de-9010-b74abb91d602"
]
| [
[
[
1,
1372
]
]
]
|
14bc0cba602f287111ec3a6c73c25977d3132b02 | 41543fd481e363d8c4794edc97e767c8defb2273 | /http/inc/http/parser_base.hpp | ac197e4029131f1f10565e0ffb5985b6ad9654cc | [
"BSL-1.0"
]
| permissive | ExpLife0011/libHTTP | 550904eddf17f5fa89a2ff9fd563ff5746cbc29b | c53b85c7192f5b2cf506a71f36ec44e9b99ada1a | refs/heads/master | 2020-03-08T16:35:52.022125 | 2010-05-14T18:13:36 | 2010-05-14T18:13:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,046 | hpp |
#ifndef HTTP_PARSER_BASE
#define HTTP_PARSER_BASE
#include <vector>
#include <stdexcept>
#include <iomanip>
#include <boost/shared_ptr.hpp>
#include <boost/array.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/logic/tribool.hpp>
#include <boost/statechart/event.hpp>
#include <boost/statechart/state_machine.hpp>
#include <boost/statechart/state.hpp>
#include <boost/statechart/simple_state.hpp>
#include <boost/statechart/transition.hpp>
#include <boost/statechart/custom_reaction.hpp>
#include <http/debug_logger.hpp>
namespace http
{
class error : public std::exception
{
public:
error(const std::string& message) :
str_(message)
{}
virtual ~error() throw () {}
virtual const char *what() const throw ()
{
return (str_.c_str());
}
private:
std::string str_;
};
struct ev_parse : boost::statechart::event<ev_parse>
{
public:
ev_parse(const char* begin, const char* end, unsigned& result) :
begin_(begin),
end_(end),
result_(result)
{}
enum
{
close_connection = 0x1,
completed_transaction = 0x2
};
const char* begin() const { return begin_; }
const char*& begin() { return begin_; }
const char* end() const { return end_; }
const char*& end() { return end_; }
unsigned& result() const { return result_; }
void set_close_connection() const { result_ |= ev_parse::close_connection; }
void set_completed_transaction() const { result_ |= ev_parse::completed_transaction; }
private:
const char* begin_;
const char* end_;
mutable unsigned& result_;
};
class parser_base
{
public:
parser_base() {}
bool parse(const char* begin, const char* end);
std::vector<char>& buffer() { return buffer_; }
const unsigned get_last_error() const { return error_; }
protected:
virtual ~parser_base() {}
unsigned error_;
std::vector<char> buffer_;
};
} // namespace http
#endif // HTTP_PARSER_BASE
| [
"rhenders@oliver.(none)"
]
| [
[
[
1,
95
]
]
]
|
888ba5032388848e7388fb732907078a2f74d632 | 6dac9369d44799e368d866638433fbd17873dcf7 | /src/branches/01032005/graphics/opengl/OGLDynamicVB.h | f3e41577e2905839c2918382e781f2c6ee9f4cfe | []
| 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 | 4,381 | h | #ifndef _DYNAMICVB_H_
#define _DYNAMICVB_H_
#include <graphics/IVertexBuffer.h>
#include <OGLShader.h>
#include <mesh/Colour.h>
#include <mesh/Mesh.h>
class ITexture;
/** @ingroup OGL_VertexBuffer_Group
* @brief Derived IVertexBuffer class for Dynamically assigned mesh data
*
* NOTE: When dealing with the m_position, m_normal, m_texture pointers:
*
* The data pointed at here is not necessarily all used
* by this vertex buffer, the index pointer defines WHAT
* position data to use in this mesh
* The dynamic vertex buffer does not own the position data,
* so do not attempt to derive this class into a custom
* version and in that version, delete this data.
* Therefore the m_position, m_normal and m_texture pointers
* are not to be directly manipulated, cause this will cause
* corruption. If you want to do this, you should derive
* from the Static version of this class, where the data
* is COPIED into the class and therefore owns the memory
* and can be manipulated.
*
* However, the contents of the pointers can be manipulated
* in whatever way the application likes, this does not affect
* the pointer to the data.
*/
class OGLDynamicVB:public IVertexBuffer{
protected:
/** @var char *m_name
* @brief A indentifiable name for the chunk of mesh data
*/
std::string m_name;
/** @var int m_num_vertex
* @brief The number of vertices in the mesh data
*/
unsigned int m_num_vertex;
/** @var int m_num_index
* @brief The number of indices in the mesh data
*/
unsigned int m_num_index;
/** @var int m_numcomp_position
* @brief The number of components (floating point values) in each position. Typically this is 3
*/
unsigned int m_numcomp_position;
/** @var int m_numcomp_texcoord
* @brief The number of components (floating point values) in each texture coordinate. Typically this is 2
*/
unsigned int m_numcomp_texcoord;
/** @var int m_bytes_position
* @brief The number of bytes per position. This is just a pre-calculated value to make life easier
*/
unsigned int m_bytes_position;
/** @var int m_bytes_texcoord
* @brief The number of bytes per texcoord. This is just a pre-calcaulated value to make life easier
*/
unsigned int m_bytes_texcoord;
/** @var int *m_index
* @brief The pointer to the meshes index data
*/
unsigned int *m_index;
/** @var float *m_position
* @brief The pointer to the meshes position data
*/
float *m_position;
/** @var float *m_normal
* @brief The pointer to the meshes normal data
*/
float *m_normal;
/** @var Material m_material
* @brief The material assigned to the mesh
*/
Material m_material;
/** @var float m_smoothingangle
* @brief The maximum smoothing angle between faces before the vertex data is duplicated (flat shaded)
*
* @todo This is a crap explanation
*/
float m_smoothingangle;
/** @var IShader *m_shader;
* @brief The shader used to colour/texture the mesh stored in this VB
*/
OGLShader m_shader;
public:
OGLDynamicVB ();
virtual ~OGLDynamicVB ();
virtual bool Initialise (unsigned int nv, unsigned int ni, unsigned int nc_p, unsigned int nc_t);
virtual void ReleaseAll (void);
virtual void SetComponents (unsigned int p, unsigned int t);
virtual void SetName (std::string name);
virtual void SetPosition (float *p);
virtual void SetNormal (float *n);
virtual void SetTextureLayer (unsigned int layer, float *tc, ITexture *t);
virtual void SetIndex (unsigned int *i);
virtual void SetColour (Colour4f *c);
virtual void SetColour (float r, float g, float b, float a);
virtual void SetMaterial (Material *m);
virtual void SetSmoothingAngle (float angle);
virtual std::string GetName (void);
virtual float * GetPosition (void);
virtual float * GetNormal (void);
virtual float * GetTexcoord (unsigned int layer=0);
virtual unsigned int * GetIndex (void);
virtual ITexture * GetTexture (unsigned int layer=0);
virtual Colour4f * GetColour (void);
virtual Material * GetMaterial (void);
virtual float GetSmoothingAngle (void);
virtual unsigned int GetNumIndex (void);
virtual void Render (void);
};
#endif // #ifndef _DYNAMICVB_H_
| [
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
]
| [
[
[
1,
136
]
]
]
|
da6ac086f0ccf1c710d640c08e735920773987f2 | 3c4f5bd6d7ac3878c181fb05ab41c1d755ddf343 | /BtnST.h | ed52bbda2b8453c30aba3179a5d4084a9d709768 | []
| no_license | imcooder/public | 1078df18c1459e67afd1200346dd971ea3b71933 | be947923c6e2fbd9c993a41115ace3e32dad74bf | refs/heads/master | 2021-05-28T08:43:00.027020 | 2010-07-24T07:39:51 | 2010-07-24T07:39:51 | 32,301,120 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,378 | h | #if !defined( _BTNST_H )
#define _BTNST_H
//#define BTNST_USE_BCMENU
//#include "BCMenu.h"
//#define BTNST_USE_SOUND
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#ifndef BTNST_OK
#define BTNST_OK 0
#endif
#ifndef BTNST_INVALIDRESOURCE
#define BTNST_INVALIDRESOURCE 1
#endif
#ifndef BTNST_FAILEDMASK
#define BTNST_FAILEDMASK 2
#endif
#ifndef BTNST_INVALIDINDEX
#define BTNST_INVALIDINDEX 3
#endif
#ifndef BTNST_INVALIDALIGN
#define BTNST_INVALIDALIGN 4
#endif
#ifndef BTNST_BADPARAM
#define BTNST_BADPARAM 5
#endif
#ifndef BTNST_INVALIDPRESSEDSTYLE
#define BTNST_INVALIDPRESSEDSTYLE 6
#endif
#ifndef BTNST_AUTO_GRAY
#define BTNST_AUTO_GRAY (HICON)(0xffffffff - 1L)
#endif
#ifndef BTNST_AUTO_DARKER
#define BTNST_AUTO_DARKER (HICON)(0xffffffff - 2L)
#endif
class CButtonST : public CButton
{
public:
CButtonST();
~CButtonST();
enum { ST_ALIGN_HORIZ = 0, // Icon/bitmap on the left, text on the right
ST_ALIGN_VERT, // Icon/bitmap on the top, text on the bottom
ST_ALIGN_HORIZ_RIGHT, // Icon/bitmap on the right, text on the left
ST_ALIGN_OVERLAP // Icon/bitmap on the same space as text
};
enum { BTNST_COLOR_BK_IN = 0, // Background color when mouse is INside
BTNST_COLOR_FG_IN, // Text color when mouse is INside
BTNST_COLOR_BK_OUT, // Background color when mouse is OUTside
BTNST_COLOR_FG_OUT, // Text color when mouse is OUTside
BTNST_COLOR_BK_FOCUS, // Background color when the button is focused
BTNST_COLOR_FG_FOCUS, // Text color when the button is focused
BTNST_MAX_COLORS
};
enum { BTNST_PRESSED_LEFTRIGHT = 0, // Pressed style from left to right (as usual)
BTNST_PRESSED_TOPBOTTOM // Pressed style from top to bottom
};
//{{AFX_VIRTUAL(CButtonST)
public:
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
virtual BOOL PreTranslateMessage(MSG* pMsg);
protected:
virtual void PreSubclassWindow();
//}}AFX_VIRTUAL
public:
DWORD SetDefaultColors(BOOL bRepaint = TRUE);
DWORD SetColor(BYTE byColorIndex, COLORREF crColor, BOOL bRepaint = TRUE);
DWORD GetColor(BYTE byColorIndex, COLORREF* crpColor);
DWORD OffsetColor(BYTE byColorIndex, short shOffset, BOOL bRepaint = TRUE);
DWORD SetCheck(int nCheck, BOOL bRepaint = TRUE);
int GetCheck();
DWORD SetURL(LPCTSTR lpszURL = NULL);
void DrawTransparent(BOOL bRepaint = FALSE);
DWORD SetBk(CDC* pDC);
BOOL GetDefault();
DWORD SetAlwaysTrack(BOOL bAlwaysTrack = TRUE);
void SetTooltipText(int nText, BOOL bActivate = TRUE);
void SetTooltipText(LPCTSTR lpszText, BOOL bActivate = TRUE);
void ActivateTooltip(BOOL bEnable = TRUE);
DWORD EnableBalloonTooltip();
DWORD SetBtnCursor(int nCursorId = NULL, BOOL bRepaint = TRUE);
DWORD SetFlat(BOOL bFlat = TRUE, BOOL bRepaint = TRUE);
DWORD SetAlign(BYTE byAlign, BOOL bRepaint = TRUE);
DWORD SetPressedStyle(BYTE byStyle, BOOL bRepaint = TRUE);
DWORD DrawBorder(BOOL bDrawBorder = TRUE, BOOL bRepaint = TRUE);
DWORD DrawFlatFocus(BOOL bDrawFlatFocus, BOOL bRepaint = TRUE);
DWORD SetIcon(int nIconIn, int nCxDesiredIn, int nCyDesiredIn, int nIconOut = NULL, int nCxDesiredOut = 0, int nCyDesiredOut = 0);
DWORD SetIcon(int nIconIn, int nIconOut = NULL);
DWORD SetIcon(HICON hIconIn, HICON hIconOut = NULL);
DWORD SetBitmaps(int nBitmapIn, COLORREF crTransColorIn, int nBitmapOut = NULL, COLORREF crTransColorOut = 0);
DWORD SetBitmaps(HBITMAP hBitmapIn, COLORREF crTransColorIn, HBITMAP hBitmapOut = NULL, COLORREF crTransColorOut = 0);
void SizeToContent();
#ifdef BTNST_USE_BCMENU
DWORD SetMenu(UINT nMenu, HWND hParentWnd, BOOL bWinXPStyle = TRUE, UINT nToolbarID = NULL, CSize sizeToolbarIcon = CSize(16, 16), COLORREF crToolbarBk = RGB(255, 0, 255), BOOL bRepaint = TRUE);
#else
DWORD SetMenu(UINT nMenu, HWND hParentWnd, BOOL bRepaint = TRUE);
#endif
DWORD SetMenuCallback(HWND hWnd, UINT nMessage, LPARAM lParam = 0);
#ifdef BTNST_USE_SOUND
DWORD SetSound(LPCTSTR lpszSound, HMODULE hMod = NULL, BOOL bPlayOnClick = FALSE, BOOL bPlayAsync = TRUE);
#endif
static short GetVersionI() { return 39; }
static LPCTSTR GetVersionC() { return (LPCTSTR)_T( "3.9" ); }
BOOL m_bShowDisabledBitmap;
POINT m_ptImageOrg;
POINT m_ptPressedOffset;
protected:
//{{AFX_MSG(CButtonST)
afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
afx_msg void OnKillFocus(CWnd* pNewWnd);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnSysColorChange();
afx_msg BOOL OnClicked();
afx_msg void OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized);
afx_msg void OnEnable(BOOL bEnable);
afx_msg void OnCancelMode();
afx_msg UINT OnGetDlgCode();
//}}AFX_MSG
#ifdef BTNST_USE_BCMENU
afx_msg LRESULT OnMenuChar(UINT nChar, UINT nFlags, CMenu* pMenu);
afx_msg void OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct);
#endif
afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor);
HICON CreateGrayscaleIcon(HICON hIcon);
HICON CreateDarkerIcon(HICON hIcon);
HBITMAP CreateGrayscaleBitmap(HBITMAP hBitmap, DWORD dwWidth, DWORD dwHeight, COLORREF crTrans);
HBITMAP CreateDarkerBitmap(HBITMAP hBitmap, DWORD dwWidth, DWORD dwHeight, COLORREF crTrans);
COLORREF DarkenColor(COLORREF crColor, double dFactor);
virtual DWORD OnDrawBackground(CDC* pDC, CRect* pRect);
virtual DWORD OnDrawBorder(CDC* pDC, CRect* pRect);
BOOL m_bIsFlat; // Is a flat button?
BOOL m_bMouseOnButton; // Is mouse over the button?
BOOL m_bDrawTransparent; // Draw transparent?
BOOL m_bIsPressed; // Is button pressed?
BOOL m_bIsFocused; // Is button focused?
BOOL m_bIsDisabled; // Is button disabled?
BOOL m_bIsDefault; // Is default button?
BOOL m_bIsCheckBox; // Is the button a checkbox?
BYTE m_byAlign; // Align mode
BOOL m_bDrawBorder; // Draw border?
BOOL m_bDrawFlatFocus; // Draw focus rectangle for flat button?
COLORREF m_crColors[BTNST_MAX_COLORS]; // Colors to be used
HWND m_hParentWndMenu; // Handle to window for menu selection
BOOL m_bMenuDisplayed; // Is menu displayed ?
#ifdef BTNST_USE_BCMENU
BCMenu m_menuPopup; // BCMenu class instance
#else
HMENU m_hMenu; // Handle to associated menu
#endif
private:
LRESULT OnSetCheck(WPARAM wParam, LPARAM lParam);
LRESULT OnGetCheck(WPARAM wParam, LPARAM lParam);
LRESULT OnSetStyle(WPARAM wParam, LPARAM lParam);
LRESULT OnMouseLeave(WPARAM wParam, LPARAM lParam);
void CancelHover();
void FreeResources(BOOL bCheckForNULL = TRUE);
void PrepareImageRect(BOOL bHasTitle, RECT* rpItem, CRect* rpTitle, BOOL bIsPressed, DWORD dwWidth, DWORD dwHeight, CRect* rpImage);
HBITMAP CreateBitmapMask(HBITMAP hSourceBitmap, DWORD dwWidth, DWORD dwHeight, COLORREF crTransColor);
virtual void DrawTheIcon(CDC* pDC, BOOL bHasTitle, RECT* rpItem, CRect* rpCaption, BOOL bIsPressed, BOOL bIsDisabled);
virtual void DrawTheBitmap(CDC* pDC, BOOL bHasTitle, RECT* rpItem, CRect* rpCaption, BOOL bIsPressed, BOOL bIsDisabled);
virtual void DrawTheText(CDC* pDC, LPCTSTR lpszText, RECT* rpItem, CRect* rpCaption, BOOL bIsPressed, BOOL bIsDisabled);
void PaintBk(CDC* pDC);
void InitToolTip();
HCURSOR m_hCursor; // Handle to cursor
CToolTipCtrl m_ToolTip; // Tooltip
CDC m_dcBk;
CBitmap m_bmpBk;
CBitmap* m_pbmpOldBk;
BOOL m_bAlwaysTrack; // Always hilight button?
int m_nCheck; // Current value for checkbox
UINT m_nTypeStyle; // Button style
DWORD m_dwToolTipStyle; // Style of tooltip control
TCHAR m_szURL[_MAX_PATH]; // URL to open when clicked
#pragma pack(1)
typedef struct _STRUCT_ICONS
{
HICON hIcon; // Handle to icon
DWORD dwWidth; // Width of icon
DWORD dwHeight; // Height of icon
} STRUCT_ICONS;
#pragma pack()
#pragma pack(1)
typedef struct _STRUCT_BITMAPS
{
HBITMAP hBitmap; // Handle to bitmap
DWORD dwWidth; // Width of bitmap
DWORD dwHeight; // Height of bitmap
HBITMAP hMask; // Handle to mask bitmap
COLORREF crTransparent; // Transparent color
} STRUCT_BITMAPS;
#pragma pack()
#pragma pack(1)
typedef struct _STRUCT_CALLBACK
{
HWND hWnd; // Handle to window
UINT nMessage; // Message identifier
WPARAM wParam;
LPARAM lParam;
} STRUCT_CALLBACK;
#pragma pack()
STRUCT_ICONS m_csIcons[2];
STRUCT_BITMAPS m_csBitmaps[2];
STRUCT_CALLBACK m_csCallbacks;
#ifdef BTNST_USE_SOUND
#pragma pack(1)
typedef struct _STRUCT_SOUND
{
TCHAR szSound[_MAX_PATH];
LPCTSTR lpszSound;
HMODULE hMod;
DWORD dwFlags;
} STRUCT_SOUND;
#pragma pack()
STRUCT_SOUND m_csSounds[2]; // Index 0 = Over 1 = Clicked
#endif
DECLARE_MESSAGE_MAP()
};
class CWinXPButtonST : public CButtonST
{
public:
CWinXPButtonST();
virtual ~CWinXPButtonST();
DWORD SetRounded( BOOL bRounded, BOOL bRepaint = TRUE );
protected:
virtual DWORD OnDrawBackground( CDC *pDC, CRect *pRect );
virtual DWORD OnDrawBorder( CDC *pDC, CRect *pRect );
private:
BOOL m_bIsRounded; // Borders must be rounded?
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif //!defined( _BTNST_H )
| [
"jtxuee@716a2f10-c84c-11dd-bf7c-81814f527a11"
]
| [
[
[
1,
284
]
]
]
|
5a6de492742339ec7643965f4af5fd1e1d568a0a | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Modules/QueueSerial/QueueSerial.cpp | 66a91a9620b80efbcd58034db6dd33315c550650 | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,786 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
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 the Vodafone Group Services Ltd 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 HOLDER 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 "arch.h"
#include "MsgBufferEnums.h"
#include "Module.h"
#include "Serial.h"
#include "Mutex.h"
#include "QueueSerial.h"
#include <map>
#include "GuiProt/GuiProtEnums.h"
#ifndef NO_LOG_OUTPUT
# define NO_LOG_OUTPUT
#endif
#include "LogMacros.h"
#include "Buffer.h"
#include "MsgBuffer.h"
/// The number of buffers that can be stored in the outbound queue
/// before the overflow policy is invoked.
#define QS_OVERFLOW_LIMIT 200
isab::QueueSerial::QueueSerial(const char* name, class OverflowPolicy* policy,
int microSecondsPoll) :
Module(name), m_connectState(CONNECTING), m_pollInterval(microSecondsPoll),
m_policy(policy)
#ifdef __SYMBIAN32__
,m_guiSideRequestStatus(NULL)
#endif
{
}
void isab::QueueSerial::decodedStartupComplete()
{
DBG("decodedStartupComplete");
if(!m_incoming.empty() && rootPublic()){
connect();
while(! m_incoming.empty()){
Buffer* buf = m_incoming.front();
m_incoming.pop();
write(buf->accessRawData(0), buf->getLength());
delete buf;
}
} else if(rootPublic()){
rootPublic()->connectionNotify(m_connectState);
}
}
bool isab::QueueSerial::write(const uint8* data, int length)
{
bool ret = false;
if(isAlive()){
if(rootPublic() && m_connectState != CONNECTED){
m_connectState = CONNECTED;
rootPublic()->connectionNotify(CONNECTED);
}
m_queue->lock();
if(rootPublic()){
//DBGDUMP("write", data, length);
uint32 src = rootPublic()->receiveData(length, data);
src = src;
DBG("Message sent with id: %0#10"PRIx32, src);
ret = true;
} else {
Buffer* buf = new Buffer(0);
buf->writeNextByteArray(data, length);
m_incoming.push(buf);
}
m_queue->unlock();
}
return ret;
}
void isab::QueueSerial::connect(){
DBG("connect");
m_connectState = CONNECTED;
if(rootPublic()){
rootPublic()->connectionNotify(CONNECTED);
}
}
void isab::QueueSerial::disconnect(){
DBG("disconnect");
m_connectState = DISCONNECTING;
if(isAlive()){
rootPublic()->connectionNotify(DISCONNECTING);
}
}
int isab::QueueSerial::read( uint8* data, int maxlength)
{
if(m_connectState != CONNECTED){
m_connectState = CONNECTED;
rootPublic()->connectionNotify(CONNECTED);
}
int retval = 0;
m_outMutex.lock();
while(!m_outQue.empty() && retval < maxlength){
Buffer* front = m_outQue.front();
int n = front->readNextByteArray(data + retval, maxlength - retval);
retval += n;
if(front->remaining() <= 0){
m_outQue.pop_front();
delete front;
}
}
m_outMutex.unlock();
//DBGDUMP("read data", data, retval);
return retval;
}
bool isab::QueueSerial::read(isab::Buffer* buf)
{
bool ret = false;
if((ret = isAlive())){
if(m_connectState != CONNECTED){
m_connectState = CONNECTED;
rootPublic()->connectionNotify(CONNECTED);
}
m_outMutex.lock();
buf->reserve(buf->getLength() + internalAvailable());
DBG("read: outque size: %d", m_outQue.size());
while(!m_outQue.empty()){
Buffer* front = m_outQue.front();
//DBGDUMP("front", front->accessRawData(0), front->getLength());
buf->writeNextByteArray(front->accessRawData(0), front->getLength());
m_outQue.pop_front();
delete front;
}
//DBGDUMP("read", buf->accessRawData(0), buf->getLength());
m_outMutex.unlock();
}
return ret;
}
#ifdef __SYMBIAN32__
void isab::QueueSerial::armReader(TRequestStatus *aStatus)
{
m_outMutex.lock();
// It is a major error if this object already is armed. FIMXE - check.
if (m_outQue.empty()) {
m_guiSideRequestStatus = aStatus;
RThread thisThread;
m_guiSideThread = thisThread.Id();
thisThread.Close();
*aStatus = KRequestPending;
} else {
User::RequestComplete(aStatus, KErrNone);
}
m_outMutex.unlock();
}
void isab::QueueSerial::cancelArm()
{
m_outMutex.lock();
if (m_guiSideRequestStatus) {
RThread otherThread;
otherThread.Open(m_guiSideThread);
otherThread.RequestComplete(m_guiSideRequestStatus, KErrCancel);
otherThread.Close();
m_guiSideRequestStatus=NULL;
}
m_outMutex.unlock();
}
#endif
int isab::QueueSerial::internalAvailable() const
{
int retval = 0;
Container::const_iterator q;
for(q = m_outQue.begin(); q != m_outQue.end(); ++q){
retval = (*q)->remaining();
}
return retval;
}
int isab::QueueSerial::available() const
{
m_outMutex.lock();
int retval = internalAvailable();
m_outMutex.unlock();
DBG("Available: %d", retval);
return retval;
}
bool isab::QueueSerial::empty() const
{
DBG("empty? %s", m_outQue.empty() ? "true": "false");
return m_outQue.empty();
}
isab::SerialProviderPublic * isab::QueueSerial::newPublicSerial()
{
DBG("newPublicSerial");
SerialProviderPublic* spp = new SerialProviderPublic(m_queue);
return spp;
}
void isab::QueueSerial::decodedSendData(int length, const uint8 *data,
uint32 /*src*/)
{
DBG("enter decodedSendData");
m_outMutex.lock();
//DBGDUMP("decodedSendData", data, length);
Buffer* buf = new Buffer(length);
buf->writeNextByteArray(data, length);
m_outQue.push_back(buf);
DBG("push_back, outque size: %d", m_outQue.size());
if(m_outQue.size() > QS_OVERFLOW_LIMIT){
INFO("Queue overflow, removing excess messages now");
removeOverflow();
}
#ifdef __SYMBIAN32__
if (m_guiSideRequestStatus) {
DBG("complete sprocket, outque size: %d", m_outQue.size());
// Notify the other (non-Nav2) side reader
RThread otherThread;
otherThread.Open(m_guiSideThread);
otherThread.RequestComplete(m_guiSideRequestStatus, KErrNone);
otherThread.Close();
m_guiSideRequestStatus=NULL;
}
#endif
m_outMutex.unlock();
DBG("exit decodedSendData");
}
void isab::QueueSerial::decodedConnectionCtrl(enum ConnectionCtrl ctrl,
const char *method,
uint32 /*src*/)
{
switch(ctrl){
case Module::CONNECT:
WARN("CONNECT %s", method);
break;
case Module::DISCONNECT:
WARN("DISCONNECT %s", method);
break;
case Module::QUERY:
WARN("QUERY %s", method);
rootPublic()->connectionNotify(m_connectState);
break;
default:
ERR("ConnectionCtrl: Unknown ctrl value: %d", ctrl);
}
}
isab::SerialConsumerPublic * isab::QueueSerial::rootPublic()
{
return static_cast<SerialConsumerPublic*>(m_rawRootPublic);
}
isab::MsgBuffer * isab::QueueSerial::dispatch(MsgBuffer *buf)
{
if(buf) buf = m_providerDecoder.dispatch(buf, this);
if(buf) buf = Module::dispatch(buf);
return buf;
}
isab::QueueSerial::~QueueSerial()
{
delete m_policy;
while(!m_outQue.empty()){
Buffer* front = m_outQue.front();
m_outQue.pop_front();
delete front;
}
}
void isab::KeepLatestGuiMessage::clean(QueueSerial::Container& deq)
{
//this method presumes that each buffer in the deque contains
//exactly one complete Gui-message
typedef std::map<uint16, Buffer*> Tree;
Tree keepers;
while(!deq.empty()){
Buffer* front = deq.front();
deq.pop_front();
int pos = front->setReadPos(0);
uint8 protocol = *(front->accessRawData(0));
uint32 length = front->readNextUnaligned32bit() & 0x0ffffff;
length = length;
uint16 message = front->readNextUnaligned16bit();
switch(protocol){
case 0:
case 3:
break;
}
std::map<uint16, Buffer*>::iterator prev = keepers.find(message);
if(prev != keepers.end()){
delete (*prev).second;
(*prev).second = front;
} else {
keepers[message] = front;
}
front->setReadPos(pos);
}
for(Tree::iterator p = keepers.begin(); p != keepers.end(); ++p){
deq.push_back((*p).second);
}
}
void isab::KeepLatestBuffer::clean(QueueSerial::Container& deq)
{
while(deq.size() > 1){
Buffer* tmp = deq.front();
deq.pop_front();
delete tmp;
}
}
void isab::RemoveGpsAndRoute::clean(QueueSerial::Container& deq)
{
QueueSerial::Container tmp;
while(!deq.empty()){
Buffer* front = deq.front();
deq.pop_front();
front->setReadPos(0);
/*uint32 length = */ front->readNextUnaligned32bit();
/*uint8 datatype = */front->readNext8bit();
uint8 message = front->readNext8bit();
front->setReadPos(0);
switch(message){
case isab::GuiProtEnums::UPDATE_POSITION_INFO:
// case isab::GuiProtEnums::UPDATE_ROUTE_INFO:
delete front;
default:
tmp.push_back(front);
}
}
std::swap(tmp,deq);
}
| [
"[email protected]"
]
| [
[
[
1,
346
]
]
]
|
bfe2667e977ea2a626f96c674155f76652a1ec6e | c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac | /src/Engine/Entity/EntityFactory.cpp | c1b259d2eb6374ee56912d516b81d1d7d7faa1e8 | [
"Zlib"
]
| permissive | ptrefall/smn6200fluidmechanics | 841541a26023f72aa53d214fe4787ed7f5db88e1 | 77e5f919982116a6cdee59f58ca929313dfbb3f7 | refs/heads/master | 2020-08-09T17:03:59.726027 | 2011-01-13T22:39:03 | 2011-01-13T22:39:03 | 32,448,422 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,975 | cpp | #include "precomp.h"
#include "EntityFactory.h"
#include "EntityManager.h"
#include <Core/CoreMgr.h>
#include <Resource/ResMgr.h>
#include <Resource/IResource.h>
#include <Resource/XMLResource.h>
#include "TypeSerializer.h"
using namespace Engine;
std::map<CL_String, CL_String>* EntityFactory::creators;
std::map<CL_String, EntityFactory::SpecialCreator>* EntityFactory::special_creators;
void EntityFactory::PreConstruct()
{
EntityFactory::creators = new std::map<CL_String, CL_String>();
EntityFactory::special_creators = new std::map<CL_String, SpecialCreator>();
}
EntityFactory::EntityFactory(CoreMgr *coreMgr)
{
this->coreMgr = coreMgr;
}
EntityFactory::~EntityFactory()
{
if(creators)
{
creators->clear();
delete creators;
creators = NULL;
}
if(special_creators)
{
special_creators->clear();
delete special_creators;
special_creators = NULL;
}
}
void EntityFactory::RegisterSpecial(const CL_String &type, SpecialCreator functor)
{
if(special_creators == 0)
special_creators = new std::map<CL_String, SpecialCreator>();
if(special_creators->find(type) == special_creators->end())
{
std::pair<CL_String, SpecialCreator> value(type, functor);
special_creators->insert(value);
}
}
IEntity* EntityFactory::CreateSpecial(const CL_String &special, const CL_String &type, const CL_String &name)
{
if(special_creators == 0)
throw CL_Exception("Special Creators has not been instanciated!");
std::map<CL_String, SpecialCreator>::iterator creatorIt = special_creators->find(special);
if(creatorIt == special_creators->end())
throw CL_Exception("Unable to create special entity " + special);
SpecialCreator creator = creatorIt->second;
return creator(coreMgr->getEntityMgr()->genUId(), type, name, coreMgr, *coreMgr->getEntityMgr()->getComponentFactory());
}
void EntityFactory::registerEntity(const CL_String &fileName)
{
if(creators == 0)
creators = new std::map<CL_String, CL_String>();
//Check if file has already been loaded, though fileName is registered as
//second value in the map, because accessing the first value is faster, and
//we need that speed in the run-time create() function more than we need that
//speed at register initialization.
std::map<CL_String, CL_String>::iterator it = creators->begin();
for(; it != creators->end(); ++it)
{
if((*it).second == fileName)
{
return;
}
}
CL_String type = loadEntity(fileName);
std::pair<CL_String, CL_String> value(type, fileName);
creators->insert(value);
}
IEntity *EntityFactory::create(const CL_String &type, const CL_String &name)
{
if(creators == 0)
throw CL_Exception("EntityCreator map has not been instanciated!");
std::map<CL_String, CL_String>::iterator creatorIt = creators->find(type);
if(creatorIt == creators->end())
throw CL_Exception(cl_format("%1 %2", "Unable to create entity of type", type));
IEntity *entity = NULL;
std::map<CL_String, CL_String>::iterator specialIt = entity_specials.find(type);
if(specialIt != entity_specials.end())
{
CL_String specialType = specialIt->second;
entity = CreateSpecial(specialType, type, name);
}
else
{
entity = new IEntity(coreMgr->getEntityMgr()->genUId(), type, name, coreMgr, *coreMgr->getEntityMgr()->getComponentFactory());
}
return entity;
}
void EntityFactory::addDataAndLogic(IEntity *entity, const CL_String &type)
{
int fail = addComponents(entity, type);
if(fail)
throw CL_Exception("Failed to add components");
fail = addProperties(entity, type);
if(fail)
throw CL_Exception("Failed to set properties");
}
int EntityFactory::addComponents(IEntity *entity, const CL_String &type)
{
std::map<CL_String, std::vector<CL_String>>::iterator compIt = entity_components.find(type);
if(compIt == entity_components.end())
{
return 1;
}
std::vector<CL_String> compTypes = compIt->second;
for(unsigned int i = 0; i < compTypes.size(); i++)
{
try
{
entity->AddComponent(compTypes[i]);
}
catch(const CL_Exception &e)
{
CL_String err = cl_format("Failed to add component to Entity of type %1: %2", type, e.what());
throw CL_Exception(err);
}
}
return 0;
}
int EntityFactory::addProperties(IEntity *entity, const CL_String &type)
{
std::map<CL_String, std::vector<std::pair<CL_String, CL_String>>>::iterator propIt = entity_properties.find(type);
if(propIt == entity_properties.end())
{
return 1;
}
std::vector<std::pair<CL_String, CL_String>> propTypes = propIt->second;
for(unsigned int i = 0; i < propTypes.size(); i++)
{
CL_String name = propTypes[i].first;
if(!entity->HasProperty(name))
continue;
CL_String value = propTypes[i].second;
IProperty *propInterface = entity->GetIProperty(name);
propInterface->SetFromString(value);
}
return 0;
}
CL_String EntityFactory::loadEntity(const CL_String &fileName)
{
IResource *res = coreMgr->getResMgr()->create(cl_format("%1/%2", "Entities", fileName), "XML");
CL_String type = res->getString("Entity/Type");
CL_String inherit;
try
{
inherit = res->getString("Entity/Inherits");
}
catch(const CL_Exception &)
{
inherit = CL_String();
}
CL_String special;
try
{
special = res->getString("Entity/Special");
}
catch(const CL_Exception &)
{
special = CL_String();
}
//If this object inherits from another, make sure that the
//parent object is already loaded, if not, load it before
//we continue
bool inheritSupported = false;
if(inherit != CL_String())
{
std::map<CL_String, CL_String>::iterator creatorIt = creators->find(inherit);
if(creatorIt == creators->end())
{
registerEntity(cl_format("%1%2", inherit, ".xml"));
creatorIt = creators->find(inherit);
if(creatorIt != creators->end())
{
inheritSupported = true;
}
}
else
{
inheritSupported = true;
}
}
//Check for special entity type
if(special != CL_String())
{
entity_specials[type] = special;
}
loadComponents(res, type, inherit, inheritSupported);
loadProperties(res, type, inherit, inheritSupported);
return type;
}
void EntityFactory::loadComponents(IResource *res, const CL_String &type, const CL_String &inherit, bool inheritSupported)
{
std::vector<CL_String> compTypes;
//First add inherited components
if(inheritSupported)
{
std::map<CL_String, std::vector<CL_String>>::iterator inheritIt = entity_components.find(inherit);
if(inheritIt != entity_components.end())
{
std::vector<CL_String> inheritCompTypes = inheritIt->second;
for(unsigned int i = 0; i < inheritCompTypes.size(); i++)
{
compTypes.push_back(inheritCompTypes[i]);
}
}
}
//Then add unique components
XMLResource *cl_res = static_cast<XMLResource*>(res);
std::vector<CL_DomNode> components = cl_res->getDoc().select_nodes("/Entity/Components/Component");
for(unsigned int i = 0; i < components.size(); i++)
{
CL_DomElement compType = components[i].to_element();
int alreadyExist = -1;
for(unsigned int j = 0; j < compTypes.size(); j++)
{
if(compTypes[j] == compType.get_text())
{
alreadyExist = j;
break;
}
}
if(alreadyExist == -1)
compTypes.push_back(compType.get_text());
}
entity_components[type] = compTypes;
}
void EntityFactory::loadProperties(IResource *res, const CL_String &type, const CL_String &inherit, bool inheritSupported)
{
std::vector<std::pair<CL_String,CL_String>> propTypes;
//First add inherited properties
if(inheritSupported)
{
std::map<CL_String, std::vector<std::pair<CL_String,CL_String>>>::iterator inheritIt = entity_properties.find(inherit);
if(inheritIt != entity_properties.end())
{
std::vector<std::pair<CL_String,CL_String>> inheritPropTypes = inheritIt->second;
for(unsigned int i = 0; i < inheritPropTypes.size(); i++)
{
propTypes.push_back(inheritPropTypes[i]);
}
}
}
//Then add unique properties
XMLResource *cl_res = static_cast<XMLResource*>(res);
std::vector<CL_DomNode> properties = cl_res->getDoc().select_nodes("/Entity/Properties/Property");
for(unsigned int i = 0; i < properties.size(); i++)
{
CL_DomElement propType = properties[i].to_element();
CL_String propName = propType.get_child_string("Name");
CL_String propValue = propType.get_child_string("Value");
int alreadyExist = -1;
for(unsigned int j = 0; j < propTypes.size(); j++)
{
if(propTypes[j].first == propName)
{
alreadyExist = j;
break;
}
}
//If property already exist, then the last property value will always win
if(alreadyExist == -1)
propTypes.push_back(std::pair<CL_String,CL_String>(propName, propValue));
else
propTypes[alreadyExist] = std::pair<CL_String,CL_String>(propName, propValue);
}
entity_properties[type] = propTypes;
}
| [
"[email protected]@c628178a-a759-096a-d0f3-7c7507b30227"
]
| [
[
[
1,
321
]
]
]
|
15a47bde55b6c27a33ecc6d2d26fdacd20908416 | fcdddf0f27e52ece3f594c14fd47d1123f4ac863 | /terralib/src/terralib/drivers/qt/TeQtThemeItem.h | d00d959e30cd79f8844e6804d472adae9e85982b | []
| no_license | radtek/terra-printer | 32a2568b1e92cb5a0495c651d7048db6b2bbc8e5 | 959241e52562128d196ccb806b51fda17d7342ae | refs/heads/master | 2020-06-11T01:49:15.043478 | 2011-12-12T13:31:19 | 2011-12-12T13:31:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,120 | h | /************************************************************************************
TerraView - visualization and exploration of geographical databases
using TerraLib.
Copyright � 2001-2007 INPE and Tecgraf/PUC-Rio.
This file is part of TerraView. TerraView 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.
You should have received a copy of the GNU General Public License
along with TerraView.
The authors reassure the license terms regarding the warranties.
They specifically disclaim any warranties, including, but not limited to,
the implied warranties of merchantability and fitness for a particular purpose.
The software provided hereunder is on an "as is" basis, and the authors have no
obligation to provide maintenance, support, updates, enhancements, or modifications.
In no event shall INPE and Tecgraf / PUC-Rio be held liable to any party for direct,
indirect, special, incidental, or consequential damages arising out of the use of
this program and its documentation.
*************************************************************************************/
#ifndef __TERRALIB_INTERNAL_QTTHEMEITEM_H
#define __TERRALIB_INTERNAL_QTTHEMEITEM_H
#include <TeQtCheckListItem.h>
class TeAppTheme;
class TeLegendEntry;
class TLAPPUTILS_DLL TeQtThemeItem : public TeQtCheckListItem
{
public:
TeQtThemeItem(QListViewItem *parent, QString text, TeAppTheme* appTheme);
~TeQtThemeItem () {}
void setThemeItemAsInvalid();
bool isThemeItemInvalid()
{ return invalidThemeItem_; }
TeAppTheme* getAppTheme()
{return appTheme_;}
void removeLegends();
void removeCharts();
void getLegends(vector<const QPixmap*>& pixmapVector, vector<string>& labels, string& title);
TeQtCheckListItem* getLegendItem(TeLegendEntry* leg);
void updateAlias();
protected:
TeAppTheme *appTheme_;
bool invalidThemeItem_;
virtual void stateChange(bool);
};
#endif
| [
"[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec"
]
| [
[
[
1,
64
]
]
]
|
4013de0ca0bf2b62fa7e8882cc283f292365e4f5 | 974a20e0f85d6ac74c6d7e16be463565c637d135 | /trunk/coreLibrary_200/source/physics/dgCollisionCompoundBreakable.cpp | bc4d56922549f5da968c0e89c29ca5cba22cd726 | []
| no_license | Naddiseo/Newton-Dynamics-fork | cb0b8429943b9faca9a83126280aa4f2e6944f7f | 91ac59c9687258c3e653f592c32a57b61dc62fb6 | refs/heads/master | 2021-01-15T13:45:04.651163 | 2011-11-12T04:02:33 | 2011-11-12T04:02:33 | 2,759,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 56,352 | cpp | /* Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "dgPhysicsStdafx.h"
#include "dgWorld.h"
#include "dgMeshEffect.h"
#include "dgCollisionConvexHull.h"
#include "dgCollisionCompoundBreakable.h"
#define DG_DYNAMINIC_ISLAND_COST 0x7fffffff
dgCollisionCompoundBreakable::dgCollisionConvexIntance::dgCollisionConvexIntance(
dgCollisionConvex* convexChild,
dgCollisionCompoundBreakable::dgDebriGraph::dgListNode* node,
dgFloat32 density) :
dgCollisionConvex(convexChild->GetAllocator(), 0, dgGetIdentityMatrix(),
m_convexConvexIntance)
{
m_treeNode = NULL;
m_graphNode = node;
m_myShape = convexChild;
m_myShape->AddRef();
SetOffsetMatrix(m_myShape->GetOffsetMatrix());
((dgCollision*) convexChild)->CalculateInertia(m_inertia, m_volume);
m_volume.m_w = ((dgCollision*) convexChild)->GetVolume();
m_inertia = m_inertia.Scale(density * m_volume.m_w);
m_inertia.m_w = density * m_volume.m_w;
SetBreakImpulse(2500);
m_vertexCount = 1;
}
dgCollisionCompoundBreakable::dgCollisionConvexIntance::dgCollisionConvexIntance(
const dgCollisionConvexIntance& source,
dgCollisionCompoundBreakable::dgDebriGraph::dgListNode* node) :
dgCollisionConvex(source.GetAllocator(), 0, source.m_offset,
m_convexConvexIntance), m_inertia(source.m_inertia)
{
m_treeNode = NULL;
m_graphNode = node;
m_myShape = source.m_myShape;
m_myShape->AddRef();
m_vertexCount = 1;
m_volume = source.m_volume;
m_destructionImpulse = source.m_destructionImpulse;
}
dgCollisionCompoundBreakable::dgCollisionConvexIntance::dgCollisionConvexIntance(
dgWorld* const world, dgDeserialize deserialization, void* const userData) :
dgCollisionConvex(world, deserialization, userData)
{
m_graphNode = NULL;
m_treeNode = NULL;
m_vertexCount = 1;
deserialization(userData, &m_volume, sizeof(m_volume));
deserialization(userData, &m_inertia, sizeof(m_inertia));
deserialization(userData, &m_destructionImpulse,
sizeof(m_destructionImpulse));
m_myShape = new (world->GetAllocator()) dgCollisionConvexHull(world,
deserialization, userData);
}
dgCollisionCompoundBreakable::dgCollisionConvexIntance::~dgCollisionConvexIntance()
{
m_myShape->Release();
}
dgFloat32 dgCollisionCompoundBreakable::dgCollisionConvexIntance::GetVolume() const
{
return ((dgCollision*) m_myShape)->GetVolume();
}
bool dgCollisionCompoundBreakable::dgCollisionConvexIntance::OOBBTest(
const dgMatrix& matrix, const dgCollisionConvex* const shape,
void* const cacheOrder) const
{
return m_myShape->OOBBTest(matrix, shape, cacheOrder);
}
dgVector dgCollisionCompoundBreakable::dgCollisionConvexIntance::SupportVertex(
const dgVector& dir) const
{
return m_myShape->SupportVertex(dir);
}
dgVector dgCollisionCompoundBreakable::dgCollisionConvexIntance::SupportVertexSimd(
const dgVector& dir) const
{
return m_myShape->SupportVertexSimd(dir);
}
void dgCollisionCompoundBreakable::dgCollisionConvexIntance::CalcAABB(
const dgMatrix &matrix, dgVector& p0, dgVector& p1) const
{
m_myShape->CalcAABB(matrix, p0, p1);
}
void dgCollisionCompoundBreakable::dgCollisionConvexIntance::CalcAABBSimd(
const dgMatrix &matrix, dgVector &p0, dgVector &p1) const
{
m_myShape->CalcAABBSimd(matrix, p0, p1);
}
void dgCollisionCompoundBreakable::dgCollisionConvexIntance::DebugCollision(
const dgMatrix& matrix, OnDebugCollisionMeshCallback callback,
void* const userData) const
{
((dgCollision*) m_myShape)->DebugCollision(matrix, callback, userData);
}
dgFloat32 dgCollisionCompoundBreakable::dgCollisionConvexIntance::RayCast(
const dgVector& localP0, const dgVector& localP1,
dgContactPoint& contactOut, OnRayPrecastAction preFilter,
const dgBody* const body, void* const userData) const
{
return m_myShape->RayCast(localP0, localP1, contactOut, preFilter, body,
userData);
}
dgFloat32 dgCollisionCompoundBreakable::dgCollisionConvexIntance::RayCastSimd(
const dgVector& localP0, const dgVector& localP1,
dgContactPoint& contactOut, OnRayPrecastAction preFilter,
const dgBody* const body, void* const userData) const
{
return m_myShape->RayCastSimd(localP0, localP1, contactOut, preFilter, body,
userData);
}
dgVector dgCollisionCompoundBreakable::dgCollisionConvexIntance::CalculateVolumeIntegral(
const dgMatrix& globalMatrix, GetBuoyancyPlane bouyancyPlane,
void* const context) const
{
return ((dgCollision*) m_myShape)->CalculateVolumeIntegral(globalMatrix,
bouyancyPlane, context);
}
dgInt32 dgCollisionCompoundBreakable::dgCollisionConvexIntance::CalculateSignature() const
{
return 0;
// return ((dgCollision*)m_myShape)->CalculateSignature ();
}
void dgCollisionCompoundBreakable::dgCollisionConvexIntance::SetCollisionBBox(
const dgVector& p0, const dgVector& p1)
{
m_myShape->SetCollisionBBox(p0, p1);
}
dgFloat32 dgCollisionCompoundBreakable::dgCollisionConvexIntance::GetBoxMinRadius() const
{
return ((dgCollision*) m_myShape)->GetBoxMinRadius();
}
dgFloat32 dgCollisionCompoundBreakable::dgCollisionConvexIntance::GetBoxMaxRadius() const
{
return ((dgCollision*) m_myShape)->GetBoxMaxRadius();
}
dgInt32 dgCollisionCompoundBreakable::dgCollisionConvexIntance::CalculatePlaneIntersection(
const dgVector& normal, const dgVector& point,
dgVector* const contactsOut) const
{
return m_myShape->CalculatePlaneIntersection(normal, point, contactsOut);
}
dgInt32 dgCollisionCompoundBreakable::dgCollisionConvexIntance::CalculatePlaneIntersectionSimd(
const dgVector& normal, const dgVector& point,
dgVector* const contactsOut) const
{
return m_myShape->CalculatePlaneIntersectionSimd(normal, point, contactsOut);
}
void dgCollisionCompoundBreakable::dgCollisionConvexIntance::GetCollisionInfo(
dgCollisionInfo* info) const
{
m_myShape->GetCollisionInfo(info);
}
void dgCollisionCompoundBreakable::dgCollisionConvexIntance::Serialize(
dgSerialize callback, void* const userData) const
{
SerializeLow(callback, userData);
callback(userData, &m_volume, sizeof(m_volume));
callback(userData, &m_inertia, sizeof(m_inertia));
callback(userData, &m_destructionImpulse, sizeof(m_destructionImpulse));
m_myShape->Serialize(callback, userData);
}
void dgCollisionCompoundBreakable::dgCollisionConvexIntance::SetBreakImpulse(
dgFloat32 force)
{
m_destructionImpulse = force;
}
dgFloat32 dgCollisionCompoundBreakable::dgCollisionConvexIntance::GetBreakImpulse() const
{
return m_destructionImpulse;
}
dgCollisionCompoundBreakable::dgVertexBuffer::dgVertexBuffer(dgInt32 vertsCount,
dgMemoryAllocator* allocator)
{
m_allocator = allocator;
m_vertexCount = vertsCount;
m_uv = (dgFloat32 *) m_allocator->Malloc(
2 * vertsCount * dgInt32(sizeof(dgFloat32)));
m_vertex = (dgFloat32 *) m_allocator->Malloc(
3 * vertsCount * dgInt32(sizeof(dgFloat32)));
m_normal = (dgFloat32 *) m_allocator->Malloc(
3 * vertsCount * dgInt32(sizeof(dgFloat32)));
}
dgCollisionCompoundBreakable::dgVertexBuffer::~dgVertexBuffer()
{
m_allocator->Free(m_normal);
m_allocator->Free(m_vertex);
m_allocator->Free(m_uv);
}
dgCollisionCompoundBreakable::dgVertexBuffer::dgVertexBuffer(
dgMemoryAllocator* const allocator, dgDeserialize callback,
void* const userData)
{
m_allocator = allocator;
callback(userData, &m_vertexCount, dgInt32(sizeof(dgInt32)));
m_uv = (dgFloat32 *) m_allocator->Malloc(
2 * m_vertexCount * dgInt32(sizeof(dgFloat32)));
m_vertex = (dgFloat32 *) m_allocator->Malloc(
3 * m_vertexCount * dgInt32(sizeof(dgFloat32)));
m_normal = (dgFloat32 *) m_allocator->Malloc(
3 * m_vertexCount * dgInt32(sizeof(dgFloat32)));
callback(userData, m_vertex,
size_t(3 * m_vertexCount * dgInt32(sizeof(dgFloat32))));
callback(userData, m_normal,
size_t(3 * m_vertexCount * dgInt32(sizeof(dgFloat32))));
callback(userData, m_uv,
size_t(2 * m_vertexCount * dgInt32(sizeof(dgFloat32))));
}
void dgCollisionCompoundBreakable::dgVertexBuffer::Serialize(
dgSerialize callback, void* const userData) const
{
callback(userData, &m_vertexCount, dgInt32(sizeof(dgInt32)));
callback(userData, m_vertex,
size_t(3 * m_vertexCount * dgInt32(sizeof(dgFloat32))));
callback(userData, m_normal,
size_t(3 * m_vertexCount * dgInt32(sizeof(dgFloat32))));
callback(userData, m_uv,
size_t(2 * m_vertexCount * dgInt32(sizeof(dgFloat32))));
}
void dgCollisionCompoundBreakable::dgVertexBuffer::GetVertexStreams(
dgInt32 vertexStrideInByte, dgFloat32* vertex, dgInt32 normalStrideInByte,
dgFloat32* normal, dgInt32 uvStrideInByte, dgFloat32* uv) const
{
uvStrideInByte /= dgInt32(sizeof(dgFloat32));
vertexStrideInByte /= dgInt32(sizeof(dgFloat32));
normalStrideInByte /= dgInt32(sizeof(dgFloat32));
for (dgInt32 i = 0; i < m_vertexCount; i++)
{
dgInt32 j = i * vertexStrideInByte;
vertex[j + 0] = m_vertex[i * 3 + 0];
vertex[j + 1] = m_vertex[i * 3 + 1];
vertex[j + 2] = m_vertex[i * 3 + 2];
j = i * normalStrideInByte;
normal[j + 0] = m_normal[i * 3 + 0];
normal[j + 1] = m_normal[i * 3 + 1];
normal[j + 2] = m_normal[i * 3 + 2];
j = i * uvStrideInByte;
uv[j + 0] = m_uv[i * 2 + 0];
uv[j + 1] = m_uv[i * 2 + 1];
}
}
dgCollisionCompoundBreakable::dgSubMesh::dgSubMesh(
dgMemoryAllocator* const allocator)
{
m_material = 0;
m_faceCount = 0;
m_indexes = NULL;
m_faceOffset = 0;
m_visibleFaces = 1;
m_allocator = allocator;
}
dgCollisionCompoundBreakable::dgSubMesh::~dgSubMesh()
{
if (m_indexes)
{
// m_allocator->Free (m_visibilityMap);
m_allocator->Free(m_indexes);
}
}
void dgCollisionCompoundBreakable::dgSubMesh::Serialize(dgSerialize callback,
void* const userData) const
{
callback(userData, &m_material, dgInt32(sizeof(dgInt32)));
callback(userData, &m_faceCount, dgInt32(sizeof(dgInt32)));
callback(userData, &m_faceOffset, dgInt32(sizeof(dgInt32)));
callback(userData, &m_visibleFaces, dgInt32(sizeof(dgInt32)));
callback(userData, m_indexes,
size_t(3 * m_faceCount * dgInt32(sizeof(dgInt32))));
}
dgCollisionCompoundBreakable::dgMesh::dgMesh(dgMemoryAllocator* const allocator) :
dgList<dgSubMesh>(allocator)
{
m_IsVisible = 1;
}
dgCollisionCompoundBreakable::dgMesh::~dgMesh()
{
}
dgCollisionCompoundBreakable::dgMesh::dgMesh(dgMemoryAllocator* const allocator,
dgDeserialize callback, void* const userData) :
dgList<dgSubMesh>(allocator), dgRefCounter()
{
dgInt32 count;
callback(userData, &m_IsVisible, dgInt32(sizeof(dgInt32)));
callback(userData, &count, dgInt32(sizeof(dgInt32)));
for (dgInt32 i = 0; i < count; i++)
{
dgInt32 material;
dgInt32 faceCount;
dgInt32 faceOffset;
dgInt32 exteriorFaces;
callback(userData, &material, dgInt32(sizeof(dgInt32)));
callback(userData, &faceCount, dgInt32(sizeof(dgInt32)));
callback(userData, &faceOffset, dgInt32(sizeof(dgInt32)));
callback(userData, &exteriorFaces, dgInt32(sizeof(dgInt32)));
dgSubMesh* const subMesh = AddgSubMesh(faceCount * 3, material);
subMesh->m_faceOffset = faceOffset;
subMesh->m_visibleFaces = exteriorFaces;
// callback (userData, subMesh->m_visibilityMap, faceCount * dgInt32 (sizeof (dgInt32)));
callback(userData, subMesh->m_indexes,
size_t(3 * faceCount * sizeof(dgInt32)));
}
}
void dgCollisionCompoundBreakable::dgMesh::Serialize(dgSerialize callback,
void* const userData) const
{
dgInt32 count;
count = GetCount();
callback(userData, &m_IsVisible, dgInt32(sizeof(dgInt32)));
callback(userData, &count, dgInt32(sizeof(dgInt32)));
for (dgListNode* node = GetFirst(); node; node = node->GetNext())
{
dgSubMesh& subMesh = node->GetInfo();
subMesh.Serialize(callback, userData);
}
}
dgCollisionCompoundBreakable::dgSubMesh* dgCollisionCompoundBreakable::dgMesh::AddgSubMesh(
dgInt32 indexCount, dgInt32 material)
{
dgSubMesh tmp(GetAllocator());
dgSubMesh& subMesh = Append(tmp)->GetInfo();
subMesh.m_faceOffset = 0;
subMesh.m_visibleFaces = 1;
subMesh.m_material = material;
subMesh.m_faceCount = indexCount / 3;
subMesh.m_indexes = (dgInt32 *) subMesh.m_allocator->Malloc(
indexCount * dgInt32(sizeof(dgInt32)));
return &subMesh;
}
dgCollisionCompoundBreakable::dgDebriNodeInfo::dgDebriNodeInfo()
{
m_mesh = NULL;
m_shape = NULL;
memset(&m_commonData, 0, sizeof(m_commonData));
}
dgCollisionCompoundBreakable::dgDebriNodeInfo::~dgDebriNodeInfo()
{
if (m_shape)
{
m_shape->Release();
}
if (m_mesh)
{
m_mesh->Release();
}
}
dgCollisionCompoundBreakable::dgSharedNodeMesh::dgSharedNodeMesh()
{
}
dgCollisionCompoundBreakable::dgSharedNodeMesh::~dgSharedNodeMesh()
{
}
dgCollisionCompoundBreakable::dgDebriGraph::dgDebriGraph(
dgMemoryAllocator* const allocator) :
dgGraph<dgDebriNodeInfo, dgSharedNodeMesh>(allocator)
{
}
dgCollisionCompoundBreakable::dgDebriGraph::dgDebriGraph(
dgMemoryAllocator* const allocator, dgDeserialize callback,
void* const userData) :
dgGraph<dgDebriNodeInfo, dgSharedNodeMesh>(allocator)
{
dgInt32 count;
dgGraph<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* node;
callback(userData, &count, dgInt32(sizeof(dgInt32)));
dgStack<dgListNode*> nodesMap(count);
node = dgGraph<dgDebriNodeInfo, dgSharedNodeMesh>::AddNode();
dgDebriNodeInfo& data = GetFirst()->GetInfo().m_nodeData;
callback(userData, &data.m_commonData, sizeof(data.m_commonData));
nodesMap[0] = node;
for (dgInt32 i = 1; i < count; i++)
{
dgGraph<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* node;
node = dgGraph<dgDebriNodeInfo, dgSharedNodeMesh>::AddNode();
dgDebriNodeInfo& data = node->GetInfo().m_nodeData;
callback(userData, &data.m_commonData, sizeof(data.m_commonData));
data.m_mesh = new (GetAllocator()) dgMesh(GetAllocator(), callback,
userData);
nodesMap[i] = node;
}
for (dgInt32 i = 0; i < count - 1; i++)
{
dgInt32 edges;
callback(userData, &edges, dgInt32(sizeof(dgInt32)));
dgStack<dgInt32> pool(edges);
callback(userData, &pool[0], size_t(edges * dgInt32(sizeof(dgInt32))));
for (dgInt32 j = 0; j < edges; j++)
{
nodesMap[i]->GetInfo().AddEdge(nodesMap[pool[j]]);
}
}
}
dgCollisionCompoundBreakable::dgDebriGraph::dgDebriGraph(
const dgDebriGraph& source) :
dgGraph<dgDebriNodeInfo, dgSharedNodeMesh>(source.GetAllocator())
{
dgGraph<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* newNode;
dgTree<dgListNode*, dgListNode*> filter(GetAllocator());
newNode = dgGraph<dgDebriNodeInfo, dgSharedNodeMesh>::AddNode();
dgDebriNodeInfo& data = newNode->GetInfo().m_nodeData;
dgDebriNodeInfo& srcData = source.GetFirst()->GetInfo().m_nodeData;
data.m_commonData = srcData.m_commonData;
filter.Insert(newNode, source.GetFirst());
for (dgGraph<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* node =
source.GetFirst()->GetNext(); node; node = node->GetNext())
{
newNode = dgGraph<dgDebriNodeInfo, dgSharedNodeMesh>::AddNode();
dgDebriNodeInfo& srcData = node->GetInfo().m_nodeData;
dgDebriNodeInfo& data = newNode->GetInfo().m_nodeData;
data.m_commonData = srcData.m_commonData;
data.m_mesh = srcData.m_mesh;
data.m_mesh->AddRef();
filter.Insert(newNode, node);
}
for (dgListNode* node = source.GetFirst(); node; node = node->GetNext())
{
dgListNode* myNode = filter.Find(node)->GetInfo();
for (dgGraphNode<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* edgeNode =
node->GetInfo().GetFirst(); edgeNode; edgeNode = edgeNode->GetNext())
{
dgListNode* otherNode;
otherNode = filter.Find(edgeNode->GetInfo().m_node)->GetInfo();
myNode->GetInfo().AddEdge(otherNode);
}
}
}
dgCollisionCompoundBreakable::dgDebriGraph::~dgDebriGraph()
{
}
void dgCollisionCompoundBreakable::dgDebriGraph::Serialize(dgSerialize callback,
void* const userData) const
{
dgInt32 lru;
dgInt32 index;
dgInt32 count;
dgTree<dgInt32, dgListNode*> enumerator(GetAllocator());
lru = 0;
index = 1;
count = GetCount();
callback(userData, &count, dgInt32(sizeof(dgInt32)));
dgDebriNodeInfo& data = GetFirst()->GetInfo().m_nodeData;
dgDebriNodeInfo::PackedSaveData packedData(data.m_commonData);
packedData.m_lru = 0;
callback(userData, &packedData, sizeof(packedData));
enumerator.Insert(0, GetFirst());
for (dgListNode* node = GetFirst()->GetNext(); node; node = node->GetNext())
{
dgDebriNodeInfo& data = node->GetInfo().m_nodeData;
dgDebriNodeInfo::PackedSaveData packedData(data.m_commonData);
packedData.m_lru = 0;
callback(userData, &packedData, sizeof(packedData));
data.m_mesh->Serialize(callback, userData);
enumerator.Insert(index, node);
index++;
}
for (dgListNode* node = GetFirst(); node != GetLast(); node = node->GetNext())
{
dgInt32 count;
index = 0;
count = node->GetInfo().GetCount();
callback(userData, &count, dgInt32(sizeof(dgInt32)));
dgStack<dgInt32> buffer(count);
dgInt32* const pool = &buffer[0];
for (dgGraphNode<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* edgeNode =
node->GetInfo().GetFirst(); edgeNode; edgeNode = edgeNode->GetNext())
{
pool[index] = enumerator.Find(edgeNode->GetInfo().m_node)->GetInfo();
index++;
}
callback(userData, &pool[0], size_t(count * sizeof(dgInt32)));
}
}
void dgCollisionCompoundBreakable::dgDebriGraph::AddNode(
dgFlatVertexArray& flatArray, dgMeshEffect* solid, dgInt32 clipperMaterial,
dgInt32 id, dgFloat32 density, dgFloat32 padding)
{
_ASSERTE(0);
/*
dgCollision* collision;
collision = solid->CreateConvexCollision(dgFloat32 (0.005f), id, padding, dgGetIdentityMatrix());
_ASSERTE (collision);
if (collision) {
dgGraph<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* node;
dgInt32 vertexCount;
dgInt32 baseVertexCount;
dgCollision* collisionInstance;
dgMeshEffect::dgIndexArray* geometryHandle;
node = dgGraph<dgDebriNodeInfo, dgSharedNodeMesh>::AddNode ();
dgDebriNodeInfo& data = node->GetInfo().m_nodeData;
collisionInstance = new (GetAllocator()) dgCollisionConvexIntance ((dgCollisionConvex*) collision, node, density);
collision->Release();
data.m_mesh = new (GetAllocator()) dgMesh(GetAllocator());
data.m_shape = (dgCollisionConvex*)collisionInstance;
vertexCount = solid->GetPropertiesCount() * 6;
dgStack<dgVector>vertex (vertexCount);
dgStack<dgVector>normal (vertexCount);
dgStack<dgVector>uv0 (vertexCount);
dgStack<dgVector>uv1 (vertexCount);
solid->GetVertexStreams (sizeof (dgVector), &vertex[0].m_x, sizeof (dgVector), &normal[0].m_x, sizeof (dgVector), &uv0[0].m_x, sizeof (dgVector), &uv1[0].m_x);
// extract the materials index array for mesh
geometryHandle = solid->MaterialGeometryBegin();
data.m_mesh->m_IsVisible = 0;
vertexCount = flatArray.m_count;
baseVertexCount = flatArray.m_count;
for (dgInt32 handle = solid->GetFirstMaterial (geometryHandle); handle != -1; handle = solid->GetNextMaterial (geometryHandle, handle)) {
dgInt32 isVisible;
dgInt32 material;
dgInt32 indexCount;
dgSubMesh* segment;
// isVisible = 1;
material = solid->GetMaterialID (geometryHandle, handle);
// if (material == clipperMaterial) {
// isVisible = 0;
// }
isVisible = (material != clipperMaterial) ? 1 : 0;
data.m_mesh->m_IsVisible |= isVisible;
indexCount = solid->GetMaterialIndexCount (geometryHandle, handle);
segment = data.m_mesh->AddgSubMesh(indexCount, material);
segment->m_visibleFaces = isVisible;
solid->GetMaterialGetIndexStream (geometryHandle, handle, segment->m_indexes);
for (dgInt32 i = 0; i < indexCount; i ++) {
dgInt32 j;
j = segment->m_indexes[i];
flatArray[vertexCount].m_point[0] = vertex[j].m_x;
flatArray[vertexCount].m_point[1] = vertex[j].m_y;
flatArray[vertexCount].m_point[2] = vertex[j].m_z;
flatArray[vertexCount].m_point[3] = normal[j].m_x;
flatArray[vertexCount].m_point[4] = normal[j].m_y;
flatArray[vertexCount].m_point[5] = normal[j].m_z;
flatArray[vertexCount].m_point[6] = uv0[j].m_x;
flatArray[vertexCount].m_point[7] = uv0[j].m_y;
flatArray[vertexCount].m_point[8] = uv1[j].m_x;
flatArray[vertexCount].m_point[9] = uv1[j].m_y;
segment->m_indexes[i] = vertexCount - baseVertexCount;
vertexCount ++;
// _ASSERTE ((vertexCount - baseVertexCount) < dgInt32 (indexBuffer.GetElementsCount()));
}
}
solid->MaterialGeomteryEnd(geometryHandle);
dgStack<dgInt32> indexBuffer (vertexCount - baseVertexCount);
flatArray.m_count += dgVertexListToIndexList (&flatArray[baseVertexCount].m_point[0], sizeof (dgFlatVertex), sizeof (dgFlatVertex), 0, vertexCount - baseVertexCount, &indexBuffer[0], dgFloat32 (1.0e-6f));
for (dgMesh::dgListNode* meshSgement = data.m_mesh->GetFirst(); meshSgement; meshSgement = meshSgement->GetNext()) {
dgSubMesh* const subMesh = &meshSgement->GetInfo();
for (dgInt32 i = 0; i < subMesh->m_faceCount * 3; i ++) {
dgInt32 j;
j = subMesh->m_indexes[i];
subMesh->m_indexes[i] = baseVertexCount + indexBuffer[j];
}
}
}
*/
}
void dgCollisionCompoundBreakable::dgDebriGraph::AddMeshes(
dgFlatVertexArray& vertexArray, dgInt32 count,
const dgMeshEffect* const solidArray[], const dgInt32* const idArray,
const dgFloat32* const densities, const dgInt32* const internalFaceMaterial,
dgFloat32 padding)
{
//padding = 0.0f;
dgGraph<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* fixNode;
fixNode = dgGraph<dgDebriNodeInfo, dgSharedNodeMesh>::AddNode();
for (dgInt32 i = 0; i < count; i++)
{
AddNode(vertexArray, (dgMeshEffect*) solidArray[i], internalFaceMaterial[i],
idArray[i], densities[i], padding);
}
}
dgCollisionCompoundBreakable::dgCollisionCompoundBreakable(dgInt32 count,
const dgMeshEffect* const solidArray[], const dgInt32* const idArray,
const dgFloat32* const densities, const dgInt32* const internalFaceMaterial,
dgInt32 debriiId, dgFloat32 collisionPadding, dgWorld* world) :
dgCollisionCompound(world), m_conectivity(world->GetAllocator()), m_detachedIslands(
world->GetAllocator())
{
dgInt32 acc;
dgInt32 indexCount;
dgInt32 vertsCount;
dgInt32 materialHitogram[256];
dgInt32 faceOffsetHitogram[256];
dgSubMesh* mainSegmenst[256];
dgMesh* mainMesh;
dgFlatVertexArray vertexArray(m_world->GetAllocator());
m_lru = 0;
m_lastIslandColor = 0;
m_visibilityMapIndexCount = 0;
m_vertexBuffer = NULL;
m_visibilityMap = NULL;
m_visibilityInderectMap = NULL;
m_collsionId = m_compoundBreakable;
m_rtti |= dgCollisionCompoundBreakable_RTTI;
if (collisionPadding < dgFloat32(0.01f))
{
collisionPadding = dgFloat32(0.01f);
}
m_conectivity.AddMeshes(vertexArray, count, solidArray, idArray, densities,
internalFaceMaterial, collisionPadding);
dgStack<dgCollisionConvex*> shapeArrayPool(m_conectivity.GetCount());
dgCollisionConvex** const shapeArray = &shapeArrayPool[0];
indexCount = 0;
for (dgDebriGraph::dgListNode* node = m_conectivity.GetFirst()->GetNext();
node; node = node->GetNext())
{
dgDebriNodeInfo& data = node->GetInfo().m_nodeData;
shapeArray[indexCount] = data.m_shape;
indexCount++;
}
if (indexCount)
{
m_root = BuildTree(indexCount, &shapeArray[0]);
}
Init(indexCount, &shapeArray[0]);
dgStack<dgInt32> indexBuffer(vertexArray.m_count);
vertsCount = dgVertexListToIndexList(&vertexArray[0].m_point[0],
sizeof(dgFlatVertex), sizeof(dgFlatVertex), 0, vertexArray.m_count,
&indexBuffer[0], dgFloat32(1.0e-6f));
m_vertexBuffer = new (m_world->GetAllocator()) dgVertexBuffer(vertsCount,
m_world->GetAllocator());
for (dgInt32 i = 0; i < vertsCount; i++)
{
m_vertexBuffer->m_vertex[i * 3 + 0] = vertexArray[i].m_point[0];
m_vertexBuffer->m_vertex[i * 3 + 1] = vertexArray[i].m_point[1];
m_vertexBuffer->m_vertex[i * 3 + 2] = vertexArray[i].m_point[2];
m_vertexBuffer->m_normal[i * 3 + 0] = vertexArray[i].m_point[3];
m_vertexBuffer->m_normal[i * 3 + 1] = vertexArray[i].m_point[4];
m_vertexBuffer->m_normal[i * 3 + 2] = vertexArray[i].m_point[5];
m_vertexBuffer->m_uv[i * 2 + 0] = vertexArray[i].m_point[6];
m_vertexBuffer->m_uv[i * 2 + 1] = vertexArray[i].m_point[7];
}
memset(materialHitogram, 0, sizeof(materialHitogram));
memset(faceOffsetHitogram, 0, sizeof(faceOffsetHitogram));
memset(mainSegmenst, 0, sizeof(mainSegmenst));
for (dgDebriGraph::dgListNode* node = m_conectivity.GetFirst()->GetNext();
node; node = node->GetNext())
{
dgDebriNodeInfo& data = node->GetInfo().m_nodeData;
for (dgMesh::dgListNode* meshSgement = data.m_mesh->GetFirst(); meshSgement;
meshSgement = meshSgement->GetNext())
{
dgInt32 material;
dgSubMesh* const subMesh = &meshSgement->GetInfo();
material = subMesh->m_material;
materialHitogram[material] += subMesh->m_faceCount;
}
}
dgDebriNodeInfo& mainNodeData = m_conectivity.dgGraph<dgDebriNodeInfo,
dgSharedNodeMesh>::AddNode()->GetInfo().m_nodeData;
acc = 0;
mainMesh = new (m_world->GetAllocator()) dgMesh(m_world->GetAllocator());
mainNodeData.m_mesh = mainMesh;
for (dgInt32 i = 0; i < 256; i++)
{
if (materialHitogram[i])
{
dgSubMesh* segment;
segment = mainMesh->AddgSubMesh(materialHitogram[i] * 3, i);
segment->m_faceOffset = acc;
segment->m_faceCount = 0;
mainSegmenst[i] = segment;
}
faceOffsetHitogram[i] = acc;
acc += materialHitogram[i];
}
m_visibilityMapIndexCount = acc;
m_visibilityMap = (dgInt8*) m_allocator->Malloc(
dgInt32(acc * sizeof(dgInt8)));
m_visibilityInderectMap = (dgInt32*) m_allocator->Malloc(
acc * dgInt32(sizeof(dgInt32)));
acc = 0;
for (dgDebriGraph::dgListNode* node = m_conectivity.GetFirst()->GetNext();
node != m_conectivity.GetLast(); node = node->GetNext())
{
dgDebriNodeInfo& data = node->GetInfo().m_nodeData;
for (dgMesh::dgListNode* node = data.m_mesh->GetFirst(); node;
node = node->GetNext())
{
dgInt8 visbility;
dgInt32 rootIndexCount;
dgSubMesh& segment = node->GetInfo();
dgSubMesh& rootSegment = *mainSegmenst[segment.m_material];
visbility = dgInt8(segment.m_visibleFaces);
memset(&m_visibilityMap[acc], visbility, size_t(segment.m_faceCount));
for (dgInt32 i = 0; i < segment.m_faceCount; i++)
{
m_visibilityInderectMap[faceOffsetHitogram[segment.m_material] + i] =
acc + i;
}
faceOffsetHitogram[segment.m_material] += segment.m_faceCount;
rootIndexCount = rootSegment.m_faceCount * 3;
for (dgInt32 i = 0; i < segment.m_faceCount * 3; i++)
{
dgInt32 j;
j = segment.m_indexes[i];
segment.m_indexes[i] = indexBuffer[j];
rootSegment.m_indexes[rootIndexCount] = indexBuffer[j];
rootIndexCount++;
}
rootSegment.m_faceCount = rootIndexCount / 3;
segment.m_faceOffset = acc;
// _ASSERTE (acc == segment.m_faceOffset);
acc += segment.m_faceCount;
}
}
LinkNodes();
dgMatrix matrix(dgGetIdentityMatrix());
for (dgDebriGraph::dgListNode* node = m_conectivity.GetFirst()->GetNext();
node != m_conectivity.GetLast(); node = node->GetNext())
{
dgInt32 stack;
dgCollisionConvexIntance* myShape;
dgNodeBase* pool[DG_COMPOUND_STACK_DEPTH];
myShape = (dgCollisionConvexIntance*) node->GetInfo().m_nodeData.m_shape;
pool[0] = m_root;
stack = 1;
dgVector p0(myShape->m_treeNode->m_p0);
dgVector p1(myShape->m_treeNode->m_p1);
p0 -= dgVector(dgFloat32(1.0e-2f), dgFloat32(1.0e-2f), dgFloat32(1.0e-2f),
dgFloat32(0.0f));
p1 += dgVector(dgFloat32(1.0e-2f), dgFloat32(1.0e-2f), dgFloat32(1.0e-2f),
dgFloat32(0.0f));
while (stack)
{
dgNodeBase* treeNode;
stack--;
treeNode = pool[stack];
if (dgOverlapTest(p0, p1, treeNode->m_p0, treeNode->m_p1))
{
if (treeNode->m_type == m_leaf)
{
dgCollisionConvexIntance* otherShape;
otherShape = (dgCollisionConvexIntance*) treeNode->m_shape;
if (otherShape->m_graphNode != node)
{
dgGraphNode<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* adjacentEdge;
// _ASSERTE (otherShape->m_graphNode != node)
for (adjacentEdge = node->GetInfo().GetFirst(); adjacentEdge;
adjacentEdge = adjacentEdge->GetNext())
{
if (adjacentEdge->GetInfo().m_node == otherShape->m_graphNode)
{
break;
}
}
if (!adjacentEdge)
{
dgInt32 disjoint;
dgTriplex normal;
dgTriplex contactA;
dgTriplex contactB;
const dgFloat32 minSeparation = dgFloat32(2.0f) * collisionPadding
+ dgFloat32(0.05f);
const dgFloat32 minSeparation2 = minSeparation * minSeparation;
disjoint = world->ClosestPoint(myShape, matrix, otherShape,
matrix, contactA, contactB, normal, 0);
if (disjoint)
{
dgVector qA(contactA.m_x, contactA.m_y, contactA.m_z,
dgFloat32(0.0f));
dgVector qB(contactB.m_x, contactB.m_y, contactB.m_z,
dgFloat32(0.0f));
dgVector dist(qB - qA);
disjoint = (dist % dist) > minSeparation2;
}
if (!disjoint)
{
otherShape->m_graphNode->GetInfo().AddEdge(node);
node->GetInfo().AddEdge(otherShape->m_graphNode);
}
}
}
}
else
{
_ASSERTE(treeNode->m_type == m_node);
pool[stack] = treeNode->m_right;
stack++;
pool[stack] = treeNode->m_left;
stack++;
}
}
}
}
ResetAnchor();
//m_conectivity.Trace();
}
dgCollisionCompoundBreakable::dgCollisionCompoundBreakable(
const dgCollisionCompoundBreakable& source) :
dgCollisionCompound(source), m_conectivity(source.m_conectivity), m_detachedIslands(
source.m_conectivity.GetAllocator())
{
dgInt32 stack;
dgNodeBase* stackPool[DG_COMPOUND_STACK_DEPTH];
dgTree<dgCompoundBreakableFilterData, dgCollisionConvex*> graphNodeMap(
m_allocator);
m_lru = source.m_lru;
m_lastIslandColor = source.m_lastIslandColor;
m_visibilityMapIndexCount = source.m_visibilityMapIndexCount;
m_visibilityMap = (dgInt8 *) m_allocator->Malloc(
dgInt32(source.m_visibilityMapIndexCount * sizeof(dgInt8)));
memcpy(m_visibilityMap, source.m_visibilityMap,
size_t(source.m_visibilityMapIndexCount * sizeof(dgInt8)));
m_visibilityInderectMap = (dgInt32 *) m_allocator->Malloc(
source.m_visibilityMapIndexCount * dgInt32(sizeof(dgInt32)));
memcpy(m_visibilityInderectMap, source.m_visibilityInderectMap,
size_t(source.m_visibilityMapIndexCount * dgInt32(sizeof(dgInt32))));
m_vertexBuffer = source.m_vertexBuffer;
m_vertexBuffer->AddRef();
m_collsionId = m_compoundBreakable;
m_rtti |= dgCollisionCompoundBreakable_RTTI;
stack = 0;
dgDebriGraph::dgListNode* myNode = m_conectivity.GetFirst()->GetNext();
for (dgDebriGraph::dgListNode* node =
source.m_conectivity.GetFirst()->GetNext();
node != source.m_conectivity.GetLast(); myNode = myNode->GetNext(), node =
node->GetNext())
{
dgCompoundBreakableFilterData info;
dgDebriNodeInfo& nodeInfo = node->GetInfo().m_nodeData;
info.m_index = stack;
info.m_node = myNode;
graphNodeMap.Insert(info, nodeInfo.m_shape);
_ASSERTE(m_array[stack] == nodeInfo.m_shape);
stack++;
}
stack = 1;
stackPool[0] = m_root;
while (stack)
{
dgNodeBase *me;
stack--;
me = stackPool[stack];
if (me->m_type == m_leaf)
{
dgInt32 index;
dgCollisionConvexIntance* newShape;
dgCompoundBreakableFilterData& info =
graphNodeMap.Find(me->m_shape)->GetInfo();
index = info.m_index;
_ASSERTE(m_array[index] == me->m_shape);
_ASSERTE(!info.m_node->GetInfo().m_nodeData.m_shape);
// newShape = new dgCollisionConvexIntance (((dgCollisionConvexIntance*) me->m_shape)->m_myShape, info.m_node, 0);
newShape = new (m_allocator) dgCollisionConvexIntance(
*((dgCollisionConvexIntance*) me->m_shape), info.m_node);
info.m_node->GetInfo().m_nodeData.m_shape = newShape;
me->m_shape->Release();
me->m_shape = newShape;
newShape->AddRef();
m_array[index]->Release();
m_array[index] = newShape;
newShape->AddRef();
}
else
{
_ASSERTE(me->m_type == m_node);
stackPool[stack] = me->m_left;
stack++;
stackPool[stack] = me->m_right;
stack++;
}
}
LinkNodes();
}
dgCollisionCompoundBreakable::dgCollisionCompoundBreakable(dgWorld* const world,
dgDeserialize deserialization, void* const userData) :
dgCollisionCompound(world, deserialization, userData), m_conectivity(
world->GetAllocator(), deserialization, userData), m_detachedIslands(
world->GetAllocator())
{
dgInt32 stack;
m_collsionId = m_compoundBreakable;
m_rtti |= dgCollisionCompoundBreakable_RTTI;
deserialization(userData, &m_lru, dgInt32(sizeof(dgInt32)));
deserialization(userData, &m_lastIslandColor, dgInt32(sizeof(dgInt32)));
deserialization(userData, &m_visibilityMapIndexCount,
dgInt32(sizeof(dgInt32)));
m_visibilityMap = (dgInt8 *) m_allocator->Malloc(
dgInt32(m_visibilityMapIndexCount * sizeof(dgInt8)));
deserialization(userData, m_visibilityMap,
m_visibilityMapIndexCount * sizeof(dgInt8));
m_visibilityInderectMap = (dgInt32 *) m_allocator->Malloc(
m_visibilityMapIndexCount * dgInt32(sizeof(dgInt32)));
deserialization(userData, m_visibilityInderectMap,
size_t(m_visibilityMapIndexCount * dgInt32(sizeof(dgInt32))));
m_vertexBuffer = new (m_allocator) dgVertexBuffer(m_allocator,
deserialization, userData);
stack = 0;
for (dgDebriGraph::dgListNode* node = m_conectivity.GetFirst()->GetNext();
node != m_conectivity.GetLast(); node = node->GetNext())
{
dgCollisionConvexIntance* instance;
instance = (dgCollisionConvexIntance*) m_array[stack];
node->GetInfo().m_nodeData.m_shape = instance;
instance->AddRef();
instance->m_graphNode = node;
stack++;
}
LinkNodes();
}
dgCollisionCompoundBreakable::~dgCollisionCompoundBreakable(void)
{
if (m_visibilityMap)
{
m_allocator->Free(m_visibilityMap);
m_allocator->Free(m_visibilityInderectMap);
}
if (m_vertexBuffer)
{
m_vertexBuffer->Release();
}
}
void dgCollisionCompoundBreakable::LinkNodes()
{
dgInt32 stack;
dgNodeBase* pool[DG_COMPOUND_STACK_DEPTH];
#ifdef _DEBUG
dgInt32 count = 0;
#endif
pool[0] = m_root;
stack = 1;
while (stack)
{
dgNodeBase* node;
stack--;
node = pool[stack];
if (node->m_type == m_leaf)
{
dgCollisionConvexIntance* shape;
shape = (dgCollisionConvexIntance*) node->m_shape;
shape->m_treeNode = node;
#ifdef _DEBUG
shape->m_ordinal = count;
count++;
#endif
}
else
{
_ASSERTE(node->m_type == m_node);
// if (node->m_type == m_node) {
pool[stack] = node->m_right;
stack++;
pool[stack] = node->m_left;
stack++;
}
}
}
void dgCollisionCompoundBreakable::Serialize(dgSerialize callback,
void* const userData) const
{
dgInt32 lru;
dgCollisionCompound::Serialize(callback, userData);
m_conectivity.Serialize(callback, userData);
lru = 0;
callback(userData, &lru, dgInt32(sizeof(dgInt32)));
callback(userData, &m_lastIslandColor, dgInt32(sizeof(dgInt32)));
callback(userData, &m_visibilityMapIndexCount, dgInt32(sizeof(dgInt32)));
callback(userData, m_visibilityMap,
m_visibilityMapIndexCount * sizeof(dgInt8));
callback(userData, m_visibilityInderectMap,
size_t(m_visibilityMapIndexCount * dgInt32(sizeof(dgInt32))));
m_vertexBuffer->Serialize(callback, userData);
}
void dgCollisionCompoundBreakable::GetCollisionInfo(dgCollisionInfo* info) const
{
dgCollisionCompound::GetCollisionInfo(info);
info->m_collisionType = m_compoundBreakable;
}
dgInt32 dgCollisionCompoundBreakable::GetSegmentIndexStreamShort(
dgDebriGraph::dgListNode* const node, dgMesh::dgListNode* subMeshNode,
dgInt16* const index) const
{
dgInt32 currentIndex;
dgSubMesh* const subMesh = &subMeshNode->GetInfo();
const dgInt32* const indexes = subMesh->m_indexes;
currentIndex = 0;
if (node == m_conectivity.GetLast())
{
dgInt32 faceCount;
const dgInt8* const visbilityMap = m_visibilityMap;
const dgInt32* const visibilityInderectMap =
&m_visibilityInderectMap[subMesh->m_faceOffset];
faceCount = subMesh->m_faceCount;
for (dgInt32 i = 0; i < faceCount; i++)
{
if (visbilityMap[visibilityInderectMap[i]])
{
index[currentIndex + 0] = dgInt16(indexes[i * 3 + 0]);
index[currentIndex + 1] = dgInt16(indexes[i * 3 + 1]);
index[currentIndex + 2] = dgInt16(indexes[i * 3 + 2]);
currentIndex += 3;
}
}
}
else
{
dgInt32 indexCount;
indexCount = subMesh->m_faceCount * 3;
for (dgInt32 i = 0; i < indexCount; i++)
{
index[i] = dgInt16(indexes[i]);
}
currentIndex = indexCount;
}
return currentIndex;
}
dgInt32 dgCollisionCompoundBreakable::GetSegmentIndexStream(
dgDebriGraph::dgListNode* const node, dgMesh::dgListNode* subMeshNode,
dgInt32* const index) const
{
dgInt32 currentIndex;
dgSubMesh* const subMesh = &subMeshNode->GetInfo();
const dgInt32* const indexes = subMesh->m_indexes;
currentIndex = 0;
if (node == m_conectivity.GetLast())
{
dgInt32 faceCount;
const dgInt8* const visbilityMap = m_visibilityMap;
const dgInt32* const visibilityInderectMap =
&m_visibilityInderectMap[subMesh->m_faceOffset];
faceCount = subMesh->m_faceCount;
for (dgInt32 i = 0; i < faceCount; i++)
{
if (visbilityMap[visibilityInderectMap[i]])
{
index[currentIndex + 0] = indexes[i * 3 + 0];
index[currentIndex + 1] = indexes[i * 3 + 1];
index[currentIndex + 2] = indexes[i * 3 + 2];
currentIndex += 3;
}
}
}
else
{
dgInt32 indexCount;
indexCount = subMesh->m_faceCount * 3;
for (dgInt32 i = 0; i < indexCount; i++)
{
index[i] = indexes[i];
}
currentIndex = indexCount;
}
return currentIndex;
}
dgInt32 dgCollisionCompoundBreakable::GetSegmentsInRadius(
const dgVector& origin, dgFloat32 radius,
dgDebriGraph::dgListNode** segments, dgInt32 maxCount)
{
dgInt32 count;
dgInt32 stack;
dgNodeBase* stackPool[DG_COMPOUND_STACK_DEPTH];
dgTriplex& p = *((dgTriplex*) &origin.m_x);
dgVector p0(origin - dgVector(radius, radius, radius, dgFloat32(0.0f)));
dgVector p1(origin + dgVector(radius, radius, radius, dgFloat32(0.0f)));
count = 0;
stack = 1;
stackPool[0] = m_root;
while (stack)
{
const dgNodeBase *me;
stack--;
me = stackPool[stack];
_ASSERTE(me);
if (dgOverlapTest(me->m_p0, me->m_p1, p0, p1))
{
if (me->m_type == m_leaf)
{
dgCollisionConvexIntance* const shape =
(dgCollisionConvexIntance*) me->m_shape;
dgDebriGraph::dgListNode* const node = shape->m_graphNode;
if (node->GetInfo().m_nodeData.m_mesh->m_IsVisible)
{
dgTriplex normal;
dgTriplex contact;
m_world->ClosestPoint(p, shape, dgGetIdentityMatrix(), contact,
normal, 0);
dgVector q(contact.m_x, contact.m_y, contact.m_z, dgFloat32(0.0f));
dgVector dist(q - origin);
if ((dist % dist) < radius * radius)
{
segments[count] = node;
count++;
if (count >= maxCount)
{
break;
}
}
}
}
else
{
_ASSERTE(me->m_type == m_node);
stackPool[stack] = me->m_left;
stack++;
_ASSERTE(stack < sizeof (stackPool) / sizeof (dgNodeBase*));
stackPool[stack] = me->m_right;
stack++;
_ASSERTE(stack < sizeof (stackPool) / sizeof (dgNodeBase*));
}
}
}
//segments[0] = segments[2];
//count = 1;
return count;
}
/*
dgInt32 dgCollisionCompoundBreakable::GetDetachedPieces (dgCollision** shapes, dgInt32 maxCount)
{
}
*/
void dgCollisionCompoundBreakable::EnumerateIslands()
{
// dgInt32 islandId;
m_lastIslandColor = 0;
// m_island.RemoveAll();
for (dgDebriGraph::dgListNode* node = m_conectivity.GetFirst();
node != m_conectivity.GetLast(); node = node->GetNext())
{
node->GetInfo().m_nodeData.m_commonData.m_islandIndex = -1;
}
for (dgDebriGraph::dgListNode* node = m_conectivity.GetFirst();
node != m_conectivity.GetLast(); node = node->GetNext())
{
dgDebriNodeInfo& data = node->GetInfo().m_nodeData;
data.m_commonData.m_distanceToFixNode = DG_DYNAMINIC_ISLAND_COST;
if (data.m_commonData.m_islandIndex == -1)
{
dgInt32 count;
dgDebriGraph::dgListNode* stack[1024 * 4];
count = 1;
stack[0] = node;
node->GetInfo().m_nodeData.m_commonData.m_islandIndex = m_lastIslandColor;
while (count)
{
dgDebriGraph::dgListNode* rootNode;
count--;
rootNode = stack[count];
for (dgGraphNode<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* edgeNode =
rootNode->GetInfo().GetFirst(); edgeNode;
edgeNode = edgeNode->GetNext())
{
dgDebriGraph::dgListNode* childNode;
childNode = edgeNode->GetInfo().m_node;
if (childNode->GetInfo().m_nodeData.m_commonData.m_islandIndex
!= m_lastIslandColor)
{
childNode->GetInfo().m_nodeData.m_commonData.m_islandIndex =
m_lastIslandColor;
stack[count] = childNode;
count++;
}
}
}
m_lastIslandColor++;
}
}
m_conectivity.GetFirst()->GetInfo().m_nodeData.m_commonData.m_distanceToFixNode =
0;
}
void dgCollisionCompoundBreakable::ResetAnchor()
{
dgDebriGraph::dgListNode* fixNode;
dgGraphNode<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* nextEdge;
fixNode = m_conectivity.GetFirst();
for (dgGraphNode<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* edgeNode =
fixNode->GetInfo().GetFirst(); edgeNode; edgeNode = nextEdge)
{
nextEdge = edgeNode->GetNext();
fixNode->GetInfo().DeleteEdge(edgeNode);
}
EnumerateIslands();
}
void dgCollisionCompoundBreakable::SetAnchoredParts(dgInt32 count,
const dgMatrix* const matrixArray, const dgCollision** collisionArray)
{
dgDebriGraph::dgListNode* fixNode;
dgMatrix matrix(dgGetIdentityMatrix());
fixNode = m_conectivity.GetFirst();
for (dgDebriGraph::dgListNode* node = m_conectivity.GetFirst()->GetNext();
node != m_conectivity.GetLast(); node = node->GetNext())
{
dgGraphNode<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* edgeNode;
for (edgeNode = fixNode->GetInfo().GetFirst(); edgeNode;
edgeNode = edgeNode->GetNext())
{
if (edgeNode->GetInfo().m_node == fixNode)
{
break;
}
}
if (!edgeNode)
{
dgCollision* shape;
shape = node->GetInfo().m_nodeData.m_shape;
for (dgInt32 i = 0; i < count; i++)
{
dgInt32 contactCount;
dgFloat32 penetration[16];
dgTriplex points[16];
dgTriplex normals[16];
contactCount = m_world->Collide(shape, matrix,
(dgCollision*) collisionArray[i], matrixArray[i], points, normals,
penetration, 4, 0);
if (contactCount)
{
node->GetInfo().AddEdge(fixNode);
fixNode->GetInfo().AddEdge(node);
break;
}
}
}
}
//m_conectivity.Trace();
EnumerateIslands();
if (fixNode->GetInfo().GetCount() > 0)
{
dgInt32 leadingIndex;
dgInt32 trealingIndex;
dgDebriGraph::dgListNode* queue[1024 * 4];
leadingIndex = 1;
trealingIndex = 0;
queue[0] = fixNode;
fixNode->GetInfo().m_nodeData.m_commonData.m_distanceToFixNode = 0;
while (trealingIndex != leadingIndex)
{
dgInt32 cost;
dgDebriGraph::dgListNode* rootNode;
rootNode = queue[trealingIndex];
trealingIndex++;
if (trealingIndex >= dgInt32(sizeof(queue) / sizeof(queue[0])))
{
trealingIndex = 0;
}
cost = rootNode->GetInfo().m_nodeData.m_commonData.m_distanceToFixNode
+ 1;
for (dgGraphNode<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* edgeNode =
rootNode->GetInfo().GetFirst(); edgeNode; edgeNode =
edgeNode->GetNext())
{
dgDebriGraph::dgListNode* childNode;
childNode = edgeNode->GetInfo().m_node;
if (childNode->GetInfo().m_nodeData.m_commonData.m_distanceToFixNode
> cost)
{
childNode->GetInfo().m_nodeData.m_commonData.m_distanceToFixNode =
cost;
queue[leadingIndex] = childNode;
leadingIndex++;
if (leadingIndex >= dgInt32(sizeof(queue) / sizeof(queue[0])))
{
leadingIndex = 0;
}
_ASSERTE(leadingIndex != trealingIndex);
}
}
}
}
}
void dgCollisionCompoundBreakable::DeleteComponent(
dgDebriGraph::dgListNode* node)
{
dgMesh* mesh;
dgNodeBase* treeNode;
dgCollisionConvexIntance* shape;
mesh = node->GetInfo().m_nodeData.m_mesh;
for (dgMesh::dgListNode* meshSgement = mesh->GetFirst(); meshSgement;
meshSgement = meshSgement->GetNext())
{
dgSubMesh* const subMesh = &meshSgement->GetInfo();
if (subMesh->m_visibleFaces)
{
memset(&m_visibilityMap[subMesh->m_faceOffset], 0,
size_t(subMesh->m_faceCount));
}
}
for (dgGraphNode<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* edgeNode =
node->GetInfo().GetFirst(); edgeNode; edgeNode = edgeNode->GetNext())
{
dgDebriGraph::dgListNode* adjecentNode;
adjecentNode = edgeNode->GetInfo().m_node;
mesh = adjecentNode->GetInfo().m_nodeData.m_mesh;
if (mesh)
{
mesh->m_IsVisible = 1;
for (dgMesh::dgListNode* meshSgement = mesh->GetFirst(); meshSgement;
meshSgement = meshSgement->GetNext())
{
dgSubMesh* const subMesh = &meshSgement->GetInfo();
if (!subMesh->m_visibleFaces)
{
subMesh->m_visibleFaces = 1;
memset(&m_visibilityMap[subMesh->m_faceOffset], 1,
size_t(subMesh->m_faceCount));
}
}
}
}
for (dgGraphNode<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* edgeNode =
node->GetInfo().GetFirst(); edgeNode; edgeNode = edgeNode->GetNext())
{
dgDebriGraph::dgListNode* neighborg;
neighborg = edgeNode->GetInfo().m_node;
if (neighborg->GetInfo().m_nodeData.m_commonData.m_lru < m_lru)
{
neighborg->GetInfo().m_nodeData.m_commonData.m_lru = m_lru;
m_detachedIslands.Append(neighborg);
}
}
shape = (dgCollisionConvexIntance*) node->GetInfo().m_nodeData.m_shape;
_ASSERTE(
shape->m_graphNode->GetInfo().GetFirst() == node->GetInfo().GetFirst());
m_conectivity.DeleteNode(node);
for (dgIsland::dgListNode* islandNode = m_detachedIslands.GetFirst();
islandNode; islandNode = islandNode->GetNext())
{
if (node == islandNode->GetInfo())
{
m_detachedIslands.Remove(islandNode);
break;
}
}
treeNode = shape->m_treeNode;
((dgCollisionConvexIntance*) m_array[m_count - 1])->m_treeNode->m_id =
treeNode->m_id;
RemoveCollision(treeNode);
}
dgBody* dgCollisionCompoundBreakable::CreateComponentBody(
dgDebriGraph::dgListNode* node) const
{
_ASSERTE(0);
return NULL;
/*
dgFloat32 Ixx;
dgFloat32 Iyy;
dgFloat32 Izz;
dgFloat32 Ixx1;
dgFloat32 Iyy1;
dgFloat32 Izz1;
dgFloat32 mass;
dgBody* body;
dgCollisionConvexIntance* shape;
shape = (dgCollisionConvexIntance*) node->GetInfo().m_nodeData.m_shape;
_ASSERTE (shape->m_graphNode->GetInfo().GetFirst() == node->GetInfo().GetFirst());
body = m_world->CreateBody(shape->m_myShape);
body->SetCentreOfMass(shape->m_volume);
mass = shape->m_inertia.m_w;
Ixx = shape->m_inertia.m_x;
Iyy = shape->m_inertia.m_y;
Izz = shape->m_inertia.m_z;
_ASSERTE (0);
mass = 1.0f;
Ixx = shape->m_inertia.m_x/shape->m_inertia.m_w;
Iyy = shape->m_inertia.m_y/shape->m_inertia.m_w;
Izz = shape->m_inertia.m_z/shape->m_inertia.m_w;
Ixx1 = ClampValue (Ixx, dgFloat32 (0.001f) * mass, dgFloat32 (100.0f) * mass);
Iyy1 = ClampValue (Iyy, dgFloat32 (0.001f) * mass, dgFloat32 (100.0f) * mass);
Izz1 = ClampValue (Izz, dgFloat32 (0.001f) * mass, dgFloat32 (100.0f) * mass);
if (mass < dgFloat32 (1.0e-3f)) {
mass = DG_INFINITE_MASS * dgFloat32 (1.5f);
}
body->SetMassMatrix (mass, Ixx1, Iyy1, Izz1);
body->SetAparentMassMatrix (dgVector (Ixx, Iyy, Izz, mass));
return body;
*/
}
void dgCollisionCompoundBreakable::DeleteComponentBegin()
{
m_lru++;
m_detachedIslands.RemoveAll();
//m_conectivity.Trace();
}
void dgCollisionCompoundBreakable::DeleteComponentEnd()
{
dgInt32 baseLru;
dgIsland::dgListNode* nextIslandNode;
int xxxx = 0;
dgDebriGraph::dgListNode* xxx[1024 * 8];
m_lru++;
baseLru = m_lru;
for (dgIsland::dgListNode* islandNode = m_detachedIslands.GetFirst();
islandNode; islandNode = nextIslandNode)
{
dgDebriGraph::dgListNode* node;
nextIslandNode = islandNode->GetNext();
node = islandNode->GetInfo();
m_lru++;
if (node->GetInfo().m_nodeData.m_commonData.m_lru > baseLru)
{
m_detachedIslands.Remove(node);
}
else
{
dgInt32 count;
dgInt32 piecesCount;
dgDebriGraph::dgListNode* stack[1024 * 4];
dgDebriGraph::dgListNode* newIslandPieces[1024 * 8];
count = 1;
stack[0] = node;
piecesCount = 0;
node->GetInfo().m_nodeData.m_commonData.m_lru = m_lru;
while (count)
{
dgInt32 stackOrigin;
dgDebriGraph::dgListNode* rootNode;
count--;
rootNode = stack[count];
_ASSERTE(node->GetInfo().m_nodeData.m_commonData.m_lru == m_lru);
newIslandPieces[piecesCount] = rootNode;
piecesCount++;
if (rootNode->GetInfo().m_nodeData.m_commonData.m_distanceToFixNode
== 0)
{
piecesCount = 0;
m_detachedIslands.Remove(node);
break;
}
stackOrigin = count;
for (dgGraphNode<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* edgeNode =
rootNode->GetInfo().GetFirst(); edgeNode;
edgeNode = edgeNode->GetNext())
{
dgInt32 cost;
dgInt32 index;
dgDebriGraph::dgListNode* childNode;
childNode = edgeNode->GetInfo().m_node;
dgDebriNodeInfo& data = childNode->GetInfo().m_nodeData;
if (data.m_commonData.m_lru < baseLru)
{
data.m_commonData.m_lru = m_lru;
cost = data.m_commonData.m_distanceToFixNode;
for (index = count;
(index > stackOrigin)
&& (stack[index - 1]->GetInfo().m_nodeData.m_commonData.m_distanceToFixNode
< cost); index--)
{
stack[index] = stack[index - 1];
}
stack[index] = childNode;
count++;
}
else if (data.m_commonData.m_lru < m_lru)
{
count = 0;
piecesCount = 0;
m_detachedIslands.Remove(node);
break;
}
}
}
if (piecesCount)
{
for (dgInt32 i = 0; i < piecesCount; i++)
{
newIslandPieces[i]->GetInfo().m_nodeData.m_commonData.m_islandIndex =
m_lastIslandColor;
xxx[xxxx] = newIslandPieces[i];
xxxx++;
#ifdef _DEBUG
for (dgInt32 j = i + 1; j < piecesCount; j++)
{
_ASSERTE(newIslandPieces[i] != newIslandPieces[j]);
}
#endif
}
m_lastIslandColor++;
piecesCount = 0;
}
}
}
for (int i = 0; i < xxxx; i++)
{
DeleteComponent(xxx[i]);
}
/*
m_conectivity.GetFirst()->GetInfo().Trace();
dgInt32 count;
dgDebriGraph::dgListNode* stack[1024 * 4];
count = 1;
stack[0] = m_conectivity.GetFirst();
m_conectivity.GetFirst()->GetInfo().m_nodeData.m_commonData.m_lru = m_lru;
while (count) {
dgDebriGraph::dgListNode* rootNode;
count --;
rootNode = stack[count];
for (dgGraphNode<dgDebriNodeInfo, dgSharedNodeMesh>::dgListNode* edgeNode = rootNode->GetInfo().GetFirst(); edgeNode; edgeNode = edgeNode->GetNext()) {
dgDebriGraph::dgListNode* childNode;
childNode = edgeNode->GetInfo().m_node;
dgDebriNodeInfo& data = childNode->GetInfo().m_nodeData;
if (data.m_commonData.m_lru != m_lru) {
data.m_commonData.m_lru = m_lru;
stack[count] = childNode;
count ++;
}
}
}
for (dgDebriGraph::dgListNode* node = m_conectivity.GetFirst(); node != m_conectivity.GetLast(); node = node->GetNext()) {
// _ASSERTE (node->GetInfo().m_nodeData.m_commonData.m_lru == m_lru);
}
*/
}
| [
"[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692"
]
| [
[
[
1,
1769
]
]
]
|
6f36a4b26d428e1680eb60b11ee5cfa14a301983 | 7f783db3cfa388eb2c974635a89caa20312fcca3 | /samples/zXML/zXML/TreeObjs.h | 165c952059667b617905a3531e400b3bffb333ad | []
| no_license | altmind/com_xmlparse | 4ca094ae1af005fa042bf0bef481d994ded0e86b | da2a09c631d581065a643cbb04fbdeb00e14b43e | refs/heads/master | 2021-01-23T08:56:46.017420 | 2010-11-24T14:46:38 | 2010-11-24T14:46:38 | 1,091,119 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,448 | h | #include "grom\ValueArray.h"
#include "grom\Object.h"
enum NodeType { XMLText, XMLAttribute, XMLElement, XMLComment, XMLPI };
class XMLElementNode;
class XMLNode
{
private:
NodeType type;
public:
XMLElementNode* parent;
};
class XMLTextNode: public XMLNode
{
private:
std::string* value;
public:
XMLTextNode(std::string* value);
~XMLTextNode();
std::string* getValue();
};
class XMLCommentNode: public XMLNode
{
private:
std::string* value;
public:
XMLCommentNode(std::string* value);
~XMLCommentNode();
std::string* getValue();
};
/*
class XMLPINode: public XMLNode
{
private:
std::string* name;
std::string* value;
public:
XMLPINode(std::string* name,std::string* value);
std::string* getValue();
std::string* getName();
};*/
class XMLAttributeNode: public XMLNode
{
private:
std::string* name;
std::string* value;
public:
std::string* getName();
std::string* getValue();
XMLAttributeNode(std::string* name,std::string* value);
~XMLAttributeNode();
};
class XMLElementNode: public XMLNode
{
private:
std::string* name;
public:
std::string* getName();
XMLElementNode(std::string* name);
Sys::TValueArray<XMLNode>* children;
void addChild(XMLNode* xn);
~XMLElementNode();
};
class XMLCDataNode: public XMLNode
{
private:
std::string* value;
public:
std::string* getValue();
XMLCDataNode(std::string* value);
~XMLCDataNode();
}; | [
"[email protected]"
]
| [
[
[
1,
81
]
]
]
|
c1cf3418798924b24596d829735c45bf0617f8d5 | 352ba1bc0bdd39d2adac2997c9dad80bab7b9683 | /handle_exception.cpp | dd0482898807aeab8d1d85f5af62cfa8c480cc07 | []
| no_license | vi-k/vi-k.wxdefault | a3d337874e7af041d739c6878b73ac74d8d50b8e | e27f061ec27e36f5f204304c7a9b98692b399aab | refs/heads/master | 2021-01-10T02:13:37.829833 | 2010-07-02T01:13:52 | 2010-07-02T01:13:52 | 44,516,050 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 803 | cpp | #include "stdafx.h"
#include "handle_exception.h"
using namespace std;
#include <boost/config/warning_disable.hpp> /* против unsafe */
#include <wx/msgdlg.h>
void handle_exception(
std::exception *e,
const std::wstring &add_to_log,
const std::wstring &window_title)
{
wstringstream log_title;
wstringstream error;
if (!e)
{
log_title << L"unknown exception";
error << L"Неизвестное исключение";
}
else
{
log_title << L"std::exception";
error << e->what();
}
if (!add_to_log.empty())
log_title << L' ' << add_to_log;
error << L"\n\n(" << log_title.str() << L')';
/*TODO: Запись ошибки в лог */
wxMessageBox(error.str(), window_title, wxOK | wxICON_ERROR);
}
| [
"victor dunaev ([email protected])"
]
| [
[
[
1,
38
]
]
]
|
0eeb4bc3133a369eb9b7803b4be3fd8250feeb67 | b4d726a0321649f907923cc57323942a1e45915b | /CODE/OBJECT/collidedebrisship.cpp | 141df0a5865688e8679f39f77d65ac0c2625a756 | []
| 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 | 17,074 | 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/Object/CollideDebrisShip.cpp $
* $Revision: 1.1.1.1 $
* $Date: 2004/08/13 22:47:42 $
* $Author: Spearhawk $
*
* Routines to detect collisions and do physics, damage, etc for ships and debris
*
* $Log: collidedebrisship.cpp,v $
* Revision 1.1.1.1 2004/08/13 22:47:42 Spearhawk
* no message
*
* Revision 1.1.1.1 2004/08/13 21:37:19 Darkhill
* no message
*
* Revision 2.4 2004/03/05 09:01:57 Goober5000
* Uber pass at reducing #includes
* --Goober5000
*
* Revision 2.3 2003/11/11 02:15:42 Goober5000
* ubercommit - basically spelling and language fixes with some additional
* warnings disabled
* --Goober5000
*
* Revision 2.2 2003/04/29 01:03:22 Goober5000
* implemented the custom hitpoints mod
* --Goober5000
*
* Revision 2.1 2002/08/01 01:41:08 penguin
* The big include file move
*
* Revision 2.0 2002/06/03 04:02:27 penguin
* Warpcore CVS sync
*
* Revision 1.2 2002/05/04 04:52:22 mharris
* 1st draft at porting
*
* Revision 1.1 2002/05/02 18:03:11 mharris
* Initial checkin - converted filenames and includes to lower case
*
*
* 12 9/14/99 2:59a Andsager
* Limit amount of damage done by debris colliding with ship for SUPERCAP
*
* 11 8/31/99 11:43p Andsager
* No ship:debris damage to ship if debris' parent is ship itself
*
* 10 8/10/99 5:49p Andsager
* Fix bug - no damage collision against debris.
*
* 9 8/09/99 4:45p Andsager
* Add HUD "collision " waring when colliding with asteroids and debris.
*
* 8 7/15/99 9:20a Andsager
* FS2_DEMO initial checkin
*
* 7 6/14/99 3:21p Andsager
* Allow collisions between ship and its debris. Fix up collision pairs
* when large ship is warping out.
*
* 6 1/12/99 10:24a Andsager
* Fix asteroid-ship collision bug, with negative collision
*
* 5 10/23/98 1:11p Andsager
* Make ship sparks emit correctly from rotating structures.
*
* 4 10/20/98 1:39p Andsager
* Make so sparks follow animated ship submodels. Modify
* ship_weapon_do_hit_stuff() and ship_apply_local_damage() to add
* submodel_num. Add submodel_num to multiplayer hit packet.
*
* 3 10/16/98 1:22p Andsager
* clean up header files
*
* 2 10/07/98 10:53a Dave
* Initial checkin.
*
* 1 10/07/98 10:50a Dave
*
* 27 4/24/98 5:35p Andsager
* Fix sparks sometimes drawing not on model. If ship is sphere in
* collision, don't draw sparks. Modify ship_apply_local_damage() to take
* parameter no_spark.
*
* 26 4/02/98 6:29p Lawrance
* compile out asteroid references for demo
*
* 25 4/02/98 5:10p Mike
* Decrease damage yet more (by 3x) when an asteroid collides with a ship
* during warp out.
*
* 24 4/02/98 4:25p Andsager
* fix bug calculating max_ship_impulse
*
* 23 3/30/98 10:35a Andsager
* Attempt to optimize ship:asteroid collisions. Maybe return if time.
*
* 22 3/25/98 2:37p Andsager
* Modify maximum damage done by asteroids, depends on ship's max_vel, not
* vel when warping out.
*
* 21 3/25/98 2:15p Andsager
*
* 20 3/25/98 1:36p Mike
* Balancing of sm1-06a, Galatea mission.
*
* 19 3/23/98 11:14a Andsager
* Modified collide_asteroid_ship to calculate next possible collision
* time based on ship afterburner speed.
*
* 18 3/20/98 12:02a Mike
* Cap damage done by an asteroid on a huge ship to 1/8 ship strength if a
* large ship. If <4000 hull, can do more than 1/8.
*
* 17 3/05/98 3:12p Mike
* Fix bugs in asteroid collisions. Throw asteroids at Galataea (needs to
* be made general). Add skill level support for asteroid throwing.
*
* 16 3/04/98 11:21p Mike
* Less rotation on huge ships in death roll.
* Less damage done to huge ships when hit an asteroid at high speed.
*
* 15 3/02/98 2:58p Mike
* Make "asteroids" in debug console turn asteroids on/off.
*
* 14 2/19/98 12:46a Lawrance
* Further work on asteroids.
*
* 13 2/07/98 2:14p Mike
* Improve asteroid splitting. Add ship:asteroid collisions. Timestamp
* ship:debris collisions.
*
* 12 2/06/98 7:29p John
* Added code to cull out some future asteroid-ship collisions.
*
* 11 2/05/98 12:51a Mike
* Early asteroid stuff.
*
* 10 2/04/98 8:57p Lawrance
* remove unused variable
*
* 9 2/04/98 6:08p Lawrance
* Add a light collision sound, overlay a shield collide sound if
* applicable.
*
* 8 1/05/98 9:07p Andsager
* Changed ship_shipor_debris_hit_info struct to more meaninful names
*
* 7 1/02/98 9:08a Andsager
* Changed ship:ship and ship:debris collision detection to ignore shields
* and collide only against hull. Also, significantly reduced radius of
* sphere.
*
* 6 12/22/97 9:56p Andsager
* Implement ship:debris collisions. Generalize and move
* ship_ship_or_debris_hit struct from CollideShipShip to ObjCollide.h
*
* 5 11/03/97 11:08p Lawrance
* play correct collision sounds.
*
* 4 10/27/97 8:35a John
* code for new player warpout sequence
*
* 3 10/01/97 5:55p Lawrance
* change call to snd_play_3d() to allow for arbitrary listening position
*
* 2 9/17/97 5:12p John
* Restructured collision routines. Probably broke a lot of stuff.
*
* 1 9/17/97 2:14p John
* Initial revision
*
* $NoKeywords: $
*/
#include "object/objcollide.h"
#include "ship/ship.h"
#include "debris/debris.h"
#include "playerman/player.h"
#include "ship/shiphit.h"
#include "io/timer.h"
#include "asteroid/asteroid.h"
#include "hud/hud.h"
#include "object/object.h"
void calculate_ship_ship_collision_physics(collision_info_struct *ship_ship_hit_info);
/*
extern int Framecount;
int Debris_ship_count = 0;
*/
// Checks debris-ship collisions. pair->a is debris and pair->b is ship.
// Returns 1 if all future collisions between these can be ignored
int collide_debris_ship( obj_pair * pair )
{
float dist;
object *pdebris = pair->a;
object *pship = pair->b;
// Don't check collisions for warping out player
if ( Player->control_mode != PCM_NORMAL ) {
if ( pship == Player_obj )
return 0;
}
Assert( pdebris->type == OBJ_DEBRIS );
Assert( pship->type == OBJ_SHIP );
/* Debris_ship_count++;
if (Debris_ship_count % 100 == 0)
nprintf(("AI", "Done %i debris:ship checks in %i frames = %.2f checks/frame\n", Debris_ship_count, Framecount, (float) Debris_ship_count/Framecount));
*/
dist = vm_vec_dist( &pdebris->pos, &pship->pos );
if ( dist < pdebris->radius + pship->radius ) {
int hit;
vector hitpos;
// create and initialize ship_ship_hit_info struct
collision_info_struct debris_hit_info;
memset( &debris_hit_info, -1, sizeof(collision_info_struct) );
if ( pdebris->phys_info.mass > pship->phys_info.mass ) {
debris_hit_info.heavy = pdebris;
debris_hit_info.light = pship;
} else {
debris_hit_info.heavy = pship;
debris_hit_info.light = pdebris;
}
hit = debris_check_collision(pdebris, pship, &hitpos, &debris_hit_info );
if ( hit ) {
float ship_damage;
float debris_damage;
// do collision physics
calculate_ship_ship_collision_physics( &debris_hit_info );
if ( debris_hit_info.impulse < 0.5f )
return 0;
// calculate ship damage
ship_damage = 0.005f * debris_hit_info.impulse; // Cut collision-based damage in half.
// Decrease heavy damage by 2x.
if (ship_damage > 5.0f)
ship_damage = 5.0f + (ship_damage - 5.0f)/2.0f;
// calculate debris damage and set debris damage to greater or debris and ship
// debris damage is needed since we can really whack some small debris with afterburner and not do
// significant damage to ship but the debris goes off faster than afterburner speed.
debris_damage = debris_hit_info.impulse/pdebris->phys_info.mass; // ie, delta velocity of debris
debris_damage = (debris_damage > ship_damage) ? debris_damage : ship_damage;
// supercaps cap damage at 10-20% max hull ship damage
if (Ship_info[Ships[pship->instance].ship_info_index].flags & SIF_SUPERCAP) {
float cap_percent_damage = frand_range(0.1f, 0.2f);
ship_damage = min(ship_damage, cap_percent_damage * Ships[pship->instance].ship_initial_hull_strength);
}
// apply damage to debris
debris_hit( pdebris, pship, &hitpos, debris_damage); // speed => damage
int quadrant_num, apply_ship_damage;
// apply damage to ship unless 1) debris is from ship
// apply_ship_damage = !((pship->signature == pdebris->parent_sig) && ship_is_beginning_warpout_speedup(pship));
apply_ship_damage = !(pship->signature == pdebris->parent_sig);
if ( debris_hit_info.heavy == pship ) {
quadrant_num = get_ship_quadrant_from_global(&hitpos, pship);
if ((pship->flags & OF_NO_SHIELDS) || !ship_is_shield_up(pship, quadrant_num) ) {
quadrant_num = -1;
}
if (apply_ship_damage) {
ship_apply_local_damage(debris_hit_info.heavy, debris_hit_info.light, &hitpos, ship_damage, quadrant_num, CREATE_SPARKS, debris_hit_info.submodel_num);
}
} else {
// don't draw sparks using sphere hit position
if (apply_ship_damage) {
ship_apply_local_damage(debris_hit_info.light, debris_hit_info.heavy, &hitpos, ship_damage, MISS_SHIELDS, NO_SPARKS);
}
}
// maybe print Collision on HUD
if ( pship == Player_obj ) {
hud_start_text_flash(XSTR("Collision", 1431), 2000);
}
collide_ship_ship_do_sound(&hitpos, pship, pdebris, pship==Player_obj);
return 0;
}
} else { // Bounding spheres don't intersect, set timestamp for next collision check.
float ship_max_speed, debris_speed;
float time;
ship *shipp;
shipp = &Ships[pship->instance];
if (ship_is_beginning_warpout_speedup(pship)) {
ship_max_speed = max(ship_get_max_speed(shipp), ship_get_warp_speed(pship));
} else {
ship_max_speed = ship_get_max_speed(shipp);
}
ship_max_speed = max(ship_max_speed, 10.0f);
ship_max_speed = max(ship_max_speed, pship->phys_info.vel.xyz.z);
debris_speed = pdebris->phys_info.speed;
time = 1000.0f * (dist - pship->radius - pdebris->radius - 10.0f) / (ship_max_speed + debris_speed); // 10.0f is a safety factor
time -= 200.0f; // allow one frame slow frame at ~5 fps
if (time > 100) {
//nprintf(("AI", "Ship %s debris #%i delay time = %.1f seconds\n", Ships[pship->instance].ship_name, pdebris-Objects, time/1000.0f));
pair->next_check_time = timestamp( fl2i(time) );
} else {
pair->next_check_time = timestamp(0); // check next time
}
}
return 0;
}
// Checks asteroid-ship collisions. pair->a is asteroid and pair->b is ship.
// Returns 1 if all future collisions between these can be ignored
int collide_asteroid_ship( obj_pair * pair )
{
#ifndef FS2_DEMO
if (!Asteroids_enabled)
return 0;
float dist;
object *pasteroid = pair->a;
object *pship = pair->b;
// Don't check collisions for warping out player
if ( Player->control_mode != PCM_NORMAL ) {
if ( pship == Player_obj ) return 0;
}
if (pasteroid->hull_strength < 0.0f)
return 0;
Assert( pasteroid->type == OBJ_ASTEROID );
Assert( pship->type == OBJ_SHIP );
dist = vm_vec_dist( &pasteroid->pos, &pship->pos );
if ( dist < pasteroid->radius + pship->radius ) {
int hit;
vector hitpos;
// create and initialize ship_ship_hit_info struct
collision_info_struct asteroid_hit_info;
memset( &asteroid_hit_info, -1, sizeof(collision_info_struct) );
if ( pasteroid->phys_info.mass > pship->phys_info.mass ) {
asteroid_hit_info.heavy = pasteroid;
asteroid_hit_info.light = pship;
} else {
asteroid_hit_info.heavy = pship;
asteroid_hit_info.light = pasteroid;
}
hit = asteroid_check_collision(pasteroid, pship, &hitpos, &asteroid_hit_info );
if ( hit ) {
float ship_damage;
float asteroid_damage;
vector asteroid_vel = pasteroid->phys_info.vel;
// do collision physics
calculate_ship_ship_collision_physics( &asteroid_hit_info );
if ( asteroid_hit_info.impulse < 0.5f )
return 0;
// limit damage from impulse by making max impulse (for damage) 2*m*v_max_relative
float max_ship_impulse = (2.0f*pship->phys_info.max_vel.xyz.z+vm_vec_mag_quick(&asteroid_vel)) *
(pship->phys_info.mass*pasteroid->phys_info.mass) / (pship->phys_info.mass + pasteroid->phys_info.mass);
if (asteroid_hit_info.impulse > max_ship_impulse) {
ship_damage = 0.001f * max_ship_impulse;
} else {
ship_damage = 0.001f * asteroid_hit_info.impulse; // Cut collision-based damage in half.
}
// Decrease heavy damage by 2x.
if (ship_damage > 5.0f)
ship_damage = 5.0f + (ship_damage - 5.0f)/2.0f;
if ((ship_damage > 500.0f) && (ship_damage > Ships[pship->instance].ship_initial_hull_strength/8.0f)) {
ship_damage = Ships[pship->instance].ship_initial_hull_strength/8.0f;
nprintf(("AI", "Pinning damage to %s from asteroid at %7.3f (%7.3f percent)\n", Ships[pship->instance].ship_name, ship_damage, 100.0f * ship_damage/Ships[pship->instance].ship_initial_hull_strength));
}
// Decrease damage during warp out because it's annoying when your escoree dies during warp out.
if (Ai_info[Ships[pship->instance].ai_index].mode == AIM_WARP_OUT)
ship_damage /= 3.0f;
//nprintf(("AI", "Asteroid damage on %s = %7.3f (%6.2f percent)\n", Ships[pship->instance].ship_name, ship_damage, 100.0f * ship_damage/Ships[pship->instance].ship_initial_hull_strength));
// calculate asteroid damage and set asteroid damage to greater or asteroid and ship
// asteroid damage is needed since we can really whack some small asteroid with afterburner and not do
// significant damage to ship but the asteroid goes off faster than afterburner speed.
asteroid_damage = asteroid_hit_info.impulse/pasteroid->phys_info.mass; // ie, delta velocity of asteroid
asteroid_damage = (asteroid_damage > ship_damage) ? asteroid_damage : ship_damage;
// apply damage to asteroid
asteroid_hit( pasteroid, pship, &hitpos, asteroid_damage); // speed => damage
//extern fix Missiontime;
int quadrant_num;
if ( asteroid_hit_info.heavy == pship ) {
quadrant_num = get_ship_quadrant_from_global(&hitpos, pship);
if ((pship->flags & OF_NO_SHIELDS) || !ship_is_shield_up(pship, quadrant_num) ) {
quadrant_num = -1;
}
ship_apply_local_damage(asteroid_hit_info.heavy, asteroid_hit_info.light, &hitpos, ship_damage, quadrant_num, CREATE_SPARKS, asteroid_hit_info.submodel_num);
//if (asteroid_hit_info.heavy->type == OBJ_SHIP) {
// nprintf(("AI", "Time = %7.3f, asteroid #%i applying %7.3f damage to ship %s\n", f2fl(Missiontime), pasteroid-Objects, ship_damage, Ships[asteroid_hit_info.heavy->instance].ship_name));
//}
} else {
// dont draw sparks (using sphere hitpos)
ship_apply_local_damage(asteroid_hit_info.light, asteroid_hit_info.heavy, &hitpos, ship_damage, MISS_SHIELDS, NO_SPARKS);
//if (asteroid_hit_info.light->type == OBJ_SHIP) {
// nprintf(("AI", "Time = %7.3f, asteroid #%i applying %7.3f damage to ship %s\n", f2fl(Missiontime), pasteroid-Objects, ship_damage, Ships[asteroid_hit_info.light->instance].ship_name));
//}
}
// maybe print Collision on HUD
if ( pship == Player_obj ) {
hud_start_text_flash(XSTR("Collision", 1431), 2000);
}
collide_ship_ship_do_sound(&hitpos, pship, pasteroid, pship==Player_obj);
return 0;
}
return 0;
} else {
// estimate earliest time at which pair can hit
float asteroid_max_speed, ship_max_speed, time;
ship *shipp = &Ships[pship->instance];
asteroid_max_speed = vm_vec_mag(&pasteroid->phys_info.vel); // Asteroid... vel gets reset, not max vel.z
asteroid_max_speed = max(asteroid_max_speed, 10.0f);
if (ship_is_beginning_warpout_speedup(pship)) {
ship_max_speed = max(ship_get_max_speed(shipp), ship_get_warp_speed(pship));
} else {
ship_max_speed = ship_get_max_speed(shipp);
}
ship_max_speed = max(ship_max_speed, 10.0f);
ship_max_speed = max(ship_max_speed, pship->phys_info.vel.xyz.z);
time = 1000.0f * (dist - pship->radius - pasteroid->radius - 10.0f) / (asteroid_max_speed + ship_max_speed); // 10.0f is a safety factor
time -= 200.0f; // allow one frame slow frame at ~5 fps
if (time > 100) {
pair->next_check_time = timestamp( fl2i(time) );
} else {
pair->next_check_time = timestamp(0); // check next time
}
return 0;
}
#else
return 0; // no asteroids in demo version
#endif
}
| [
"[email protected]"
]
| [
[
[
1,
481
]
]
]
|
fefe1dd173179d383cc42868374ad084400d995b | ed1a161411b6850d6113b640b5b8c776e7cb0f2c | /TiGLiCS/src/Engine/Engine.h | 4c467a75a3799c41e5e3b2d7ec8977e91b8c1222 | []
| no_license | weimingtom/tiglics | 643d19a616dcae3e474471e3dea868f6631463ba | 450346a441ee6c538e39968311ab60eb9e572746 | refs/heads/master | 2021-01-10T01:36:31.607727 | 2008-08-13T03:35:45 | 2008-08-13T03:35:45 | 48,733,131 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 4,391 | h | #pragma once
#include "Base/Base.h"
#include "Base/Configure.h"
#include "Manager/SoundManager.h"
#include "Manager/RenderManager.h"
#include "Manager/PageManager.h"
#include <ctime>
#include <vector>
#include <mmsystem.h> // winmm.lib をリンクするのを忘れずに
namespace TiGLiCS{
/**
@brief タスクシステム
@author my04337
すべての中心となるクラス。各マネージャ類へのアクセスは<br>
ほぼここから可能である。
*/
class CEngine{ //シングルトンクラス
Selene::ICore *pCore; //コア
Selene::IGraphicCard *pGraphicCard; //グラフィックカード情報
Selene::Renderer::IRender *pRender; //レンダー
Selene::File::IFileManager *pFileMgr; //ファイルマネージャ
Selene::Peripheral::IMouse *pMouse; //マウスデバイス
Selene::Peripheral::IKeyboard *pKeyboard; //キーボードデバイス
Selene::Renderer::CTextureConfig Conf; //テクスチャコンフィグ
bool bShowLog;
Selene::Math::Point2DI ScreenSize;//スクリーンサイズ
Sint32 FrameRate;
//デバッグ用変数
void Exec(void);//処理実行
void _Release(void);//解放処理
///コンストラクタ。シングルトン用にプライベート
CEngine(){
//まずはNULLで初期化
pCore=NULL;
pGraphicCard=NULL;
pRender=NULL;
pMouse=NULL;
pKeyboard=NULL;
bShowLog=false;
}
//デストラクタ
~CEngine(){
}
static CEngine * Instance;//自分自身のインスタンス(シングルトン用)
public:
static CEngine * GetInstance(){
return Instance;
}
static void Release(){
Instance->_Release();
delete Instance;
}
/*
@brief 初期化関数
@author my04337
@param Title [in] タイトル
@param FrameRate [in] フレームレート指定
@param isDrawDebugTitle [in] デバッグ用タイトルを表示するか
@param ScreenWidth [in] スクリーン幅
@param ScreenHeight [in] スクリーン高さ
@param isFullScreen [in] フルスクリーンにするか
@param RootPath [in] ルートディレクトリのアドレス
@param CurrentPath [in] カレントディレクトリのアドレス
@param isBenchMode [in] ベンチマークモードにするか
@return 初期化に成功したか
*/
bool Init(const char * Title,Selene::eFrameRate FrameRate,bool isDrawDebugTitle,
Sint32 ScreenWidth,Sint32 ScreenHeight,bool isFullScreen,const char * RootPath,
const char * CurrentPath,bool isBenchMode=false);
/**
@brief 実行関数
@author my04337
@retval true タスクが終了していない
@retval false タスクが終了した
この関数をループさせることで、毎フレーム各処理を行わせる。<br>
実行の際には、以下のように記述する<br>
@code
...
WinMain(){
...//初期化等
while(pEngine->Run()){}
...//終了処理
return ...;
}
@endcode
*/
inline Bool Run(){
Exec();
return pCore->Run();
}
inline bool GetShowLog(){
return bShowLog;
}
inline void SetShowLog(bool state){
bShowLog=state;
}
//スクリーンサイズとフレームレート
Selene::Math::Point2DI GetScreenSize(){return ScreenSize;}
Sint32 GetFrameRate(){return FrameRate;}
inline void End(){pCore->Exit();}//終了させる。
///TiGLICSのバージョン取得
inline const char* GetVerStr(){return TIGLICS_VERSION;}
//各種オブジェクトへのポインタの取得
///Selene::ICoreを取得
inline Selene::ICore* GetICore(){return pCore;}
///Selene::IGraphicを取得
inline Selene::IGraphicCard* GetIGraphicCard(){return pGraphicCard;}
///Selene::IRenderを取得
inline Selene::Renderer::IRender* GetIRender(){return pRender;}
///テクスチャ設定を取得
inline Selene::Renderer::CTextureConfig *GetCTextureConfig(){return &Conf;}
///Selene::File::IFileManagerを取得
inline Selene::File::IFileManager* GetIFileManager(){return pFileMgr;}
///Selene::Peripheral::IMouseを取得
inline Selene::Peripheral::IMouse* GetIMouse(){return pMouse;}
///Selene::Peripheral::IKeyboardを取得
inline Selene::Peripheral::IKeyboard* GetIKeyboard(){return pKeyboard;}
};
}; | [
"my04337@d15ed888-2954-0410-b748-710a6ca92709"
]
| [
[
[
1,
135
]
]
]
|
ff0ca1cd37160824beadb55ff4bb159e2ae9fdc8 | 16ba8e891c084c827148d9c6cd6981a29772cb29 | /KaraokeMachine/trunk/tools/KMPackageBuilder/src/DialogImagePackageEdit.cpp | 3b2558b423d207ae244d496996ef496db4b01ce5 | []
| no_license | RangelReale/KaraokeMachine | efa1d5d23d0759762f3d6f590e114396eefdb28a | abd3b05d7af8ebe8ace15e888845f1ca8c5e481f | refs/heads/master | 2023-06-29T20:32:56.869393 | 2008-09-16T18:09:40 | 2008-09-16T18:09:40 | 37,156,415 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,080 | cpp | #include <wx/statline.h>
#include <wx/valgen.h>
#include <wx/thread.h>
#include "DialogImagePackageEdit.h"
BEGIN_EVENT_TABLE(KMPB_ImagePackageEditDialog, wxDialog)
END_EVENT_TABLE()
KMPB_ImagePackageEditDialog::KMPB_ImagePackageEditDialog( wxWindow* parent,
wxWindowID id,
const wxString& caption,
const wxPoint& pos,
const wxSize& size,
long style) :
wxDialog(parent, id, caption, pos, size, style)
{
SetExtraStyle(wxWS_EX_VALIDATE_RECURSIVELY);
Init();
CreateControls();
}
KMPB_ImagePackageEditDialog::~KMPB_ImagePackageEditDialog()
{
}
void KMPB_ImagePackageEditDialog::Init()
{
title_=wxEmptyString;
author_=wxEmptyString;
description_=wxEmptyString;
}
void KMPB_ImagePackageEditDialog::Load(KMImagePackage *package)
{
title_=wxString(package->GetTitle().c_str(), wxConvUTF8);
author_=wxString(package->GetAuthor().c_str(), wxConvUTF8);
description_=wxString(package->GetDescription().c_str(), wxConvUTF8);
}
void KMPB_ImagePackageEditDialog::Save(KMImagePackage *package)
{
package->SetTitle(std::string(title_.mb_str(wxConvUTF8)));
package->SetAuthor(std::string(author_.mb_str(wxConvUTF8)));
package->SetDescription(std::string(description_.mb_str(wxConvUTF8)));
}
void KMPB_ImagePackageEditDialog::CreateControls()
{
wxBoxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
wxBoxSizer *boxsizer = new wxBoxSizer(wxVERTICAL);
topsizer->Add(boxsizer, 1, wxEXPAND|wxALL, 3);
// BODY
wxBoxSizer *bodysizer = new wxBoxSizer(wxHORIZONTAL);
boxsizer->Add(bodysizer, 1, wxEXPAND|wxALL, 3);
// FIELDS
wxBoxSizer *fieldssizer = new wxBoxSizer(wxVERTICAL);
bodysizer->Add(fieldssizer, 1, wxEXPAND|wxALL, 3);
// Title
fieldssizer->Add(new wxStaticText(this, wxID_STATIC, wxT("&Title:"), wxDefaultPosition, wxDefaultSize, 0),
0, wxALIGN_LEFT|wxALL, 3);
fieldssizer->Add(new wxTextCtrl(this, ID_TITLE, wxEmptyString, wxDefaultPosition, wxSize(200, -1), 0),
0, wxGROW|wxALL, 3);
// Author
fieldssizer->Add(new wxStaticText(this, wxID_STATIC, wxT("&Author:"), wxDefaultPosition, wxDefaultSize, 0),
0, wxALIGN_LEFT|wxALL, 3);
fieldssizer->Add(new wxTextCtrl(this, ID_AUTHOR, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0),
0, wxGROW|wxALL, 3);
// Description
fieldssizer->Add(new wxStaticText(this, wxID_STATIC, wxT("&Description:"), wxDefaultPosition, wxDefaultSize, 0),
0, wxALIGN_LEFT|wxALL, 3);
fieldssizer->Add(new wxTextCtrl(this, ID_DESCRIPTION, wxEmptyString, wxDefaultPosition, wxSize(200, 200), wxTE_MULTILINE|wxTE_PROCESS_ENTER),
1, wxGROW|wxALL, 3);
// divider line
wxStaticLine *line = new wxStaticLine(this, wxID_STATIC, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL);
boxsizer->Add(line, 0, wxGROW|wxALL, 3);
wxBoxSizer *buttonsizer = new wxBoxSizer(wxHORIZONTAL);
boxsizer->Add(buttonsizer, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 3);
// ok button
buttonsizer->Add(new wxButton ( this, wxID_OK, wxT("&OK"), wxDefaultPosition, wxDefaultSize, 0 ),
0, wxALIGN_CENTER_VERTICAL|wxALL, 3);
// cancel button
buttonsizer->Add(new wxButton ( this, wxID_CANCEL, wxT("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 ),
0, wxALIGN_CENTER_VERTICAL|wxALL, 3);
// validators
FindWindow(ID_TITLE)->SetValidator(wxTextValidator(wxFILTER_NONE, &title_));
FindWindow(ID_AUTHOR)->SetValidator(wxTextValidator(wxFILTER_NONE, &author_));
FindWindow(ID_DESCRIPTION)->SetValidator(wxTextValidator(wxFILTER_NONE, &description_));
SetSizer(topsizer);
topsizer->SetSizeHints(this);
CentreOnScreen();
}
bool KMPB_ImagePackageEditDialog::TransferDataToWindow()
{
if (!wxDialog::TransferDataToWindow()) return false;
return true;
}
bool KMPB_ImagePackageEditDialog::TransferDataFromWindow()
{
if (!wxDialog::TransferDataFromWindow()) return false;
return true;
}
| [
"hitnrun@6277c508-b546-0410-9041-f9c9960c1249"
]
| [
[
[
1,
124
]
]
]
|
569afb405f9249b187cdbdfd51c2e84ce5880d07 | 58496be10ead81e2531e995f7d66017ffdfc6897 | /Sources/System/Nix/DllHolderImpl.h | 992a36a80c0a46d2d62cafc1c3deae1f12f35bde | []
| no_license | Diego160289/cross-fw | ba36fc6c3e3402b2fff940342315596e0365d9dd | 532286667b0fd05c9b7f990945f42279bac74543 | refs/heads/master | 2021-01-10T19:23:43.622578 | 2011-01-09T14:54:12 | 2011-01-09T14:54:12 | 38,457,864 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 697 | h | //============================================================================
// Date : 22.12.2010
// Author : Tkachenko Dmitry
// Copyright : (c) Tkachenko Dmitry ([email protected])
//============================================================================
#ifndef __DLLHOLDERIMPL_H__
#define __DLLHOLDERIMPL_H__
#include <pthread.h>
#include <dlfcn.h>
#include "DllHolder.h"
namespace System
{
class DllHolder::DllHolderImpl
: NoCopyable
{
public:
DllHolderImpl(const char *libName);
~DllHolderImpl();
void* GetProc(const char *procName);
private:
void *Dll;
};
}
#endif // !__DLLHOLDERIMPL_H__
| [
"TkachenkoDmitryV@d548627a-540d-11de-936b-e9512c4d2277"
]
| [
[
[
1,
32
]
]
]
|
096d3251e652783828c9630bef67e11d71b9f6a2 | c1c3866586c56ec921cd8c9a690e88ac471adfc8 | /Practise_2005/WorldEditor/AssemblyInfo.cpp | 1dd0bf7854238c8f7ca7a24250f87427c5f68f26 | []
| no_license | rtmpnewbie/lai3d | 0802dbb5ebe67be2b28d9e8a4d1cc83b4f36b14f | b44c9edfb81fde2b40e180a651793fec7d0e617d | refs/heads/master | 2021-01-10T04:29:07.463289 | 2011-03-22T17:51:24 | 2011-03-22T17:51:24 | 36,842,700 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,292 | cpp | #include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// 程序集的常规信息通过下列属性集
// 控制。更改这些属性值可修改
// 与程序集关联的信息。
//
[assembly:AssemblyTitleAttribute("WorldEditor")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("征途网络")];
[assembly:AssemblyProductAttribute("WorldEditor")];
[assembly:AssemblyCopyrightAttribute("Copyright (c) 征途网络 2008")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
//
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 您可以指定所有值,也可使用“修订号”和“内部版本号”的默认值,
// 方法是按如下所示使用“*”:
[assembly:AssemblyVersionAttribute("1.0.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
| [
"laiyanlin@27d9c402-1b7e-11de-9433-ad2e3fad96c5"
]
| [
[
[
1,
40
]
]
]
|
86a31e8273b78d893683b34581566cc7afaaad49 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEFoundation/SEDistance/SEDistLine3Triangle3.h | d3be81933a0a3f317ff046f59c8b887ace757868 | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,444 | h | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// 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. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#ifndef Swing_DistLine3Triangle3_H
#define Swing_DistLine3Triangle3_H
#include "SEFoundationLIB.h"
#include "SEDistance.h"
#include "SELine3.h"
#include "SETriangle3.h"
namespace Swing
{
//----------------------------------------------------------------------------
// Description:
// Author:Sun Che
// Date:20090114
//----------------------------------------------------------------------------
class SE_FOUNDATION_API SEDistLine3Triangle3f : public SEDistance<float,
SEVector3f>
{
public:
SEDistLine3Triangle3f(const SELine3f& rLine, const SETriangle3f&
rTriangle);
// 对象访问.
const SELine3f& GetLine(void) const;
const SETriangle3f& GetTriangle(void) const;
// static distance查询.
virtual float Get(void);
virtual float GetSquared(void);
// 用于dynamic distance查询的convex function计算.
virtual float Get(float fT, const SEVector3f& rVelocity0,
const SEVector3f& rVelocity1);
virtual float GetSquared(float fT, const SEVector3f& rVelocity0,
const SEVector3f& rVelocity1);
// 最近点相关信息.
float GetLineParameter(void) const;
float GetTriangleBary(int i) const;
private:
const SELine3f* m_pLine;
const SETriangle3f* m_pTriangle;
// 最近点相关信息.
float m_fLineParameter; // closest0 = line.origin+param*line.direction
float m_afTriangleBary[3]; // closest1 = sum_{i=0}^2 bary[i]*tri.vertex[i]
};
}
#endif
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
73
]
]
]
|
fa76bec11acafdbc9b1bbfb83cc0fa2b372b3a62 | 713659538c3e4d0d332d43002b7ef96400ed6b53 | /src/game/server/gamemodes/kvach.hpp | faa55595953519b853c259cec6cf8594a70efc8d | [
"LicenseRef-scancode-other-permissive",
"Zlib",
"BSD-3-Clause"
]
| permissive | Berzzzebub/TeeFork | 449b31ce836a47476efa15f32930a28908a56b37 | 53142119f62af52379b7a5e7344f38b1b2e56cf7 | refs/heads/master | 2016-09-06T08:21:23.745520 | 2010-12-12T09:37:52 | 2010-12-12T09:37:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,293 | hpp | /* copyright (c) 2007 magnus auvinen, see licence.txt for more info */
#include <game/server/gamecontroller.hpp>
// you can subclass GAMECONTROLLER_CTF, GAMECONTROLLER_TDM etc if you want
// todo a modification with their base as well.
class GAMECONTROLLER_KVACH : public GAMECONTROLLER
{
public:
int kvacher_client_id;
int leader_client_id;
int last_kvacher_client_id;
int invinsible_tick;
int point_counter;
int hook_point_counter;
GAMECONTROLLER_KVACH();
virtual void tick();
virtual bool on_entity(int index, vec2 pos);
virtual void on_character_spawn(class CHARACTER *chr);
virtual void on_player_info_change(class PLAYER *p);
virtual int on_character_death(class CHARACTER *victim, class PLAYER *killer, int weapon);
virtual void endround();
// add more virtual functions here if you wish
void explosion_calculate(vec2 p, int owner, int weapon, bool bnodamage);
void damage_calculate(class CHARACTER *chrTo, int dmg, class CHARACTER *chrFrom, int weapon);
void choose_new_kvach();
void update_score_leader();
void update_equipment();
bool timer_going(int timerTick, int timerLife);
void update_colors();
void create_explosion(vec2 p, int owner, int weapon, bool bnodamage);
void character_tick(CHARACTER* character);
};
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
0a4a3ed0eafb13b1414eec2d35d698432c383292 | 06965c8bfe9274f24b961eaad95062051aaec1b2 | /Unit.h | a9908a96437ab810efe3cee0770f34b2e40fc891 | []
| no_license | vinaybalhara/BaczekKPAI | 902f2a27c1f565e9bae11ace82125052a3364306 | 9550e0c5abc260efc47355031aebd7d1831dfb0c | refs/heads/master | 2021-01-16T19:14:52.776176 | 2010-12-07T15:43:48 | 2010-12-07T15:43:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,550 | h | #pragma once
// a thin wrapper on friendly unitids
#include <boost/shared_ptr.hpp>
#include "LegacyCpp/UnitDef.h"
#include "UnitAI.h"
class BaczekKPAI;
class Unit
{
protected:
void Init();
public:
int id;
BaczekKPAI *global_ai;
boost::shared_ptr<UnitAI> ai;
// unit status flags
bool is_complete;
bool is_killed;
// unit type flags
bool is_constructor;
bool is_base;
bool is_expansion;
bool is_spam;
// unit state flags
bool is_producing;
// last idle state
int last_idle_frame;
// last attacked
int last_attacked_frame;
Unit(BaczekKPAI* g_ai, int id) : global_ai(g_ai), id(id), is_complete(false), is_killed(false),
is_producing(false)
{ Init(); }
~Unit() {}
void complete() { is_complete = true; }
void destroy(int attacker) { is_killed = true; if (ai) ai->OwnerKilled(); }
// FIXME move to data file
static bool IsConstructor(const UnitDef* ud) { return ud->name == "assembler" || ud->name == "gateway" || ud->name == "trojan"; }
static bool IsBase(const UnitDef* ud) { return ud->name == "kernel" || ud->name == "hole" || ud->name == "carrier"; }
static bool IsExpansion(const UnitDef* ud) { return ud->name == "window" || ud->name == "socket" || ud->name == "port"; }
static bool IsSuperWeapon(const UnitDef* ud) { return ud->name == "terminal" || ud->name == "firewall" || ud->name == "obelisk"; }
static bool IsSpam(const UnitDef* ud) { return ud->name == "bit" || ud->name == "bug" || ud->name == "exploit" || ud->name == "packet"; }
};
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
6
],
[
8,
57
]
],
[
[
7,
7
]
]
]
|
bf593b587471bb8e53c538b70064ec5796047df2 | b22c254d7670522ec2caa61c998f8741b1da9388 | /common/ZoneActor.h | cdb25b969fa2f8060a218918203195d1767b2410 | []
| 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,800 | 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_ZoneActor_h)
#define __LbaNetModel_1_ZoneActor_h
#include "Actor.h"
#include <set>
/***********************************************************************
* Module: ZoneActor.h
* Author: vivien
* Modified: lundi 27 juillet 2009 14:53:50
* Purpose: Declaration of the class Actor
*********************************************************************/
class ZoneActor : public Actor
{
public:
//! constructor
ZoneActor(float zoneSizeX, float zoneSizeY, float zoneSizeZ);
//! destructor
virtual ~ZoneActor();
//! check zone activation
virtual int ActivateZone(float PlayerPosX, float PlayerPosY, float PlayerPosZ, float PlayerRotation,
MainPlayerHandler * _mph, bool DirectActivation=true);
//! render editor part
virtual void RenderEditor();
//! accessors
float GetZoneX()
{return _zoneSizeX;}
float GetZoneY()
{return _zoneSizeY;}
float GetZoneZ()
{return _zoneSizeZ;}
void SetZoneX(float zx)
{_zoneSizeX = zx;}
void SetZoneY(float zy)
{_zoneSizeY = zy;}
void SetZoneZ(float zz)
{_zoneSizeZ = zz;}
//! check if the actor need desactivation
virtual bool NeedDesactivation(){return true;}
// actor avtivate other actors
virtual void ActorActivateActor(Actor * act);
//! check if the actor is activated
//! activating group is the group that the actiavating agent belows:
//! 0 -> everybody; 1 -> player; 2 -> other actors
virtual bool IsActivated(int activatinggroup);
protected:
// used to get the zone center - depend of the actor type
virtual float GetZoneCenterX(){return _posX;}
virtual float GetZoneCenterY(){return _posY;}
virtual float GetZoneCenterZ(){return _posZ;}
private:
float _zoneSizeX;
float _zoneSizeY;
float _zoneSizeZ;
std::set<long> _activatedactors;
};
#endif | [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
]
| [
[
[
1,
95
]
]
]
|
ff21cbab42f5c0dd29e56627cfd1acb51ba8c509 | 080941f107281f93618c30a7aa8bec9e8e2d8587 | /src/libloader/refinery_LibLoader.cpp | 8ae25a75042c985ccb8818cb7684de184d9f3c90 | [
"MIT"
]
| permissive | scoopr/COLLADA_Refinery | 6d40ee1497b9f33818ec1e71677c3d0a0bf8ced4 | 3a5ad1a81e0359f9025953e38e425bc10b5bf6c5 | refs/heads/master | 2021-01-22T01:55:14.642769 | 2009-03-10T21:31:04 | 2009-03-10T21:31:04 | 194,828 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,112 | cpp | /*
The MIT License
Copyright 2006 Sony Computer Entertainment Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "refinery_LibLoader.h"
#include "libloader.h"
#include "conditioner.h"
JNIEXPORT void JNICALL Java_refinery_LibLoader_init
(JNIEnv *env, jobject obj )
{
//printf( "in Init\n" );
LibLoader::init( env, obj );
}
JNIEXPORT jint JNICALL Java_refinery_LibLoader_getNumAvailableConditioners
(JNIEnv *, jobject )
{
return LibLoader::getNumAvailableConditioners();
}
JNIEXPORT jobject JNICALL Java_refinery_LibLoader_getConditioner
(JNIEnv *env, jobject obj, jint idx)
{
const ConditionerCreator *cc = LibLoader::getAvailableConditioner( idx );
if ( cc == NULL )
return NULL;
jstring name = env->NewStringUTF( cc->getBaseName().c_str() );
jstring desc = env->NewStringUTF( cc->getDescription().c_str() );
jstring cat = env->NewStringUTF( cc->getCategory().c_str() );
jmethodID mid = env->GetMethodID( env->GetObjectClass(obj),
"newConditionerBase",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lrefinery/ConditionerTemplate;");
if (mid == 0) {
printf("newConditionerBase not found !!\n");
return NULL;
}
jvalue args[3];
args[0].l = name;
args[1].l = desc;
args[2].l = cat;
return env->CallObjectMethodA( obj, mid, args );
}
JNIEXPORT jboolean JNICALL Java_refinery_LibLoader_loadConditioner
(JNIEnv *env, jobject obj, jstring baseName, jstring name, jobject cw )
{
//Look for conditioner
const char *nm = env->GetStringUTFChars( baseName, 0 );
std::string nmStr = std::string( nm );
env->ReleaseStringUTFChars( baseName, nm );
const ConditionerCreator *cc = LibLoader::getAvailableConditioner( nmStr );
if ( cc == NULL )
{
return false;
}
//create conditioner
Conditioner *cond = cc->create();
//add conditioner
nm = env->GetStringUTFChars( name, 0 );
nmStr = std::string( nm );
env->ReleaseStringUTFChars( name, nm );
cond->setName( nmStr );
if ( !LibLoader::addConditioner( nmStr, cond ) )
{
delete cond;
return false;
}
//set up conditioner
cond->init();
//set up ConditionerWrapper
//set number of inputs and outputs
jclass cls = env->GetObjectClass( cw );
jmethodID mid = env->GetMethodID( cls, "init", "(IIZ[Ljava/lang/String;[Z)V");
if (mid == 0) {
printf("init not found !!\n");
return false;
}
unsigned int numOuts = cond->getNumOutputs();
jboolean *ba = new jboolean[numOuts*2];
jbooleanArray barray= env->NewBooleanArray( numOuts *2 );
jobjectArray oa = env->NewObjectArray( numOuts, env->GetObjectClass( name ), env->NewStringUTF( "" ) );
for ( unsigned int i = 0; i < numOuts; i++ )
{
env->SetObjectArrayElement( oa, i, env->NewStringUTF( cond->getOutput(i).c_str() ) );
ba[i*2 ] = cond->isOutputLinked(i);
ba[i*2 +1] = cond->isOutputEditable(i);
}
env->SetBooleanArrayRegion( barray, 0, numOuts*2, ba );
delete[] ba;
jvalue args[5];
args[0].i = cond->getNumInputs();
args[1].i = numOuts;
args[2].z = cond->hasVariableNumInputs();
args[3].l = oa;
args[4].l = barray;
env->CallVoidMethodA( cw, mid, args );
return true;
}
JNIEXPORT jboolean JNICALL Java_refinery_LibLoader_removeConditioner
(JNIEnv *env, jobject, jstring name)
{
const char *nm = env->GetStringUTFChars( name, 0 );
std::string nmStr = std::string( nm );
env->ReleaseStringUTFChars( name, nm );
return LibLoader::removeConditioner( nmStr );
}
JNIEXPORT jboolean JNICALL Java_refinery_LibLoader_loadBoolOptions
(JNIEnv *env, jobject obj, jstring name, jobject cw )
{
//add other options
jclass cls = env->GetObjectClass( cw );
jmethodID mid = env->GetMethodID( cls, "addBoolOption",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V");
if (mid == 0) {
printf("addBoolOption not found !!\n");
return false;
}
const char *nm = env->GetStringUTFChars( name, 0 );
std::string nmStr = std::string( nm );
env->ReleaseStringUTFChars( name, nm );
Conditioner *cond = LibLoader::getConditioner( nmStr );
if ( cond == NULL )
{
printf("unable to find Conditioner named %s!!\n", nmStr.c_str() );
return false;
}
Conditioner::BoolOptionMap::const_iterator bIter = cond->getBoolOptionsMap().begin();
while ( bIter != cond->getBoolOptionsMap().end() )
{
jstring name = env->NewStringUTF( bIter->first.c_str() );
jstring fName = env->NewStringUTF( bIter->second.fullName.c_str() );
jstring desc = env->NewStringUTF( bIter->second.description.c_str() );
jvalue bArgs[4];
bArgs[0].l = name;
bArgs[1].l = fName;
bArgs[2].l = desc;
bArgs[3].z = bIter->second.value;
env->CallVoidMethodA( cw, mid, bArgs );
++bIter;
}
return true;
}
JNIEXPORT jboolean JNICALL Java_refinery_LibLoader_loadStringOptions
(JNIEnv *env, jobject obj, jstring name, jobject cw )
{
jclass cls = env->GetObjectClass( cw );
jmethodID mid = env->GetMethodID( cls, "addStringOption",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V");
if (mid == 0) {
printf("addStringOption not found !!\n");
return false;
}
const char *nm = env->GetStringUTFChars( name, 0 );
std::string nmStr = std::string( nm );
env->ReleaseStringUTFChars( name, nm );
Conditioner *cond = LibLoader::getConditioner( nmStr );
if ( cond == NULL )
{
printf("unable to find Conditioner named %s!!\n", nmStr.c_str() );
return false;
}
Conditioner::StringOptionMap::const_iterator sIter = cond->getStringOptionsMap().begin();
while ( sIter != cond->getStringOptionsMap().end() )
{
jstring name = env->NewStringUTF( sIter->first.c_str() );
jstring fName = env->NewStringUTF( sIter->second.fullName.c_str() );
jstring desc = env->NewStringUTF( sIter->second.description.c_str() );
jstring val = env->NewStringUTF( sIter->second.value.c_str() );
jboolean flag = sIter->second.flag;
jvalue sArgs[5];
sArgs[0].l = name;
sArgs[1].l = fName;
sArgs[2].l = desc;
sArgs[3].l = val;
sArgs[4].z = flag;
env->CallVoidMethodA( cw, mid, sArgs );
++sIter;
}
return true;
}
JNIEXPORT jboolean JNICALL Java_refinery_LibLoader_loadFloatOptions
(JNIEnv *env, jobject obj, jstring name, jobject cw )
{
jclass cls = env->GetObjectClass( cw );
jmethodID mid = env->GetMethodID( cls, "addFloatOption",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;F)V");
if (mid == 0) {
printf("addFloatOption not found !!\n");
return false;
}
const char *nm = env->GetStringUTFChars( name, 0 );
std::string nmStr = std::string( nm );
env->ReleaseStringUTFChars( name, nm );
Conditioner *cond = LibLoader::getConditioner( nmStr );
if ( cond == NULL )
{
printf("unable to find Conditioner named %s!!\n", nmStr.c_str() );
return false;
}
Conditioner::FloatOptionMap::const_iterator fIter = cond->getFloatOptionsMap().begin();
while ( fIter != cond->getFloatOptionsMap().end() )
{
jstring name = env->NewStringUTF( fIter->first.c_str() );
jstring fName = env->NewStringUTF( fIter->second.fullName.c_str() );
jstring desc = env->NewStringUTF( fIter->second.description.c_str() );
jvalue fArgs[4];
fArgs[0].l = name;
fArgs[1].l = fName;
fArgs[2].l = desc;
fArgs[3].f = fIter->second.value;
env->CallVoidMethodA( cw, mid, fArgs );
++fIter;
}
return true;
}
JNIEXPORT jboolean JNICALL Java_refinery_LibLoader_changeConditionerName
(JNIEnv *env, jobject obj, jstring oldName, jstring newName )
{
const char *nm = env->GetStringUTFChars( oldName, 0 );
std::string oStr = std::string( nm );
env->ReleaseStringUTFChars( oldName, nm );
Conditioner *cond = LibLoader::getConditioner( oStr );
if ( cond == NULL ) {
printf( "unable to find conditioner: %s\n", oStr.c_str() );
return false;
}
nm = env->GetStringUTFChars( newName, 0 );
std::string nStr = std::string( nm );
env->ReleaseStringUTFChars( newName, nm );
cond->setName( nStr );
if ( !LibLoader::addConditioner( nStr, cond ) )
{
printf( "unable to add conditioner: %s\n", nStr.c_str() );
return false;
}
return LibLoader::removeConditioner( oStr );
}
JNIEXPORT jint JNICALL Java_refinery_LibLoader_execute
(JNIEnv *env, jobject obj, jstring name )
{
const char *nm = env->GetStringUTFChars( name, 0 );
std::string nmStr = std::string( nm );
env->ReleaseStringUTFChars( name, nm );
//printf("entering execute libName is %s\n", nmStr.c_str() );
Conditioner *cond = LibLoader::getConditioner( nmStr );
if ( cond == NULL )
{
printf( "failed to find conditioner named %s!\n", nmStr.c_str() );
return -1;
}
/*for ( unsigned int i = 0; i < cond->getNumInputs(); i++ )
{
printf("input%d is %s\n", i, cond->getInput( i ).c_str() );
}*/
return cond->execute();
}
JNIEXPORT jboolean JNICALL Java_refinery_LibLoader_loadDocument
(JNIEnv *env, jclass cls, jstring doc)
{
const char *nm = env->GetStringUTFChars( doc, 0 );
std::string nmStr = std::string( nm );
env->ReleaseStringUTFChars( doc, nm );
return LibLoader::loadDocument( nmStr );
}
JNIEXPORT jboolean JNICALL Java_refinery_LibLoader_saveDocument
(JNIEnv *env, jclass cls, jstring doc, jstring toFile )
{
const char *nm = env->GetStringUTFChars( doc, 0 );
std::string docStr = std::string( nm );
env->ReleaseStringUTFChars( doc, nm );
nm = env->GetStringUTFChars( toFile, 0 );
std::string toStr = std::string( nm );
env->ReleaseStringUTFChars( toFile, nm );
return LibLoader::saveDocument( docStr, toStr );
}
JNIEXPORT void JNICALL Java_refinery_LibLoader_setInputNumber
(JNIEnv *env, jobject, jstring name, jint num)
{
const char *nm = env->GetStringUTFChars( name, 0 );
std::string nameStr = std::string( nm );
env->ReleaseStringUTFChars( name, nm );
Conditioner *cond = LibLoader::getConditioner( nameStr );
if ( cond == NULL )
{
return;
}
cond->setNumInputs( num, true );
}
JNIEXPORT void JNICALL Java_refinery_LibLoader_setInput
(JNIEnv *env, jobject, jstring name, jint num, jstring doc)
{
const char *nm = env->GetStringUTFChars( name, 0 );
std::string nameStr = std::string( nm );
env->ReleaseStringUTFChars( name, nm );
nm = env->GetStringUTFChars( doc, 0 );
std::string docStr = std::string( nm );
env->ReleaseStringUTFChars( doc, nm );
Conditioner *cond = LibLoader::getConditioner( nameStr );
if ( cond == NULL )
{
return;
}
cond->setInput( num, docStr );
}
JNIEXPORT void JNICALL Java_refinery_LibLoader_setOutput
(JNIEnv *env, jobject, jstring name, jint num, jstring doc)
{
const char *nm = env->GetStringUTFChars( name, 0 );
std::string nameStr = std::string( nm );
env->ReleaseStringUTFChars( name, nm );
nm = env->GetStringUTFChars( doc, 0 );
std::string docStr = std::string( nm );
env->ReleaseStringUTFChars( doc, nm );
Conditioner *cond = LibLoader::getConditioner( nameStr );
if ( cond == NULL )
{
return;
}
cond->setOutput( num, docStr );
}
JNIEXPORT void JNICALL Java_refinery_LibLoader_setBoolOption
(JNIEnv *env, jobject, jstring cName, jstring oName, jboolean val )
{
const char *nm = env->GetStringUTFChars( cName, 0 );
std::string nameStr = std::string( nm );
env->ReleaseStringUTFChars( cName, nm );
nm = env->GetStringUTFChars( oName, 0 );
std::string optionStr = std::string( nm );
env->ReleaseStringUTFChars( oName, nm );
Conditioner *cond = LibLoader::getConditioner( nameStr );
if ( cond == NULL )
{
return;
}
cond->setBoolOption( optionStr, (val != 0) );
}
JNIEXPORT void JNICALL Java_refinery_LibLoader_setStringOption
(JNIEnv *env, jobject, jstring cName, jstring oName, jstring val )
{
const char *nm = env->GetStringUTFChars( cName, 0 );
std::string nameStr = std::string( nm );
env->ReleaseStringUTFChars( cName, nm );
nm = env->GetStringUTFChars( oName, 0 );
std::string optionStr = std::string( nm );
env->ReleaseStringUTFChars( oName, nm );
nm = env->GetStringUTFChars( val, 0 );
std::string valStr = std::string( nm );
env->ReleaseStringUTFChars( val, nm );
Conditioner *cond = LibLoader::getConditioner( nameStr );
if ( cond == NULL )
{
return;
}
cond->setStringOption( optionStr, valStr );
}
JNIEXPORT void JNICALL Java_refinery_LibLoader_setFloatOption
(JNIEnv *env, jobject, jstring cName, jstring oName, jfloat val)
{
const char *nm = env->GetStringUTFChars( cName, 0 );
std::string nameStr = std::string( nm );
env->ReleaseStringUTFChars( cName, nm );
nm = env->GetStringUTFChars( oName, 0 );
std::string optionStr = std::string( nm );
env->ReleaseStringUTFChars( oName, nm );
Conditioner *cond = LibLoader::getConditioner( nameStr );
if ( cond == NULL )
{
return;
}
cond->setFloatOption( optionStr, val );
}
JNIEXPORT void JNICALL Java_refinery_LibLoader_cloneDocument
(JNIEnv *env, jclass, jstring from, jstring to)
{
const char *nm = env->GetStringUTFChars( from, 0 );
std::string fromStr = std::string( nm );
env->ReleaseStringUTFChars( from, nm );
nm = env->GetStringUTFChars( to, 0 );
std::string toStr = std::string( nm );
env->ReleaseStringUTFChars( to, nm );
LibLoader::cloneDocument( fromStr, toStr );
}
JNIEXPORT void JNICALL Java_refinery_LibLoader_clearDOM
(JNIEnv *, jclass)
{
LibLoader::clearDOM();
}
| [
"alorino@7d79dae2-2c22-0410-a73c-a02ad39e49d4",
"sceahklaw@7d79dae2-2c22-0410-a73c-a02ad39e49d4",
"steve314@7d79dae2-2c22-0410-a73c-a02ad39e49d4"
]
| [
[
[
1,
1
],
[
23,
422
],
[
424,
487
]
],
[
[
2,
22
]
],
[
[
423,
423
]
]
]
|
84ab935bbcb04e08da4312163d646d78f591f96b | 72071dfcccdab286fce3b0d4483d9e075f0a2ae3 | /Shape.cpp | 0dcc471b7628e3f2c0aa1edd3f1c4468851aaad0 | []
| no_license | rickumali/RicksTetris | bc824d25ca6403cd12891aa2eae59fc5c6c41a9c | 76128d72f0cfb75ff4d619784c70fec9562d5c71 | refs/heads/master | 2016-09-06T04:27:15.587789 | 2011-12-23T18:17:10 | 2011-12-23T18:17:10 | 3,043,175 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,227 | cpp | #include "Shape.h"
// Constructor
Shape::Shape() {
rotation = 0;
}
// height()
int Shape::height() const {
return shape_height[rotation];
}
// width()
int Shape::width() const {
return shape_width[rotation];
}
// &height()
int& Shape::height() {
return shape_height[rotation];
}
// &width()
int& Shape::width() {
return shape_width[rotation];
}
// direction is -1 for left, and +1 for right
void Shape::rotate(int direction) {
rotation += direction;
if (rotation < 0) {
rotation = 3;
} else if (rotation > 3) {
rotation = 0;
}
}
// return the shape_data character at row, col
// Take a look at the Ruminations on C++ Book, Chapter 9, for the
// inspiration of this method
char Shape::shapedata(int row, int col) const {
return (shape_data[rotation][(row*shape_width[rotation])+col]);
}
char& Shape::shapedata(int row, int col) {
return (shape_data[rotation][(row*shape_width[rotation])+col]);
}
// This is meant for initialization routines. It returns a reference to
// shape_data for the current "rotation." See init_shape() routines in the
// various shapes.
string& Shape::shapedata() {
return shape_data[rotation];
}
| [
"[email protected]"
]
| [
[
[
1,
52
]
]
]
|
c0454091be12cf4855ec177a68a51a1dbe3274a6 | a0155e192c9dc2029b231829e3db9ba90861f956 | /Libs/mwnlm/Libraries/MSL C++/Include/strstream.h | 06c245738f679a3f6f227086f46960c11972e6be | []
| no_license | zeha/mailfilter | d2de4aaa79bed2073cec76c93768a42068cfab17 | 898dd4d4cba226edec566f4b15c6bb97e79f8001 | refs/heads/master | 2021-01-22T02:03:31.470739 | 2010-08-12T23:51:35 | 2010-08-12T23:51:35 | 81,022,257 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 499 | h | /* Metrowerks Standard Library
* Copyright © 1995-2002 Metrowerks Corporation. All rights reserved.
*
* $Date: 2002/07/01 21:13:37 $
* $Revision: 1.3 $
*/
// strstream.h
#ifndef _STRSTREAM_H
#define _STRSTREAM_H
#include <strstream>
#ifndef _MSL_NO_CPP_NAMESPACE
#ifndef _MSL_NO_IO
using std::strstreambuf;
using std::istrstream;
using std::ostrstream;
using std::strstream;
#endif
#endif
#endif // _STRSTREAM_H
// hh 990120 changed name of MSIPL flags
| [
"[email protected]"
]
| [
[
[
1,
26
]
]
]
|
92c84c174aa5cf9770694d5c1c97085087a787de | 1e01b697191a910a872e95ddfce27a91cebc57dd | /GrfParsedString.h | a571619fa4260991c029722d406016d9c6bfe6b2 | []
| no_license | canercandan/codeworker | 7c9871076af481e98be42bf487a9ec1256040d08 | a68851958b1beef3d40114fd1ceb655f587c49ad | refs/heads/master | 2020-05-31T22:53:56.492569 | 2011-01-29T19:12:59 | 2011-01-29T19:12:59 | 1,306,254 | 7 | 5 | null | null | null | null | IBM852 | C++ | false | false | 1,555 | h | /* "CodeWorker": a scripting language for parsing and generating text.
Copyright (C) 1996-1997, 1999-2002 CÚdric Lemaire
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
To contact the author: [email protected]
*/
#ifndef _GrfParsedString_h_
#define _GrfParsedString_h_
#include "GrfBlock.h"
namespace CodeWorker {
class ExprScriptExpression;
class GrfParsedString : public GrfBlock {
private:
ExprScriptExpression* _pInputString;
public:
GrfParsedString(GrfBlock* pParent) : GrfBlock(pParent), _pInputString(NULL) {}
virtual ~GrfParsedString();
inline void setInputString(ExprScriptExpression* pInputString) { _pInputString = pInputString; }
virtual void compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const;
protected:
virtual SEQUENCE_INTERRUPTION_LIST executeInternal(DtaScriptVariable& visibility);
};
}
#endif
| [
"cedric.p.r.lemaire@28b3f5f3-d42e-7560-b87f-5f53cf622bc4"
]
| [
[
[
1,
46
]
]
]
|
b7a86ecaaa8eff9663a98a3b97ce3425fcb26253 | 036f83e4ba5370b4ec50da6d1d1561d85dedbde0 | /learning-cpp/pair.cpp | dc01e246fd83ebb673c8f73aa0fdfcc79306fa57 | []
| no_license | losvald/high-school | 8ba4487889093451b519c3f582d0dce8a5a6f5b8 | 4bfe295ad4ef1badf8a01d19e2ab3a65d59c1ce8 | refs/heads/master | 2016-09-06T03:48:25.747372 | 2008-01-17T10:56:55 | 2008-01-17T10:56:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | cpp | #include <conio.h>
#include <iostream.h>
#include <vector.h>
#include <algorithm>
#include <stdio.h>
int main() {
int a[6] = {1, 4, 6, 7, 10, 25};
vector<int> v2(&a[0], &a[5]);
pair<vector<int>::iterator, vector<int>::iterator> par;
par.first = lower_bound(v2.begin(), v2.end(), 7);
par.second = upper_bound(v2.begin(), v2.end(), 4);
cout << *par.first << " " << *par.second;
getch();
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
15
]
]
]
|
a1ed864b89a32e57ba798f2f10f90826007a8381 | 80716d408715377e88de1fc736c9204b87a12376 | /TspLib3/Samples/JTSP/TSP/Phone.cpp | bdbd78610ae9a65d0f12ab44a689a918ba01b9e2 | []
| no_license | junction/jn-tapi | b5cf4b1bb010d696473cabcc3d5950b756ef37e9 | a2ef6c91c9ffa60739ecee75d6d58928f4a5ffd4 | refs/heads/master | 2021-03-12T23:38:01.037779 | 2011-03-10T01:08:40 | 2011-03-10T01:08:40 | 199,317 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 12,367 | cpp | /***************************************************************************
//
// PHONE.CPP
//
// JulMar Sample TAPI Service provider for TSP++ version 3.00
// Phone management functions
//
// Copyright (C) 1998 JulMar Entertainment Technology, Inc.
// All rights reserved
//
// This source code is intended only as a supplement to the
// TSP++ Class Library product documentation. This source code cannot
// be used in part or whole in any form outside the TSP++ library.
//
// Modification History
// ------------------------------------------------------------------------
// 09/04/1998 MCS@Julmar Generated from TSPWizard.exe
//
/***************************************************************************/
/*-------------------------------------------------------------------------------*/
// INCLUDE FILES
/*-------------------------------------------------------------------------------*/
#include "stdafx.h"
#include "jtsp.h"
/*-------------------------------------------------------------------------------*/
// DEBUG SUPPORT
/*-------------------------------------------------------------------------------*/
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/*-------------------------------------------------------------------------------*/
// TSPI Request map
/*-------------------------------------------------------------------------------*/
BEGIN_TSPI_REQUEST(CJTPhone)
ON_TSPI_REQUEST_SETHOOKSWITCHGAIN(OnSetGain)
ON_TSPI_REQUEST_SETHOOKSWITCH(OnSetHookswitch)
ON_TSPI_REQUEST_SETHOOKSWITCHVOL(OnSetVolume)
END_TSPI_REQUEST()
/*****************************************************************************
** Procedure: CJTPhone::read
**
** Arguments: 'istm' - Input stream
**
** Returns: pointer to istm
**
** Description: This function is called to serialize data in from the
** registry. The phone object has already been completely
** initialized by the TSP++ library
**
*****************************************************************************/
TStream& CJTPhone::read(TStream& istm)
{
// Load our default display which is used while we have no agent
// logged into this station.
SetDisplay(_T(" NOT LOGGED ON"));
// Return the base class loading.
return CTSPIPhoneConnection::read(istm);
}// CJTPhone::read
/*****************************************************************************
** Procedure: CJTPhone::OpenDevice
**
** Arguments: void
**
** Returns: void
**
** Description: This method is called when the phone is opened by TAPI.
** We want to check and see if the associated line is currently CONNECTED
** to the TL server.
**
*****************************************************************************/
bool CJTPhone::OpenDevice()
{
// If the associated line is not connected then fail the open request.
// The connected flag on the line is used to determine whether we are connected
// to the simulator.
if ((GetAssociatedLine()->GetLineDevStatus()->dwDevStatusFlags & LINEDEVSTATUSFLAGS_CONNECTED) == 0)
return false;
return CTSPIPhoneConnection::OpenDevice();
}// CJTPhone::OpenDevice
/*****************************************************************************
** Procedure: CJTPhone::OnTimer
**
** Arguments: void
**
** Returns: void
**
** Description: This method is called periodically by the interval timer
**
*****************************************************************************/
void CJTPhone::OnTimer()
{
// Poll the active request for timeout
ReceiveData();
}// CJTPhone::OnTimer
/*****************************************************************************
** Procedure: CJTPhone::OnSetGain
**
** Arguments: 'pReq' - Request object representing this phone request
** 'lpBuff' - Our CEventBlock* pointer
**
** Returns: void
**
** Description: This function manages the TSPI_phoneSetGain processing
** for this service provider.
**
*****************************************************************************/
bool CJTPhone::OnSetGain(RTSetGain* pRequest, LPCVOID lpBuff)
{
// Cast our pointer back to an event block
const CEventBlock* pBlock = static_cast<const CEventBlock*>(lpBuff);
// If we are in the initial state (i.e. this request has not been processed
// before by any other thread). Then move the packet to the waiting state so
// other threads will not interfere with other events or timers. This is
// guarenteed to be thread-safe and atomic.
if (pRequest->EnterState(STATE_INITIAL, STATE_WAITING))
{
// Send the command to the switch
GetDeviceInfo()->DRV_SetGain(this, pRequest->GetGain());
}
// If we are in the waiting stage (2) then see if we received an event from the
// switch (vs. an interval timer) and if that event was an ACK/NAK in response
// to the command we issued.
else if (pRequest->GetState() == STATE_WAITING && pBlock != NULL)
{
// If this is a command response for our SETGAIN, then manage it.
const CPECommand* peCommand = dynamic_cast<const CPECommand*>(pBlock->GetElement(CPBXElement::Command));
const CPEErrorCode* pidError = dynamic_cast<const CPEErrorCode*>(pBlock->GetElement(CPBXElement::ErrorCode));
if (pBlock->GetEventType() == CEventBlock::CommandResponse &&
peCommand->GetCommand() == CPECommand::SetGain && pidError != NULL)
{
// Complete the request with the appropriate error code.
TranslateErrorCode(pRequest, pidError->GetError());
return true;
}
}
// Check to see if our request has exceeded the limit for processing. If
// so, tell TAPI that the request failed and delete the request.
if (pRequest->GetState() == STATE_WAITING &&
(pRequest->GetStateTime()+REQUEST_TIMEOUT) < GetTickCount())
CompleteRequest(pRequest, PHONEERR_OPERATIONFAILED);
// Let the request fall through to the unsolicited handler where we
// set all the options concerning the newly found call.
return false;
}// CJTPhone::OnSetGain
/*****************************************************************************
** Procedure: CJTPhone::OnSetHookswitch
**
** Arguments: 'pReq' - Request object representing this phone request
** 'lpBuff' - Our CEventBlock* pointer
**
** Returns: void
**
** Description: This function manages the TSPI_phoneSetHookSwitch processing
** for this service provider.
**
*****************************************************************************/
bool CJTPhone::OnSetHookswitch(RTSetHookswitch* pRequest, LPCVOID lpBuff)
{
// Cast our pointer back to an event block
const CEventBlock* pBlock = static_cast<const CEventBlock*>(lpBuff);
// If we are in the initial state (i.e. this request has not been processed
// before by any other thread). Then move the packet to the waiting state so
// other threads will not interfere with other events or timers. This is
// guarenteed to be thread-safe and atomic.
if (pRequest->EnterState(STATE_INITIAL, STATE_WAITING))
{
// Validate the state passed
if (pRequest->GetHookswitchState() == PHONEHOOKSWITCHMODE_ONHOOK ||
pRequest->GetHookswitchState() == PHONEHOOKSWITCHMODE_MIC)
CompleteRequest(pRequest, PHONEERR_INVALHOOKSWITCHMODE);
// Send the command to the switch
else
GetDeviceInfo()->DRV_SetHookswitch(this, (pRequest->GetHookswitchState() == PHONEHOOKSWITCHMODE_MICSPEAKER) ? 1 : 0);
}
// If we are in the waiting stage (2) then see if we received an event from the
// switch (vs. an interval timer) and if that event was an ACK/NAK in response
// to the command we issued.
else if (pRequest->GetState() == STATE_WAITING && pBlock != NULL)
{
// If this is a command response for our SETGAIN, then manage it.
const CPECommand* peCommand = dynamic_cast<const CPECommand*>(pBlock->GetElement(CPBXElement::Command));
const CPEErrorCode* pidError = dynamic_cast<const CPEErrorCode*>(pBlock->GetElement(CPBXElement::ErrorCode));
if (pBlock->GetEventType() == CEventBlock::CommandResponse &&
peCommand->GetCommand() == CPECommand::SetHookSwitch && pidError != NULL)
{
// Complete the request with the appropriate error code.
TranslateErrorCode(pRequest, pidError->GetError());
return true;
}
}
// Check to see if our request has exceeded the limit for processing. If
// so, tell TAPI that the request failed and delete the request.
if (pRequest->GetState() == STATE_WAITING &&
(pRequest->GetStateTime()+REQUEST_TIMEOUT) < GetTickCount())
CompleteRequest(pRequest, PHONEERR_OPERATIONFAILED);
// Let the request fall through to the unsolicited handler where we
// set all the options concerning the newly found call.
return false;
}// CJTPhone::OnSetHookswitch
/*****************************************************************************
** Procedure: CJTPhone::OnSetVolume
**
** Arguments: 'pReq' - Request object representing this phone request
** 'lpBuff' - Our CEventBlock* pointer
**
** Returns: void
**
** Description: This function manages the TSPI_phoneSetVolume processing
** for this service provider.
**
*****************************************************************************/
bool CJTPhone::OnSetVolume(RTSetVolume* pRequest, LPCVOID lpBuff)
{
// Cast our pointer back to an event block
const CEventBlock* pBlock = static_cast<const CEventBlock*>(lpBuff);
// If we are in the initial state (i.e. this request has not been processed
// before by any other thread). Then move the packet to the waiting state so
// other threads will not interfere with other events or timers. This is
// guarenteed to be thread-safe and atomic.
if (pRequest->EnterState(STATE_INITIAL, STATE_WAITING))
{
// Send the command to the switch
GetDeviceInfo()->DRV_SetVolume(this, pRequest->GetVolume());
}
// If we are in the waiting stage (2) then see if we received an event from the
// switch (vs. an interval timer) and if that event was an ACK/NAK in response
// to the command we issued.
else if (pRequest->GetState() == STATE_WAITING && pBlock != NULL)
{
// If this is a command response for our SETGAIN, then manage it.
const CPECommand* peCommand = dynamic_cast<const CPECommand*>(pBlock->GetElement(CPBXElement::Command));
const CPEErrorCode* pidError = dynamic_cast<const CPEErrorCode*>(pBlock->GetElement(CPBXElement::ErrorCode));
if (pBlock->GetEventType() == CEventBlock::CommandResponse &&
peCommand->GetCommand() == CPECommand::SetVolume && pidError != NULL)
{
// Complete the request with the appropriate error code.
TranslateErrorCode(pRequest, pidError->GetError());
return true;
}
}
// Check to see if our request has exceeded the limit for processing. If
// so, tell TAPI that the request failed and delete the request.
if (pRequest->GetState() == STATE_WAITING &&
(pRequest->GetStateTime()+REQUEST_TIMEOUT) < GetTickCount())
CompleteRequest(pRequest, PHONEERR_OPERATIONFAILED);
// Let the request fall through to the unsolicited handler where we
// set all the options concerning the newly found call.
return false;
}// CJTPhone::OnSetVolume
/*****************************************************************************
** Procedure: CJTPhone::TranslateErrorCode
**
** Arguments: 'pRequest' - Request object representing this phone request
** 'dwError' - Error code
**
** Returns: void
**
** Description: This function completes the request with an appropriate
** TAPI error code based on the PBX error received.
**
*****************************************************************************/
void CJTPhone::TranslateErrorCode(CTSPIRequest* pRequest, DWORD dwError)
{
switch (dwError)
{
case CPEErrorCode::None: dwError = 0; break;
case CPEErrorCode::InvalidDevice: dwError = PHONEERR_BADDEVICEID; break;
case CPEErrorCode::BadCommand: dwError = PHONEERR_INVALPHONESTATE; break;
case CPEErrorCode::InvalidParameter: dwError = PHONEERR_INVALPARAM; break;
default: dwError = PHONEERR_OPERATIONFAILED; break;
}
CompleteRequest(pRequest, dwError);
}// CJTPhone::TranslateErrorCode
| [
"Owner@.(none)"
]
| [
[
[
1,
305
]
]
]
|
450ab6f8a75e00289afd65d1b19087c7f9c8db0d | f49d4ccfa7c584e6768e7be6ef12543beaa8c609 | /src/geometry.h | c8c6adf56645a62e1b0c828f1917f26df5341344 | []
| no_license | rehno-lindeque/osi-glrasre | eb38eb8a5398d3694e8c4e9433d93e6bd3b5cb7d | 6d687330c88ed0cb8a5c07b36bf3a8594da4497f | refs/heads/master | 2016-09-06T11:30:08.776829 | 2011-01-29T09:58:01 | 2011-01-29T09:58:01 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 16,694 | h | #ifndef __GLRASRE_GEOMETRY_H__
#define __GLRASRE_GEOMETRY_H__
//////////////////////////////////////////////////////////////////////////////
//
// GEOMETRY.H
//
// Author: Rehno Lindeque
//
// Description: GlRasRE classes used to implement api
//
// Version: 0.1 (informal prototype)
//
// Copyright © 2006, Rehno Lindeque. All rights reserved.
//
//////////////////////////////////////////////////////////////////////////////
/* DOCUMENTATION */
/*
DESCRIPTION:
Geometry implementation for opengl using PBO's fpr VBO (etc) and texture
storage.
IMPLEMENTATION:
+ Currently the implementation assumes (requires) 16bit unsigned
integer format for indexes.
DEPENDENCIES:
stream.h
*/
/* COMPILER MACROS */
#ifndef __BASERE_STREAM_H__
#error "stream.h must be included before geometry.h"
#endif
/* CLASSES */
using namespace BaseRE;
namespace GlRasRE
{
class GlRasMesh : public Mesh
{
protected:
/*float* vertices;
uint16* indices;*/
public:
/*GlStream vertexStream;
GlStream indexStream;
//GlStream discStream; // for ambient occlusion
GlStream normDiscStream; // vertex normals and disc area for ambient occlusion
void create(uint sizeX, uint sizeY /* todo:, flag = STATIC_GEOMETRY *)
{
vertexStream.create(sizeX, sizeY, VEC4_FLOAT16_STREAM, null);
indexStream.create(sizeX, sizeY, FIXED16_STREAM, null);
//discStream.create(vertexStream.getLength(), VEC4_FLOAT16_STREAM, null);
//discStream.create(sizeX, sizeY, FLOAT16_STREAM, null);
normDiscStream.create(sizeX, sizeY, VEC4_FLOAT16_STREAM, null);
/*DEPRICATED: how big will the indexStream be? For now: size/2
indexStream.create((uint)ceil(sizeX/2.0), (uint)ceil(sizeY/2.0), VEC4_FIXED8_STREAM, null);*
vertices = (float*)vertexStream.map(WRITE_ONLY);
indices = (uint16*)indexStream.map(WRITE_ONLY);
}*/
void build()
{
Component* component;
if(points == null)
{
if(vertices == null)
return;
else
component = vertices;
}
else
component = points;
// calculate bent normals and disc areas (for use in ambient occlusion calculation)
if(component->getAttributes(RE_EXT_BENT_NORMAL_AREA) == 0)
{
// determine number of points in the mesh
REid locations = component->getAttributes(RE_LOCATION);
REuint nElements = reGetElementsLength(locations);
// create an elements set for bent normals and point disc areas
REid normAreaElements = reBeginElements(RE_VEC4_FLOAT, nElements);
float normArea[4] = {0.0f, 0.0f, 0.0f, 2.0f};
for(uint c = 0; c < nElements; ++c)
{
reElement(normArea);
}
reEndElements();
component->addAttributes(RE_EXT_BENT_NORMAL_AREA, normAreaElements);
}
}
/* old void build()
{
//calculate normals & vertex-disc sizes for ambient occlusion
if(true) // (if ambient occlusion is on? - but what about normals)
{
//HVector3* vertices = (HVector3*)GlRasGeometry::vertices;
HCoord3* vertices = (HCoord3*)GlRasGeometry::vertices;
// create & open stream for disc areas
//discStream.create(vertexStream.getLength(), FLOAT16_STREAM, null);
//discStream.create(vertexStream.getLength(), VEC4_FLOAT16_STREAM, null);
float* discs = (float*)normDiscStream.map(WRITE_ONLY);
memset(discs, 0, normDiscStream.getMappedBufferSize());
for(uint c = 0; c < indexStream.getLength()/3; c++) // for each triangle
{
// initialize variables
//Vector3 v1(&vertices[indices[c*3+0]*4]); //note: 3 indices\vertices per triangle, 4 floats per vertex
uint16 i1 = indices[c*3+0];
uint16 i2 = indices[c*3+1];
uint16 i3 = indices[c*3+2];
//HVector3& v1 = vertices[i1];
//HVector3& v2 = vertices[i2];
//HVector3& v3 = vertices[i3];
Vector3& v1 = (Vector3&)vertices[i1];
Vector3& v2 = (Vector3&)vertices[i2];
Vector3& v3 = (Vector3&)vertices[i3];
// calculate 2 sides (to be used for normal calculation later)
Vector3 s1 = v1-v2;
Vector3 s2 = v2-v3;
// calculate triangle side lengths
float l1 = s1.getLength(); //(v1-v2).getLength();
float l2 = s2.getLength(); //(v2-v3).getLength();
float l3 = (v3-v1).getLength();
// calculate triangle area using heron's formula
float s = (l1 + l2 + l3)/2.0f;
float triangleArea = sqrt(s*(s-l1)*(s-l2)*(s-l3));
// add to disc areas
discs[i1*4+3] += triangleArea / 3.0f;
discs[i2*4+3] += triangleArea / 3.0f;
discs[i3*4+3] += triangleArea / 3.0f;
// calculate triangle normal
Vector3 n = Vector3::cross(s1, s2).normalize();
// add triangle normal to each vertex
Vector3& n1 = *(Vector3*)&discs[i1*4];
Vector3& n2 = *(Vector3*)&discs[i2*4];
Vector3& n3 = *(Vector3*)&discs[i3*4];
n1 += n;
n2 += n;
n3 += n;
}
// normalize vertex normals
for(uint c = 0; c < vertexStream.getLength()/3; c++) // for each vertex \ disc
{
Vector3& n = *(Vector3*)&discs[c*4];
n.normalize();
}
// close stream for normals & disc areas
normDiscStream.unmap();
discs = null;
}
// close vertex and index streams
vertexStream.unmap();
indexStream.unmap();
vertices = null;
indices = null;
}*/
/*old: void addQuads(const Quads& quads)
{
// convert quads to triangles
uint nTriangles = quads.nQuads*2;
/*short* indices = null;
float* vertices = null;*
// create vertices
if(quads.vertexStride == /*sizeof(float)*4* vertexStream.getMappedElementSize())
//vertices = quads.vertices;
vertexStream.appendCopy(quads.vertices, quads.nVertices);
else
{
float* vertices = (float*)vertexStream.appendCreate(quads.nVertices); //DEPRICATED: vertices = new float[quads.nVertices*4];
for(uint c = 0; c < quads.nQuads; ++c)
{
((HPoint3*)vertices)[c*4+0] = quads.getVertex(c,0);
((HPoint3*)vertices)[c*4+1] = quads.getVertex(c,1);
((HPoint3*)vertices)[c*4+2] = quads.getVertex(c,2);
((HPoint3*)vertices)[c*4+3] = quads.getVertex(c,3);
}
}
// create indices
if(quads.indices != null)
{
// initialize temporary variables
uint nIndices = nTriangles * 3;
uint16* indices = (uint16*)indexStream.appendCreate(nIndices); //DEPRICATED: indices = new short[nIndices];
// convert quad indices to triangle indices
for(uint c = 0; c < quads.nQuads; ++c)
{
// split quad along shortest cross-connection (note: we're working with square length for efficiency reasons)
//todo: this could probably be optimized further (maybe look into it later)
Vector3 v0(quads.getVertex(c,0));
Vector3 v1(quads.getVertex(c,1));
Vector3 v2(quads.getVertex(c,2));
Vector3 v3(quads.getVertex(c,3));
float len1 = (v0 - v2).getSquareLength();
float len2 = (v1 - v3).getSquareLength();
if(len1 < len2)
{
// copy quad indices 0,1,2 -> triangle indices 0,1,2
indices[c*6+0] = quads.getIndex(c,0);
indices[c*6+1] = quads.getIndex(c,1);
indices[c*6+2] = quads.getIndex(c,2);
// copy quad indices 2,3,0 -> triangle indices 3,4,5
indices[c*6+3] = quads.getIndex(c,2);
indices[c*6+4] = quads.getIndex(c,3);
indices[c*6+5] = quads.getIndex(c,0);
}
else
{
// copy quad indices 0,1,3 -> triangle indices 0,1,2
indices[c*6+0] = quads.getIndex(c,0);
indices[c*6+1] = quads.getIndex(c,1);
indices[c*6+2] = quads.getIndex(c,3);
// copy quad indices 1,2,3 -> triangle indices 3,4,5
indices[c*6+3] = quads.getIndex(c,1);
indices[c*6+4] = quads.getIndex(c,2);
indices[c*6+5] = quads.getIndex(c,3);
}
}
}
else
{
// initialize temporary variables
uint nIndices = nTriangles * 3;
uint16* indices = (uint16*)indexStream.appendCreate(nIndices); //DEPRICATED: indices = new short[nIndices];
uint firstIndex = vertexStream.getLength() - quads.nVertices;
// create triangle indices
for(uint c = 0; c < quads.nQuads; ++c)
{
// split quad along shortest cross-connection (note: we're working with square length for efficiency reasons)
//todo: this could probably be optimized further (maybe look into it later)
Vector3 v0(quads.getVertex(c,0));
Vector3 v1(quads.getVertex(c,1));
Vector3 v2(quads.getVertex(c,2));
Vector3 v3(quads.getVertex(c,3));
float len1 = (v0 - v2).getSquareLength();
float len2 = (v1 - v3).getSquareLength();
if(len1 < len2)
{
// set quad vertices 0,1,2 -> triangle indices 0,1,2
indices[c*6+0] = firstIndex+c*4+0;
indices[c*6+1] = firstIndex+c*4+1;
indices[c*6+2] = firstIndex+c*4+2;
// copy quad vertices 2,3,0 -> triangle indices 3,4,5
indices[c*6+3] = firstIndex+c*4+2;
indices[c*6+4] = firstIndex+c*4+3;
indices[c*6+5] = firstIndex+c*4+0;
}
else
{
// copy quad vertices 0,1,3 -> triangle vertices 0,1,2
indices[c*6+0] = firstIndex+c*4+0;
indices[c*6+1] = firstIndex+c*4+1;
indices[c*6+2] = firstIndex+c*4+3;
// copy quad vertices 1,2,3 -> triangle vertices 3,4,5
indices[c*6+3] = firstIndex+c*4+1;
indices[c*6+4] = firstIndex+c*4+2;
indices[c*6+5] = firstIndex+c*4+3;
}
}
}
/* TEMPORARILY DEPRICATED: Note - this is needed if indices aren't used
else
{
// initialize temporary variables
uint nVertices = nTriangles * 3;
float* vertices = new float[nTriangles*3*4];
// convert quad vertices to triangle vertices
for(uint c = 0; c < quads.nQuads; ++c)
{
// split quad along shortest cross-connection (note: we're working with square length for efficiency reasons)
//todo: this could probably be optimized further (maybe look into it later)
Vector3 v0(quads.getVertex(c,0));
Vector3 v1(quads.getVertex(c,1));
Vector3 v2(quads.getVertex(c,2));
Vector3 v3(quads.getVertex(c,3));
float len1 = (v0 - v2).getSquareLength();
float len2 = (v1 - v3).getSquareLength();
if(len1 < len2)
{
// copy quad vertices 0,1,2 -> triangle vertices 0,1,2
/* old: memcpy(&vertices[(c*6+0)*3], &quads.vertices[(c*4+0)*3], 3*3*sizeof(float)); *
*(HPoint3*)((int8*)vertices + (c*6+0) * 4*sizeof(float)) = v0;
*(HPoint3*)((int8*)vertices + (c*6+1) * 4*sizeof(float)) = v1;
*(HPoint3*)((int8*)vertices + (c*6+2) * 4*sizeof(float)) = v2;
// copy quad vertices 2,3,0 -> triangle vertices 3,4,5
/* old: memcpy(&vertices[(c*6+3)*3], &quads.vertices[(c*4+2)*3], 2*3*sizeof(float));
memcpy(&vertices[(c*6+5)*3], &quads.vertices[(c*4+0)*3], 1*3*sizeof(float)); *
*(HPoint3*)((int8*)vertices + (c*6+3) * 4*sizeof(float)) = v2;
*(HPoint3*)((int8*)vertices + (c*6+4) * 4*sizeof(float)) = v3;
*(HPoint3*)((int8*)vertices + (c*6+5) * 4*sizeof(float)) = v0;
}
else
{
// copy quad vertices 0,1,3 -> triangle vertices 0,1,2
/*old: memcpy(&vertices[(c*6+0)*3], &quads.vertices[(c*4+0)*3], 2*3*sizeof(float));
memcpy(&vertices[(c*6+2)*3], &quads.vertices[(c*4+3)*3], 1*3*sizeof(float)); *
*(HPoint3*)((int8*)vertices + (c*6+0) * 4*sizeof(float)) = v0;
*(HPoint3*)((int8*)vertices + (c*6+1) * 4*sizeof(float)) = v1;
*(HPoint3*)((int8*)vertices + (c*6+2) * 4*sizeof(float)) = v3;
// copy quad vertices 1,2,3 -> triangle vertices 3,4,5
/* old: memcpy(&vertices[(c*6+3)*3], &quads.vertices[(c*4+1)*3], 3*3*sizeof(float)); *
*(HPoint3*)((int8*)vertices + (c*6+3) * 4*sizeof(float)) = v1;
*(HPoint3*)((int8*)vertices + (c*6+4) * 4*sizeof(float)) = v2;
*(HPoint3*)((int8*)vertices + (c*6+5) * 4*sizeof(float)) = v3;
}
}
}*/
/* DEPRICATED:
// append triangle data to the buffer
vertexStream.append(vertices, nTriangles*3);
indexStream.append(indices, nIndices);
// destroy temporary buffer
delete[] vertices;*
}
/*
void oldAddQuads(const Quads& quads)
{
// convert quads to triangles
uint nTriangles = quads.nQuads*2;
// create vertices
// initialize temporary variables
uint nVertices = nTriangles * 3;
float* vertices = new float[nTriangles*3*4];
// convert quad vertices to triangle vertices
for(uint c = 0; c < quads.nQuads; ++c)
{
// split quad along shortest cross-connection (note: we're working with square length for efficiency reasons)
//todo: this could probably be optimized further (maybe look into it later)
Vector3 v0(quads.getVertex(c,0));
Vector3 v1(quads.getVertex(c,1));
Vector3 v2(quads.getVertex(c,2));
Vector3 v3(quads.getVertex(c,3));
float len1 = (v0 - v2).getSquareLength();
float len2 = (v1 - v3).getSquareLength();
if(len1 < len2)
{
// copy quad vertices 0,1,2 -> triangle vertices 0,1,2
/* old: memcpy(&vertices[(c*6+0)*3], &quads.vertices[(c*4+0)*3], 3*3*sizeof(float)); *
*(HPoint3*)((int8*)vertices + (c*6+0) * 4*sizeof(float)) = v0;
*(HPoint3*)((int8*)vertices + (c*6+1) * 4*sizeof(float)) = v1;
*(HPoint3*)((int8*)vertices + (c*6+2) * 4*sizeof(float)) = v2;
// copy quad vertices 2,3,0 -> triangle vertices 3,4,5
/* old: memcpy(&vertices[(c*6+3)*3], &quads.vertices[(c*4+2)*3], 2*3*sizeof(float));
memcpy(&vertices[(c*6+5)*3], &quads.vertices[(c*4+0)*3], 1*3*sizeof(float)); *
*(HPoint3*)((int8*)vertices + (c*6+3) * 4*sizeof(float)) = v2;
*(HPoint3*)((int8*)vertices + (c*6+4) * 4*sizeof(float)) = v3;
*(HPoint3*)((int8*)vertices + (c*6+5) * 4*sizeof(float)) = v0;
}
else
{
// copy quad vertices 0,1,3 -> triangle vertices 0,1,2
/*old: memcpy(&vertices[(c*6+0)*3], &quads.vertices[(c*4+0)*3], 2*3*sizeof(float));
memcpy(&vertices[(c*6+2)*3], &quads.vertices[(c*4+3)*3], 1*3*sizeof(float)); *
*(HPoint3*)((int8*)vertices + (c*6+0) * 4*sizeof(float)) = v0;
*(HPoint3*)((int8*)vertices + (c*6+1) * 4*sizeof(float)) = v1;
*(HPoint3*)((int8*)vertices + (c*6+2) * 4*sizeof(float)) = v3;
// copy quad vertices 1,2,3 -> triangle vertices 3,4,5
/* old: memcpy(&vertices[(c*6+3)*3], &quads.vertices[(c*4+1)*3], 3*3*sizeof(float)); *
*(HPoint3*)((int8*)vertices + (c*6+3) * 4*sizeof(float)) = v1;
*(HPoint3*)((int8*)vertices + (c*6+4) * 4*sizeof(float)) = v2;
*(HPoint3*)((int8*)vertices + (c*6+5) * 4*sizeof(float)) = v3;
}
}
// append triangle data to the buffer
vertexStream.appendCopy(vertices, nTriangles*3);
// destroy temporary buffer
delete[] vertices;
}*/
void destroy()
{
/*indexStream.destroy();
vertexStream.destroy();
normDiscStream.destroy();*/
}
};
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
426
]
]
]
|
a456ebe6002ea7f58cfbaa37ed36db47abd27e7a | 9152cb31fbe4e82c22092bb3071b2ec8c6ae86ab | /face/popoface/IMShortcutTool.h | 665ee311f8fd30cfae0b73c659cf728fa3b74d67 | []
| no_license | zzjs2001702/sfsipua-svn | ca3051b53549066494f6264e8f3bf300b8090d17 | e8768338340254aa287bf37cf620e2c68e4ff844 | refs/heads/master | 2022-01-09T20:02:20.777586 | 2006-03-29T13:24:02 | 2006-03-29T13:24:02 | null | 0 | 0 | null | null | null | null | ISO-8859-7 | C++ | false | false | 1,830 | h | #if !defined(AFX_IMSHORTCUTTOOL_H__DC6D3943_144A_11D7_90A4_006008267A03__INCLUDED_)
#define AFX_IMSHORTCUTTOOL_H__DC6D3943_144A_11D7_90A4_006008267A03__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// IMShortcutTool.h : header file
//
#include "Skin.h"
#include "CNButton.h"
#include "IMChat.h"
/////////////////////////////////////////////////////////////////////////////
// CIMShortcutTool window
#define MAX_BUTTON 10
#define BUTTON_HEIGHT 18
#define WM_CN_ITEMCLICK WM_USER+100
class CIMShortcutTool : public CWnd
{
// Construction
public:
CIMShortcutTool();
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CIMShortcutTool)
//}}AFX_VIRTUAL
// Implementation
public:
virtual int GetClientHeight();
BOOL m_bHide;
virtual BOOL AddButton(CString Caption, int nID,int nImage = -1);
virtual ~CIMShortcutTool();
// Generated message map functions
protected:
CSkin *m_pSkin;
CNButton *m_pBtnIWarnt;
CNButton *m_pBtn[MAX_BUTTON];
CImageList *m_ILIcon; //ΝΌΟσΑΠ±ν
//{{AFX_MSG(CIMShortcutTool)
afx_msg void OnPaint();
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnBNClicked1();
afx_msg void OnBNClicked2();
//}}AFX_MSG
afx_msg LRESULT OnBNClicked(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
private:
void ShowHideButton();
int m_iButtonCount;
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_IMSHORTCUTTOOL_H__DC6D3943_144A_11D7_90A4_006008267A03__INCLUDED_)
| [
"yippeesoft@5dda88da-d10c-0410-ac74-cc18da35fedd"
]
| [
[
[
1,
72
]
]
]
|
bed413f18150fb1e2b25ee4923e80bd22aaeb033 | af260b99d9f045ac4202745a3c7a65ac74a5e53c | /trunk/engine/src/status_reporter/BaseStatusReporter.hpp | 20a3ba8d413a000f4f9012378ca19119ad8b9c94 | []
| no_license | BackupTheBerlios/snap-svn | 560813feabcf5d01f25bc960d474f7e218373da0 | a99b5c64384cc229e8628b22f3cf6a63a70ed46f | refs/heads/master | 2021-01-22T09:43:37.862180 | 2008-02-17T15:50:06 | 2008-02-17T15:50:06 | 40,819,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,574 | hpp | #ifndef __BASE_STATUS_REPORTER_H__
#define __BASE_STATUS_REPORTER_H__
/*
BaseStatusReporter.hpp
Author: Jeremy Moskovich
Abstract base class for progress reporting.
*/
#include "boost/shared_ptr.hpp"
#include "core/Defs.h"
#include "core/Str.h"
#include "core/Argv.h"
class BaseStatusReporter {
protected:
enum JobStatus {
NULL_STATUS = 0,
PROCESSING_STATUS = 2,
CANCEL_REQUEST_STATUS = 6,//the process accepted the cancel request
CANCELLED_STATUS = 7,
DONE_STATUS = 3,
PROCESSING_ERROR_STATUS = 8 //an error occured while processing
};
public:
virtual ~BaseStatusReporter () {
}
//returns true if user has requested that the job be cancelled
virtual bool hasUserCancelled() = 0;
//updates progress field in database, parameter is an int
//assuming a value of 0-100
virtual void setProgress( int inPercentDone ) = 0;
//call when processing starts on the job
virtual void setJobStarted() = 0;
//call once job was succesfully cancelled
virtual void setJobCancelled() = 0;
//call when job is completed
virtual void setJobDone() = 0;
//call when job is stopped because of error
virtual void setJobError(const Str&) = 0;
struct StatusException : public BaseException {
StatusException() {
}
StatusException( const Str &inErrString )
{
inErrString.getCString (_message);
}
~StatusException () throw () {
}
};
struct CancelledException : public StatusException {
~CancelledException () throw () {
}
};
};
//Aviad's Singleton Manager
struct StatusReportManager {
//
// setup the global reporter
static void setup (boost::shared_ptr <BaseStatusReporter> in)
{
_reporter = in;
}
static void setMaxProgress (int inMaxProgressPoints) {
_progressPoints = 0;
_maxProgressPoints = inMaxProgressPoints;
}
static boost::shared_ptr <BaseStatusReporter> getInstance () {
return _reporter;
}
//returns true if user has requested that the job be cancelled
static inline bool hasUserCancelled() {
return (_reporter)? _reporter->hasUserCancelled () : false;
}
//updates progress field in database, parameter is an int
//assuming a value of 0-100
static inline void setProgress( int inPercentDone) {
if (_reporter) _reporter->setProgress (inPercentDone);
}
static inline void setProgress() {
++_progressPoints;
if (_reporter) {
int percentDone = (100 * _progressPoints) / _maxProgressPoints;
_reporter->setProgress (percentDone);
}
}
//call when processing starts on the job
static inline void setJobStarted() {
if (_reporter) _reporter->setJobStarted ();
}
//call once job was succesfully cancelled
static inline void setJobCancelled() {
if (_reporter) _reporter->setJobCancelled ();
}
//call when job is completed
static inline void setJobDone() {
if (_reporter) _reporter->setJobDone ();
}
//call when job is completed
static inline void setJobError(const Str& s) {
if (_reporter) _reporter->setJobError (s);
}
struct Sentry {
Sentry ( int argc, char **argv, Argv &outArgv );
~Sentry () {
}
};
private:
static int _progressPoints;
static int _maxProgressPoints;
static boost::shared_ptr <BaseStatusReporter> _reporter;
};
#endif //__BASE_STATUS_REPORTER_H__
| [
"aviadr1@1f8b7f26-7806-0410-ba70-a23862d07478"
]
| [
[
[
1,
139
]
]
]
|
90657344a72e9061eb42502f7370229937f099e0 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEAudioRenderers/SE_OpenAL_Renderer/SEOpenALRendering/SEOpenALRenderer.cpp | cbdd1f8fb0b06670880a94f7014368adc41b5339 | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,894 | cpp | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// 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. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "SEOpenALRendererPCH.h"
#include "SEOpenALRenderer.h"
#include "SEOpenALResources.h"
#include "SEListener.h"
#include "SESound.h"
using namespace Swing;
SEWaveCatalog* SEOpenALRenderer::ms_pWaveCatalog = 0;
SE_IMPLEMENT_INITIALIZE(SEOpenALRenderer);
SE_IMPLEMENT_TERMINATE(SEOpenALRenderer);
//SE_REGISTER_INITIALIZE(SEOpenALRenderer);
//SE_REGISTER_TERMINATE(SEOpenALRenderer);
//----------------------------------------------------------------------------
void SEOpenALRenderer::Initialize()
{
ms_pWaveCatalog = SE_NEW SEWaveCatalog("Main");
SEWaveCatalog::SetActive(ms_pWaveCatalog);
}
//----------------------------------------------------------------------------
void SEOpenALRenderer::Terminate()
{
if( SEWaveCatalog::GetActive() == ms_pWaveCatalog )
{
SEWaveCatalog::SetActive(0);
}
SE_DELETE ms_pWaveCatalog;
}
//----------------------------------------------------------------------------
SEOpenALRenderer::SEOpenALRenderer()
{
}
//----------------------------------------------------------------------------
SEOpenALRenderer::~SEOpenALRenderer()
{
}
//----------------------------------------------------------------------------
void SEOpenALRenderer::InitializeState()
{
alDistanceModel(AL_INVERSE_DISTANCE);
}
//----------------------------------------------------------------------------
void SEOpenALRenderer::OnMasterGainChange()
{
SE_AL_BEGIN_DEBUG_ALAPI;
alListenerf(AL_GAIN, (ALfloat)m_pListener->GetMasterGain());
SE_AL_END_DEBUG_ALAPI;
}
//----------------------------------------------------------------------------
void SEOpenALRenderer::SetSoundParams(SEAudioResourceIdentifier* pID)
{
SESoundID* pResource = (SESoundID*)pID;
// 更新sound世界姿态.
SetSoundFrame(pResource->ID, m_pSound);
// 更新sound其他物理参数.
SE_AL_BEGIN_DEBUG_ALAPI;
alSourcef(pResource->ID, AL_PITCH, (ALfloat)m_pSound->Pitch);
alSourcef(pResource->ID, AL_GAIN, (ALfloat)m_pSound->Gain);
alSourcef(pResource->ID, AL_ROLLOFF_FACTOR,
(ALfloat)m_pSound->RollOffRate);
alSourcei(pResource->ID, AL_LOOPING, m_pSound->Looping);
SE_AL_END_DEBUG_ALAPI;
}
//----------------------------------------------------------------------------
void SEOpenALRenderer::SetSoundFrame(unsigned int uiID, SESound* pSound)
{
const SEVector3f& rPos = pSound->World.GetTranslate();
SEVector3f vec3fDir;
pSound->World.GetRotate().GetRow(2, vec3fDir);
SE_AL_BEGIN_DEBUG_ALAPI;
ALfloat afValue[3];
afValue[0] = rPos.X;
afValue[1] = rPos.Y;
afValue[2] = -rPos.Z;
alSourcefv(uiID, AL_POSITION, afValue);
afValue[0] = vec3fDir.X;
afValue[1] = vec3fDir.Y;
afValue[2] = -vec3fDir.Z;
alSourcefv(uiID, AL_DIRECTION, afValue);
SE_AL_END_DEBUG_ALAPI;
}
//---------------------------------------------------------------------------- | [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
108
]
]
]
|
931848d8878a97b284c95ebdb48fbe48ddab6c70 | 5927f0908f05d3f58fe0adf4d5d20c27a4756fbe | /examples/chrome/browser_shutdown.h | 3e70ee39ea9718b4d31000a42f9ace7be781b896 | []
| no_license | seasky013/x-framework | b5585505a184a7d00d229da8ab0f556ca0b4b883 | 575e29de5840ede157e0348987fa188b7205f54d | refs/heads/master | 2016-09-16T09:41:26.994686 | 2011-09-16T06:16:22 | 2011-09-16T06:16:22 | 41,719,436 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,585 | h |
#ifndef __browser_shutdown_h__
#define __browser_shutdown_h__
#pragma once
namespace browser_shutdown
{
enum ShutdownType
{
// an uninitialized value
NOT_VALID = 0,
// the last browser window was closed
WINDOW_CLOSE,
// user clicked on the Exit menu item
BROWSER_EXIT,
// windows is logging off or shutting down
END_SESSION
};
// Called when the browser starts shutting down so that we can measure shutdown
// time.
void OnShutdownStarting(ShutdownType type);
// Get the current shutdown type.
ShutdownType GetShutdownType();
// Invoked in two ways:
// . When the last browser has been deleted and the message loop has finished
// running.
// . When ChromeFrame::EndSession is invoked and we need to do cleanup.
// NOTE: in this case the message loop is still running, but will die soon
// after this returns.
void Shutdown();
// There are various situations where the browser process should continue to
// run after the last browser window has closed - the Mac always continues
// running until the user explicitly quits, and on Windows/Linux the application
// should not shutdown when the last browser window closes if there are any
// BackgroundContents running.
// When the user explicitly chooses to shutdown the app (via the "Exit" or
// "Quit" menu items) BrowserList will call SetTryingToQuit() to tell itself to
// initiate a shutdown when the last window closes.
// If the quit is aborted, then the flag should be reset.
// This is a low-level mutator; in general, don't call SetTryingToQuit(true),
// except from appropriate places in BrowserList. To quit, use usual means,
// e.g., using |chrome_browser_application_mac::Terminate()| on the Mac, or
// |BrowserList::CloseAllWindowsAndExit()| on other platforms. To stop quitting,
// use |chrome_browser_application_mac::CancelTerminate()| on the Mac; other
// platforms can call SetTryingToQuit(false) directly.
void SetTryingToQuit(bool quitting);
// General accessor.
bool IsTryingToQuit();
// This is true on X during an END_SESSION, when we can no longer depend
// on the X server to be running. As a result we don't explicitly close the
// browser windows, which can lead to conditions which would fail checks.
bool ShuttingDownWithoutClosingBrowsers();
} //namespace browser_shutdown
#endif //__browser_shutdown_h__ | [
"[email protected]"
]
| [
[
[
1,
65
]
]
]
|
545538e3b9805de3534dca56f5cf03ca2aad4226 | 188058ec6dbe8b1a74bf584ecfa7843be560d2e5 | /FLVCodec/DeviceGrapBuilder1.cpp | 75bbfee2e13ac1ad6c08fb72acfd65c2412f35f3 | []
| no_license | mason105/red5cpp | 636e82c660942e2b39c4bfebc63175c8539f7df0 | fcf1152cb0a31560af397f24a46b8402e854536e | refs/heads/master | 2021-01-10T07:21:31.412996 | 2007-08-23T06:29:17 | 2007-08-23T06:29:17 | 36,223,621 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 7,311 | cpp | // DeviceGrapBuilder1.cpp: implementation of the CDeviceGrapBuilder1 class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "DeviceGrapBuilder1.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CDeviceGrapBuilder1::CDeviceGrapBuilder1()
{
m_pDeviceFilter = NULL;
m_pEncoderFilter = NULL;
}
CDeviceGrapBuilder1::~CDeviceGrapBuilder1()
{
}
HRESULT CDeviceGrapBuilder1::AddCapturePinStream(IBaseFilter* p_device_filter,
const char *szPinName)
{
HRESULT hr = E_FAIL;
bool b_audio = false;
CDeviceGrapBuilder *p_sys = this;
int i = 0;
SampleCaptureFilter *p_capture_filter = NULL;
do {
CComPtr<IPin> ptmpPin;
if(FAILED((GetPin_ByName(p_device_filter, szPinName, &ptmpPin))))
{
if(FAILED((GetPin_ByName(p_device_filter, "²¶»ñ", &ptmpPin))))
break;
}
AM_MEDIA_TYPE media_types[MAX_MEDIA_TYPES];
size_t media_count =
EnumDeviceCaps( this, ptmpPin, b_audio ? p_sys->i_achroma: p_sys->i_chroma,
p_sys->i_width, p_sys->i_height,p_sys->f_fps,
p_sys->i_channels,
p_sys->i_samplespersec,
p_sys->i_bitspersample,
media_types, MAX_MEDIA_TYPES );
if(media_count == 0)
break;
bool b_stream_type = false;
for( i = 0; i < media_count; i++ )
{
if( media_types[i].majortype == MEDIATYPE_Stream )
{
b_stream_type = true;
break;
}
}
size_t mt_count = 0;
AM_MEDIA_TYPE *mt = NULL;
if( media_count > 0 )
{
mt = (AM_MEDIA_TYPE *)realloc( mt, sizeof(AM_MEDIA_TYPE) *
(mt_count + media_count) );
// Order and copy returned media types according to arbitrary
// fourcc priority
for( size_t c = 0; c < media_count; c++ )
{
int slot_priority =
GetFourCCPriority(GetFourCCFromMediaType(media_types[c]));
size_t slot_copy = c;
for( size_t d = c+1; d < media_count; d++ )
{
int priority =
GetFourCCPriority(GetFourCCFromMediaType(media_types[d]));
if( priority > slot_priority )
{
slot_priority = priority;
slot_copy = d;
}
}
if( slot_copy != c )
{
mt[c+mt_count] = media_types[slot_copy];
media_types[slot_copy] = media_types[c];
}
else
{
mt[c+mt_count] = media_types[c];
}
}
mt_count += media_count;
}
p_capture_filter =
new SampleCaptureFilter( this, mt, mt_count );
if(FAILED(AddFilter_Simple(NULL, (IBaseFilter**)&p_capture_filter)))
break;
{
CComPtr<IPin> ptmpPin1;
CComPtr<IPin> ptmpPin2;
if(FAILED((GetPin_ByName(p_device_filter, szPinName, &ptmpPin1))))
{
if(FAILED((GetPin_ByName(p_device_filter, "²¶»ñ", &ptmpPin1))))
break;
}
if(FAILED( GetPin_FirstDisconnected(p_capture_filter, PINDIR_INPUT, &ptmpPin2)))
break;
if(FAILED( ConnectPin_Simple(ptmpPin1, ptmpPin2)))
break;
}
CDShowStream dshow_stream;
dshow_stream.b_audio = false;
dshow_stream.i_SampleCount = 0;
dshow_stream.b_pts = false;
dshow_stream.p_es = 0;
dshow_stream.mt =
p_capture_filter->CustomGetPin()->CustomGetMediaType();
dshow_stream.i_fourcc = GetFourCCFromMediaType( dshow_stream.mt );
if( dshow_stream.i_fourcc )
{
if( dshow_stream.mt.majortype == MEDIATYPE_Video )
{
dshow_stream.header.video =
*(VIDEOINFOHEADER *)dshow_stream.mt.pbFormat;
ATLTRACE( "MEDIATYPE_Video" );
ATLTRACE( "selected video pin accepts format: %4.4s",
(char *)&dshow_stream.i_fourcc);
}
else if( dshow_stream.mt.majortype == MEDIATYPE_Audio )
{
dshow_stream.header.audio =
*(WAVEFORMATEX *)dshow_stream.mt.pbFormat;
ATLTRACE( "MEDIATYPE_Audio" );
ATLTRACE( "selected audio pin accepts format: %4.4s",
(char *)&dshow_stream.i_fourcc);
}
else if( dshow_stream.mt.majortype == MEDIATYPE_Stream )
{
ATLTRACE( "MEDIATYPE_Stream" );
ATLTRACE( "selected stream pin accepts format: %4.4s",
(char *)&dshow_stream.i_fourcc);
}
else
{
ATLTRACE( "unknown stream majortype" );
break;
}
/* Add directshow elementary stream to our list */
dshow_stream.p_device_filter = p_device_filter;
dshow_stream.p_capture_filter = p_capture_filter;
dshow_stream.p_encoder_filter = NULL;
pp_streams = (CDShowStream **)realloc( pp_streams,
sizeof(CDShowStream *) * (i_streams + 1) );
pp_streams[i_streams] = new CDShowStream;
*pp_streams[i_streams++] = dshow_stream;
return 0;
}
} while(false);
if(p_capture_filter)
{
RemoveFilter_Simple((IBaseFilter**)&p_capture_filter);
SAFE_RELEASE(p_capture_filter);
}
return hr;
}
HRESULT CDeviceGrapBuilder1::ApplyVideoConfig_Software_Pin(IAMStreamConfig* stream_config,
int width,
int height)
{
HRESULT hr =S_OK;
if(stream_config == NULL)
return hr;
int caps_count = 0, caps_size = 0;
bool bFlag = true;
BOOL bSetConfig = FALSE;
AM_MEDIA_TYPE* pmt = NULL;
VIDEO_STREAM_CONFIG_CAPS caps;
hr = stream_config->GetNumberOfCapabilities(&caps_count, &caps_size);
if(FAILED(hr) || caps_count == 0)
return hr;
for(int i = 0; i < caps_count; i ++)
{
hr = stream_config->GetStreamCaps(i, &pmt, (BYTE*)&caps);
if(FAILED(hr))
continue;
VIDEOINFOHEADER* format = (VIDEOINFOHEADER*)pmt->pbFormat;
if ( pmt->formattype != FORMAT_VideoInfo )
goto next_stream_caps;
bFlag = true;
if(format->AvgTimePerFrame !=(ULONGLONG)((double)10000000/f_fps))
bFlag = false;
if(width && format->bmiHeader.biWidth != width )
bFlag = false;
if(height && format->bmiHeader.biHeight != height)
bFlag = false;
if(bFlag)
{
hr = stream_config->SetFormat(pmt);
DeleteMediaType(pmt);
if(FAILED(hr))
goto next_stream_caps;
bSetConfig = TRUE;
break;
}
else
{
VIDEOINFOHEADER* format = (VIDEOINFOHEADER*)pmt->pbFormat;
format->AvgTimePerFrame=(ULONGLONG)((double)10000000/f_fps);
if(width)
format->bmiHeader.biWidth = width;
if(height)
format->bmiHeader.biHeight = height;
format->bmiHeader.biSizeImage = helper_GetBMISizeImage(format->bmiHeader);
/*format->rcSource.right = format->bmiHeader.biWidth;
format->rcSource.bottom = format->bmiHeader.biHeight;
format->rcTarget.right = format->bmiHeader.biWidth;
format->rcTarget.bottom= format->bmiHeader.biHeight;
format->dwBitRate = format->bmiHeader.biSizeImage * f_fps;*/
hr = stream_config->SetFormat(pmt);
if(SUCCEEDED(hr))
{
DeleteMediaType(pmt);
bSetConfig = TRUE;
break;
}
}
next_stream_caps:
DeleteMediaType(pmt);
}
return hr;
} | [
"soaris@46205fef-a337-0410-8429-7db05d171fc8"
]
| [
[
[
1,
253
]
]
]
|
47e2e9ee2b8ece2276840a4e0effc1812f42cac4 | b4d726a0321649f907923cc57323942a1e45915b | /CODE/NETWORK/multi_data.cpp | 3a73fb4c7215cbbfc2eabe8c179cbf310155ba0b | []
| 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 | 16,754 | 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/Network/multi_data.cpp $
* $Revision: 1.1.1.1 $
* $Date: 2004/08/13 22:47:42 $
* $Author: Spearhawk $
*
* $Log: multi_data.cpp,v $
* Revision 1.1.1.1 2004/08/13 22:47:42 Spearhawk
* no message
*
* Revision 1.1.1.1 2004/08/13 21:21:38 Darkhill
* no message
*
* Revision 2.4 2004/03/05 09:02:02 Goober5000
* Uber pass at reducing #includes
* --Goober5000
*
* Revision 2.3 2002/08/01 01:41:07 penguin
* The big include file move
*
* Revision 2.2 2002/07/22 01:22:25 penguin
* Linux port -- added NO_STANDALONE ifdefs
*
* Revision 2.1 2002/07/07 19:55:59 penguin
* Back-port to MSVC
*
* Revision 2.0 2002/06/03 04:02:26 penguin
* Warpcore CVS sync
*
* Revision 1.1 2002/05/02 18:03:11 mharris
* Initial checkin - converted filenames and includes to lower case
*
*
* 8 6/16/99 4:06p Dave
* New pilot info popup. Added new draw-bitmap-as-poly function.
*
* 7 1/21/99 2:06p Dave
* Final checkin for multiplayer testing.
*
* 6 1/14/99 6:06p Dave
* 100% full squad logo support for single player and multiplayer.
*
* 5 12/18/98 12:31p Johnson
* Fixed a bug where the server would not properly redistribute a data
* file that he already had to other players.
*
* 4 12/14/98 4:01p Dave
* Got multi_data stuff working well with new xfer stuff.
*
* 3 12/14/98 12:13p Dave
* Spiffed up xfer system a bit. Put in support for squad logo file xfer.
* Need to test now.
*
* 2 10/07/98 10:53a Dave
* Initial checkin.
*
* 1 10/07/98 10:50a Dave
*
* 19 6/13/98 3:18p Hoffoss
* NOX()ed out a bunch of strings that shouldn't be translated.
*
* 18 5/21/98 3:45a Sandeep
* Make sure file xfer sender side uses correct directory type.
*
* 17 5/17/98 6:32p Dave
* Make sure clients/servers aren't kicked out of the debriefing when team
* captains leave a game. Fixed chatbox off-by-one error. Fixed image
* xfer/pilot info popup stuff.
*
* 16 5/13/98 6:54p Dave
* More sophistication to PXO interface. Changed respawn checking so
* there's no window for desynchronization between the server and the
* clients.
*
* 15 4/30/98 4:53p John
* Restructured and cleaned up cfile code. Added capability to read off
* of CD-ROM drive and out of multiple pack files.
*
* 14 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.
*
* 13 4/16/98 1:55p Dave
* Removed unneeded Assert when processing chat packets. Fixed standalone
* sequencing bugs. Laid groundwork for join screen server status
* icons/text.
*
* 12 4/14/98 12:19p Dave
* Revised the pause system yet again. Seperated into its own module.
*
* 11 4/08/98 2:51p Dave
* Fixed pilot image xfer once again. Solidify team selection process in
* pre-briefing multiplayer.
*
* 10 4/04/98 4:22p Dave
* First rev of UDP reliable sockets is done. Seems to work well if not
* overly burdened.
*
* 9 3/30/98 6:27p Dave
* Put in a more official set of multiplayer options, including a system
* for distributing netplayer and netgame settings.
*
* 8 3/26/98 6:01p Dave
* Put in file checksumming routine in cfile. Made pilot pic xferring more
* robust. Cut header size of voice data packets in half. Put in
* restricted game host query system.
*
* 7 3/23/98 5:42p Dave
* Put in automatic xfer of pilot pic files. Changed multi_xfer system so
* that it can support multiplayer sends/received between client and
* server simultaneously.
*
* 6 3/21/98 7:14p Dave
* Fixed up standalone player slot switching. Made training missions not
* count towards player stats.
*
* 5 3/15/98 4:17p Dave
* Fixed oberver hud problems. Put in handy netplayer macros. Reduced size
* of network orientation matrices.
*
* 4 3/11/98 2:04p Dave
* Removed optimized build warnings.
*
* 3 2/20/98 4:43p Dave
* Finished support for multiplayer player data files. Split off
* multiplayer campaign functionality.
*
* 2 2/19/98 6:44p Dave
* Finished server getting data from players. Now need to rebroadcast the
* data.
*
* 1 2/19/98 6:21p Dave
* Player data file xfer module.
*
* $NoKeywords: $
*/
#include <time.h>
#include "network/multi.h"
#include "network/multi_data.h"
#include "network/multi_xfer.h"
#include "network/multiutil.h"
#include "playerman/player.h"
#include "cfile/cfile.h"
#include "globalincs/systemvars.h"
// -------------------------------------------------------------------------
// MULTI DATA DEFINES/VARS
//
#define MAX_MULTI_DATA 40
// player data struct
typedef struct np_data {
char filename[MAX_FILENAME_LEN+1]; // filename
ubyte status[MAX_PLAYERS]; // status for all players (0 == don't have it, 1 == have or sending, 2 == i sent it originally)
ushort player_id; // id of the player who sent the file
ubyte used; // in use or not
} np_data;
np_data Multi_data[MAX_MULTI_DATA];
time_t Multi_data_time = 0;
// -------------------------------------------------------------------------
// MULTI DATA FORWARD DECLARATIONS
//
// is the given filename for a "multi data" file (pcx, wav, etc)
int multi_data_is_data(char *filename);
// get a free np_data slot
int multi_data_get_free();
// server side - add a new file
int multi_data_add_new(char *filename, int player_index);
// maybe try and reload player squad logo bitmaps
void multi_data_maybe_reload();
// -------------------------------------------------------------------------
// MULTI DATA FUNCTIONS
//
// reset the data xfer system
void multi_data_reset()
{
int idx;
// clear out all used bits
for(idx=0; idx<MAX_MULTI_DATA; idx++){
Multi_data[idx].used = 0;
}
}
// handle a player join (clear out lists of files, etc)
void multi_data_handle_join(int player_index)
{
int idx;
// clear out his status for all files
for(idx=0;idx<MAX_MULTI_DATA;idx++){
Multi_data[idx].status[player_index] = 0;
}
}
// handle a player drop (essentially the same as multi_data_handle_join)
void multi_data_handle_drop(int player_index)
{
int idx;
// mark all files he sent as being unused
for(idx=0;idx<MAX_MULTI_DATA;idx++){
if(Multi_data[idx].player_id == Net_players[player_index].player_id){
Multi_data[idx].used = 0;
}
}
}
// do all sync related data stuff (server-side only)
void multi_data_do()
{
int idx, p_idx;
// only do this once a second
if((time(NULL) - Multi_data_time) < 1){
return;
}
// maybe try and reload player squad logo bitmaps
multi_data_maybe_reload();
// reset the time
Multi_data_time = time(NULL);
// if I'm the server
if(Net_player && (Net_player->flags & NETINFO_FLAG_AM_MASTER)){
// for all valid files
for(idx=0; idx<MAX_MULTI_DATA; idx++){
// a valid file that isn't currently xferring (ie, anything we've got completely on our hard drive)
if(Multi_data[idx].used && (multi_xfer_lookup(Multi_data[idx].filename) < 0)){
// send it to all players who need it
for(p_idx=0; p_idx<MAX_PLAYERS; p_idx++){
// if he doesn't have it
if((Net_player != &Net_players[p_idx]) && MULTI_CONNECTED(Net_players[p_idx]) && (Net_players[p_idx].reliable_socket != INVALID_SOCKET) && (Multi_data[idx].status[p_idx] == 0)){
// queue up the file to send to him, or at least try to
if(multi_xfer_send_file(Net_players[p_idx].reliable_socket, Multi_data[idx].filename, CF_TYPE_ANY, MULTI_XFER_FLAG_AUTODESTROY | MULTI_XFER_FLAG_QUEUE) < 0){
nprintf(("Network", "Failed to send data file! Trying again later...\n"));
} else {
// mark his status
Multi_data[idx].status[p_idx] = 1;
}
}
}
}
}
}
}
// handle an incoming xfer request from the xfer system
void multi_data_handle_incoming(int handle)
{
int player_index = -1;
PSNET_SOCKET_RELIABLE sock = INVALID_SOCKET;
char *fname;
// get the player who is sending us this file
sock = multi_xfer_get_sock(handle);
player_index = find_player_socket(sock);
// get the filename of the file
fname = multi_xfer_get_filename(handle);
if(fname == NULL){
nprintf(("Network", "Could not get file xfer filename! wacky...!\n"));
// kill the stream
multi_xfer_xor_flags(handle, MULTI_XFER_FLAG_REJECT);
return;
}
// if this is not a valid data file
if(!multi_data_is_data(fname)){
nprintf(("Network", "Not accepting xfer request because its not a valid data file!\n"));
// kill the stream
multi_xfer_xor_flags(handle, MULTI_XFER_FLAG_REJECT);
return;
}
// if we already have a copy of this file, abort the xfer
// Does file exist in \multidata?
if( cf_exist(fname, CF_TYPE_MULTI_CACHE) ){
nprintf(("Network", "Not accepting file xfer because a duplicate exists!\n"));
// kill the stream
multi_xfer_xor_flags(handle, MULTI_XFER_FLAG_REJECT);
// if we're the server, we still need to add it to the list though
if((Net_player->flags & NETINFO_FLAG_AM_MASTER) && (player_index >= 0)){
multi_data_add_new(fname, player_index);
}
return;
}
// if I'm the server of the game, do stuff a little differently
if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
if(player_index == -1){
nprintf(("Network", "Could not find player for incoming player data stream!\n"));
// kill the stream
multi_xfer_xor_flags(handle, MULTI_XFER_FLAG_REJECT);
return;
}
// attempt to add the file
if(!multi_data_add_new(fname, player_index)){
// kill the stream
multi_xfer_xor_flags(handle, MULTI_XFER_FLAG_REJECT);
return;
} else {
// force the file to go into the multi cache directory
multi_xfer_handle_force_dir(handle, CF_TYPE_MULTI_CACHE);
// mark it as autodestroy
multi_xfer_xor_flags(handle, MULTI_XFER_FLAG_AUTODESTROY);
}
}
// if i'm a client, this is an incoming file from the server
else {
// if i'm not accepting pilot pics, abort
if(!(Net_player->p_info.options.flags & MLO_FLAG_ACCEPT_PIX)){
nprintf(("Network", "Client not accepting files because we don't want 'em!\n"));
// kill the stream
multi_xfer_xor_flags(handle, MULTI_XFER_FLAG_REJECT);
return;
}
// set the xfer handle to autodestroy itself since we don't really want to have to manage all incoming pics
multi_xfer_xor_flags(handle, MULTI_XFER_FLAG_AUTODESTROY);
// force the file to go into the multi cache directory
multi_xfer_handle_force_dir(handle, CF_TYPE_MULTI_CACHE);
// begin receiving the file
nprintf(("Network", "Client receiving xfer handle %d\n",handle));
}
}
// send all my files as necessary
void multi_data_send_my_junk()
{
char *with_ext;
int bmap, w, h;
int ok_to_send = 1;
// pilot pic --------------------------------------------------------------
// verify that my pilot pic is valid
if(strlen(Net_player->player->image_filename)){
bmap = bm_load(Net_player->player->image_filename);
if(bmap == -1){
ok_to_send = 0;
}
// verify image dimensions
if(ok_to_send){
w = -1;
h = -1;
bm_get_info(bmap,&w,&h);
// release the bitmap
bm_release(bmap);
bmap = -1;
// if the dimensions are invalid, kill the filename
if((w != PLAYER_PILOT_PIC_W) || (h != PLAYER_PILOT_PIC_H)){
ok_to_send = 0;
}
}
} else {
ok_to_send = 0;
}
if(ok_to_send){
with_ext = cf_add_ext(Net_player->player->image_filename, NOX(".pcx"));
if(with_ext != NULL){
strcpy(Net_player->player->image_filename, with_ext);
}
// host should put his own pic file in the list now
if((Net_player->flags & NETINFO_FLAG_AM_MASTER) && !(Game_mode & GM_STANDALONE_SERVER) && (strlen(Net_player->player->image_filename) > 0)){
multi_data_add_new(Net_player->player->image_filename, MY_NET_PLAYER_NUM);
}
// otherwise clients should just queue up a send
else {
// add a file extension if necessary
multi_xfer_send_file(Net_player->reliable_socket, Net_player->player->image_filename, CF_TYPE_ANY, MULTI_XFER_FLAG_AUTODESTROY | MULTI_XFER_FLAG_QUEUE);
}
}
// squad logo --------------------------------------------------------------
// verify that my pilot pic is valid
ok_to_send = 1;
if(strlen(Net_player->player->squad_filename)){
bmap = bm_load(Net_player->player->squad_filename);
if(bmap == -1){
ok_to_send = 0;
}
if(ok_to_send){
// verify image dimensions
w = -1;
h = -1;
bm_get_info(bmap,&w,&h);
// release the bitmap
bm_release(bmap);
bmap = -1;
// if the dimensions are invalid, kill the filename
if((w != PLAYER_SQUAD_PIC_W) || (h != PLAYER_SQUAD_PIC_H)){
ok_to_send = 0;
}
}
} else {
ok_to_send = 0;
}
if(ok_to_send){
with_ext = cf_add_ext(Net_player->player->squad_filename, NOX(".pcx"));
if(with_ext != NULL){
strcpy(Net_player->player->squad_filename,with_ext);
}
// host should put his own pic file in the list now
if((Net_player->flags & NETINFO_FLAG_AM_MASTER) && !(Game_mode & GM_STANDALONE_SERVER) && (strlen(Net_player->player->squad_filename) > 0)){
multi_data_add_new(Net_player->player->squad_filename, MY_NET_PLAYER_NUM);
}
// otherwise clients should just queue up a send
else {
// add a file extension if necessary
multi_xfer_send_file(Net_player->reliable_socket, Net_player->player->squad_filename, CF_TYPE_ANY, MULTI_XFER_FLAG_AUTODESTROY | MULTI_XFER_FLAG_QUEUE);
}
}
}
// -------------------------------------------------------------------------
// MULTI DATA FORWARD DECLARATIONS
//
// is the give file xfer handle for a "multi data" file (pcx, wav, etc)
int multi_data_is_data(char *filename)
{
int len,idx;
Assert(filename != NULL);
// some kind of error
if(filename == NULL){
return 0;
}
// convert to lowercase
len = strlen(filename);
for(idx=0;idx<len;idx++){
filename[idx] = (char)tolower(filename[idx]);
}
// check to see if the extension is .pcx
if(strstr(filename, NOX(".pcx"))){
return 1;
}
// not a data file
return 0;
}
// get a free np_data slot
int multi_data_get_free()
{
int idx;
// find a free slot
for(idx=0; idx<MAX_MULTI_DATA; idx++){
if(!Multi_data[idx].used){
return idx;
}
}
// couldn't find one
return -1;
}
// server side - add a new file. return 1 on success
int multi_data_add_new(char *filename, int player_index)
{
int slot;
// try and get a free slot
slot = multi_data_get_free();
if(slot < 0){
nprintf(("Network", "Could not get free np_data slot! yikes!\n"));
return 0;
}
// if the netgame isn't flagged as accepting data files
if(!(Netgame.options.flags & MSO_FLAG_ACCEPT_PIX)){
nprintf(("Network", "Server not accepting pilot pic because we don't want 'em!\n"));
return 0;
}
// assign the data
memset(&Multi_data[slot], 0, sizeof(np_data)); // clear the slot out
strcpy(Multi_data[slot].filename, filename); // copy the filename
Multi_data[slot].used = 1; // set it as being in use
Multi_data[slot].player_id = Net_players[player_index].player_id; // player id of who's sending the file
Multi_data[slot].status[player_index] = 2; // mark his status appropriately
// success
return 1;
}
// maybe try and reload player squad logo bitmaps
void multi_data_maybe_reload()
{
int idx;
// go through all connected and try to reload their images if necessary
for(idx=0; idx<MAX_PLAYERS; idx++){
if(MULTI_CONNECTED(Net_players[idx]) && strlen(Net_players[idx].player->squad_filename) && (Net_players[idx].player->insignia_texture == -1)){
Net_players[idx].player->insignia_texture = bm_load_duplicate(Net_players[idx].player->squad_filename);
// if the bitmap loaded properly, lock it as a transparent texture
if(Net_players[idx].player->insignia_texture != -1){
bm_lock(Net_players[idx].player->insignia_texture, 16, BMP_TEX_XPARENT);
bm_unlock(Net_players[idx].player->insignia_texture);
}
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
556
]
]
]
|
291418777488ea97ae2752c71055b6e9ccc2ae6d | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/SimulatorQt/Util/qt/Win32/include/Qt/qabstractitemmodel.h | 65c5c0e274a3c2ab969939ec301c0018af9c40be | [
"BSD-2-Clause"
]
| permissive | pranet/bhuman2009fork | 14e473bd6e5d30af9f1745311d689723bfc5cfdb | 82c1bd4485ae24043aa720a3aa7cb3e605b1a329 | refs/heads/master | 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,828 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtCore module 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$
**
****************************************************************************/
#ifndef QABSTRACTITEMMODEL_H
#define QABSTRACTITEMMODEL_H
#include <QtCore/qvariant.h>
#include <QtCore/qobject.h>
#include <QtCore/qhash.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Core)
class QAbstractItemModel;
class QPersistentModelIndex;
class Q_CORE_EXPORT QModelIndex
{
friend class QAbstractItemModel;
friend class QProxyModel;
public:
inline QModelIndex() : r(-1), c(-1), p(0), m(0) {}
inline QModelIndex(const QModelIndex &other)
: r(other.r), c(other.c), p(other.p), m(other.m) {}
inline ~QModelIndex() { p = 0; m = 0; }
inline int row() const { return r; }
inline int column() const { return c; }
inline void *internalPointer() const { return p; }
inline qint64 internalId() const { return reinterpret_cast<qint64>(p); }
inline QModelIndex parent() const;
inline QModelIndex sibling(int row, int column) const;
inline QModelIndex child(int row, int column) const;
inline QVariant data(int role = Qt::DisplayRole) const;
inline Qt::ItemFlags flags() const;
inline const QAbstractItemModel *model() const { return m; }
inline bool isValid() const { return (r >= 0) && (c >= 0) && (m != 0); }
inline bool operator==(const QModelIndex &other) const
{ return (other.r == r) && (other.p == p) && (other.c == c) && (other.m == m); }
inline bool operator!=(const QModelIndex &other) const
{ return !(*this == other); }
inline bool operator<(const QModelIndex &other) const
{
if (r < other.r) return true;
if (r == other.r) {
if (c < other.c) return true;
if (c == other.c) {
if (p < other.p) return true;
if (p == other.p) return m < other.m;
}
}
return false; }
private:
inline QModelIndex(int row, int column, void *ptr, const QAbstractItemModel *model);
int r, c;
void *p;
const QAbstractItemModel *m;
};
Q_DECLARE_TYPEINFO(QModelIndex, Q_MOVABLE_TYPE);
#ifndef QT_NO_DEBUG_STREAM
Q_CORE_EXPORT QDebug operator<<(QDebug, const QModelIndex &);
#endif
class QPersistentModelIndexData;
class Q_CORE_EXPORT QPersistentModelIndex
{
public:
QPersistentModelIndex();
QPersistentModelIndex(const QModelIndex &index);
QPersistentModelIndex(const QPersistentModelIndex &other);
~QPersistentModelIndex();
bool operator<(const QPersistentModelIndex &other) const;
bool operator==(const QPersistentModelIndex &other) const;
inline bool operator!=(const QPersistentModelIndex &other) const
{ return !operator==(other); }
QPersistentModelIndex &operator=(const QPersistentModelIndex &other);
bool operator==(const QModelIndex &other) const;
bool operator!=(const QModelIndex &other) const;
QPersistentModelIndex &operator=(const QModelIndex &other);
operator const QModelIndex&() const;
int row() const;
int column() const;
void *internalPointer() const;
qint64 internalId() const;
QModelIndex parent() const;
QModelIndex sibling(int row, int column) const;
QModelIndex child(int row, int column) const;
QVariant data(int role = Qt::DisplayRole) const;
Qt::ItemFlags flags() const;
const QAbstractItemModel *model() const;
bool isValid() const;
private:
QPersistentModelIndexData *d;
friend uint qHash(const QPersistentModelIndex &);
#ifndef QT_NO_DEBUG_STREAM
friend Q_CORE_EXPORT QDebug operator<<(QDebug, const QPersistentModelIndex &);
#endif
};
Q_DECLARE_TYPEINFO(QPersistentModelIndex, Q_MOVABLE_TYPE);
inline uint qHash(const QPersistentModelIndex &index)
{ return qHash(index.d); }
#ifndef QT_NO_DEBUG_STREAM
Q_CORE_EXPORT QDebug operator<<(QDebug, const QPersistentModelIndex &);
#endif
template<typename T> class QList;
typedef QList<QModelIndex> QModelIndexList;
class QMimeData;
class QAbstractItemModelPrivate;
template <class Key, class T> class QMap;
class Q_CORE_EXPORT QAbstractItemModel : public QObject
{
Q_OBJECT
friend class QPersistentModelIndexData;
friend class QAbstractItemViewPrivate;
public:
explicit QAbstractItemModel(QObject *parent = 0);
virtual ~QAbstractItemModel();
bool hasIndex(int row, int column, const QModelIndex &parent = QModelIndex()) const;
virtual QModelIndex index(int row, int column,
const QModelIndex &parent = QModelIndex()) const = 0;
virtual QModelIndex parent(const QModelIndex &child) const = 0;
inline QModelIndex sibling(int row, int column, const QModelIndex &idx) const
{ return index(row, column, parent(idx)); }
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const = 0;
virtual int columnCount(const QModelIndex &parent = QModelIndex()) const = 0;
virtual bool hasChildren(const QModelIndex &parent = QModelIndex()) const;
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const = 0;
virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
virtual QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const;
virtual bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value,
int role = Qt::EditRole);
virtual QMap<int, QVariant> itemData(const QModelIndex &index) const;
virtual bool setItemData(const QModelIndex &index, const QMap<int, QVariant> &roles);
virtual QStringList mimeTypes() const;
virtual QMimeData *mimeData(const QModelIndexList &indexes) const;
virtual bool dropMimeData(const QMimeData *data, Qt::DropAction action,
int row, int column, const QModelIndex &parent);
virtual Qt::DropActions supportedDropActions() const;
Qt::DropActions supportedDragActions() const;
void setSupportedDragActions(Qt::DropActions);
virtual bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex());
virtual bool insertColumns(int column, int count, const QModelIndex &parent = QModelIndex());
virtual bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
virtual bool removeColumns(int column, int count, const QModelIndex &parent = QModelIndex());
inline bool insertRow(int row, const QModelIndex &parent = QModelIndex());
inline bool insertColumn(int column, const QModelIndex &parent = QModelIndex());
inline bool removeRow(int row, const QModelIndex &parent = QModelIndex());
inline bool removeColumn(int column, const QModelIndex &parent = QModelIndex());
virtual void fetchMore(const QModelIndex &parent);
virtual bool canFetchMore(const QModelIndex &parent) const;
virtual Qt::ItemFlags flags(const QModelIndex &index) const;
virtual void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
virtual QModelIndex buddy(const QModelIndex &index) const;
virtual QModelIndexList match(const QModelIndex &start, int role,
const QVariant &value, int hits = 1,
Qt::MatchFlags flags =
Qt::MatchFlags(Qt::MatchStartsWith|Qt::MatchWrap)) const;
virtual QSize span(const QModelIndex &index) const;
#ifdef Q_NO_USING_KEYWORD
inline QObject *parent() const { return QObject::parent(); }
#else
using QObject::parent;
#endif
Q_SIGNALS:
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
void headerDataChanged(Qt::Orientation orientation, int first, int last);
void layoutChanged();
void layoutAboutToBeChanged();
#if !defined(Q_MOC_RUN) && !defined(qdoc)
private: // can only be emitted by QAbstractItemModel
#endif
void rowsAboutToBeInserted(const QModelIndex &parent, int first, int last);
void rowsInserted(const QModelIndex &parent, int first, int last);
void rowsAboutToBeRemoved(const QModelIndex &parent, int first, int last);
void rowsRemoved(const QModelIndex &parent, int first, int last);
void columnsAboutToBeInserted(const QModelIndex &parent, int first, int last);
void columnsInserted(const QModelIndex &parent, int first, int last);
void columnsAboutToBeRemoved(const QModelIndex &parent, int first, int last);
void columnsRemoved(const QModelIndex &parent, int first, int last);
void modelAboutToBeReset();
void modelReset();
public Q_SLOTS:
virtual bool submit();
virtual void revert();
protected:
QAbstractItemModel(QAbstractItemModelPrivate &dd, QObject *parent = 0);
inline QModelIndex createIndex(int row, int column, void *data = 0) const;
inline QModelIndex createIndex(int row, int column, int id) const;
inline QModelIndex createIndex(int row, int column, quint32 id) const;
void encodeData(const QModelIndexList &indexes, QDataStream &stream) const;
bool decodeData(int row, int column, const QModelIndex &parent, QDataStream &stream);
void beginInsertRows(const QModelIndex &parent, int first, int last);
void endInsertRows();
void beginRemoveRows(const QModelIndex &parent, int first, int last);
void endRemoveRows();
void beginInsertColumns(const QModelIndex &parent, int first, int last);
void endInsertColumns();
void beginRemoveColumns(const QModelIndex &parent, int first, int last);
void endRemoveColumns();
void reset();
void changePersistentIndex(const QModelIndex &from, const QModelIndex &to);
void changePersistentIndexList(const QModelIndexList &from, const QModelIndexList &to);
QModelIndexList persistentIndexList() const;
private:
Q_DECLARE_PRIVATE(QAbstractItemModel)
Q_DISABLE_COPY(QAbstractItemModel)
};
inline bool QAbstractItemModel::insertRow(int arow, const QModelIndex &aparent)
{ return insertRows(arow, 1, aparent); }
inline bool QAbstractItemModel::insertColumn(int acolumn, const QModelIndex &aparent)
{ return insertColumns(acolumn, 1, aparent); }
inline bool QAbstractItemModel::removeRow(int arow, const QModelIndex &aparent)
{ return removeRows(arow, 1, aparent); }
inline bool QAbstractItemModel::removeColumn(int acolumn, const QModelIndex &aparent)
{ return removeColumns(acolumn, 1, aparent); }
inline QModelIndex QAbstractItemModel::createIndex(int arow, int acolumn, void *adata) const
{ return QModelIndex(arow, acolumn, adata, this); }
inline QModelIndex QAbstractItemModel::createIndex(int arow, int acolumn, int aid) const
#if defined(Q_CC_MSVC)
#pragma warning( push )
#pragma warning( disable : 4312 ) // avoid conversion warning on 64-bit
#endif
{ return QModelIndex(arow, acolumn, reinterpret_cast<void*>(aid), this); }
#if defined(Q_CC_MSVC)
#pragma warning( pop )
#endif
inline QModelIndex QAbstractItemModel::createIndex(int arow, int acolumn, quint32 aid) const
#if defined(Q_CC_MSVC)
#pragma warning( push )
#pragma warning( disable : 4312 ) // avoid conversion warning on 64-bit
#endif
{ return QModelIndex(arow, acolumn, reinterpret_cast<void*>(aid), this); }
#if defined(Q_CC_MSVC)
#pragma warning( pop )
#endif
class Q_CORE_EXPORT QAbstractTableModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit QAbstractTableModel(QObject *parent = 0);
~QAbstractTableModel();
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
bool dropMimeData(const QMimeData *data, Qt::DropAction action,
int row, int column, const QModelIndex &parent);
protected:
QAbstractTableModel(QAbstractItemModelPrivate &dd, QObject *parent);
private:
Q_DISABLE_COPY(QAbstractTableModel)
QModelIndex parent(const QModelIndex &child) const;
bool hasChildren(const QModelIndex &parent) const;
};
class Q_CORE_EXPORT QAbstractListModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit QAbstractListModel(QObject *parent = 0);
~QAbstractListModel();
QModelIndex index(int row, int column = 0, const QModelIndex &parent = QModelIndex()) const;
bool dropMimeData(const QMimeData *data, Qt::DropAction action,
int row, int column, const QModelIndex &parent);
protected:
QAbstractListModel(QAbstractItemModelPrivate &dd, QObject *parent);
private:
Q_DISABLE_COPY(QAbstractListModel)
QModelIndex parent(const QModelIndex &child) const;
int columnCount(const QModelIndex &parent) const;
bool hasChildren(const QModelIndex &parent) const;
};
// inline implementations
inline QModelIndex::QModelIndex(int arow, int acolumn, void *adata,
const QAbstractItemModel *amodel)
: r(arow), c(acolumn), p(adata), m(amodel) {}
inline QModelIndex QModelIndex::parent() const
{ return m ? m->parent(*this) : QModelIndex(); }
inline QModelIndex QModelIndex::sibling(int arow, int acolumn) const
{ return m ? (r == arow && c == acolumn) ? *this : m->index(arow, acolumn, m->parent(*this)) : QModelIndex(); }
inline QModelIndex QModelIndex::child(int arow, int acolumn) const
{ return m ? m->index(arow, acolumn, *this) : QModelIndex(); }
inline QVariant QModelIndex::data(int arole) const
{ return m ? m->data(*this, arole) : QVariant(); }
inline Qt::ItemFlags QModelIndex::flags() const
{ return m ? m->flags(*this) : Qt::ItemFlags(0); }
inline uint qHash(const QModelIndex &index)
{ return uint((index.row() << 4) + index.column() + index.internalId()); }
QT_END_NAMESPACE
QT_END_HEADER
#endif // QABSTRACTITEMMODEL_H
| [
"alon@rogue.(none)"
]
| [
[
[
1,
390
]
]
]
|
78bf1cd119759b2ef9b8d556bac1a10229296d73 | c82d009662b7b3da2707a577a3143066d128093a | /numeric/units/inches.h | c394b61732f15f56319f579927dabdf363a581a8 | []
| no_license | canilao/cpp_framework | 01a2c0787440d9fca64dbb0fb10c1175a4f7d198 | da5c612e8f15f6987be0c925f46e854b2e703d73 | refs/heads/master | 2021-01-10T13:26:39.376268 | 2011-02-04T16:26:26 | 2011-02-04T16:26:26 | 49,291,836 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,198 | h | /*******************************************************************************
\file inches.h
\brief Class declaration for a inch of length.
\note C Anilao 10/26/2006 Created.
*******************************************************************************/
#ifndef INCHES_H
#define INCHES_H
// General Dependancies.
#include "length.h"
namespace numeric
{
/*******************************************************************************
\class Class for a declaration for an inch.
\brief Concrete class for measurable length units.
*******************************************************************************/
class inches : public length
{
public:
// Constructor.
inches();
// Copy Constructor.
inches(const inches & origInches);
// Decimal number constructor.
inches(const double & decimalNumber);
// Base length number constructor.
inches(const length & origBaseLength);
// Destructor.
virtual ~inches();
// The child class must define this for conversions.
virtual double GetCoreUnitConversion() const;
};
/*******************************************************************************
\brief Constructor
\note C Anilao 10/26/2006 Created.
*******************************************************************************/
inline inches::inches()
{}
/*******************************************************************************
\brief Copy constructor
\note C Anilao 10/26/2006 Created.
*******************************************************************************/
inline inches::inches(const inches & origInches) : length(origInches)
{}
/*******************************************************************************
\brief Decimal constructor.
\note C Anilao 10/26/2006 Created.
*******************************************************************************/
inline inches::inches(const double & decimalNumber)
{
// Use our assignment operator to assign ourself.
SetData(decimalNumber * GetCoreUnitConversion());
}
/*******************************************************************************
\brief Base length constructor.
\note C Anilao 10/26/2006 Created.
*******************************************************************************/
inline inches::inches(const length & origBaseLength) : length(origBaseLength)
{}
/*******************************************************************************
\brief Destructor
\note C Anilao 10/26/2006 Created.
*******************************************************************************/
inline inches::~inches()
{}
/*******************************************************************************
\brief The child class must define this for conversions.
\note C Anilao 10/26/2006 Created.
*******************************************************************************/
inline double inches::GetCoreUnitConversion() const
{
// Return our conversion.
return CORE_UNITS_TO_ONE_INCH;
}
}
#endif
| [
"Chris@55e5c601-11dd-bd4b-a960-93a593583956"
]
| [
[
[
1,
116
]
]
]
|
28c74a5f4b1ae3d1e028b1e6cad995ee77e5ac2e | ce1b0d027c41f70bc4cfa13cb05f09bd4edaf6a2 | / edge2d --username [email protected]/include/EDGEGraphics.h | 0e37f505064fd31b1a81b6c06fc6007024e19e72 | []
| no_license | ratalaika/edge2d | 11189c41b166960d5d7d5dbcf9bfaf833a41c079 | 79470a0fa6e8f5ea255df1696da655145bbf83ff | refs/heads/master | 2021-01-10T04:59:22.495428 | 2010-02-19T13:45:03 | 2010-02-19T13:45:03 | 36,088,756 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,496 | h | /*
-----------------------------------------------------------------------------
This source file is part of EDGE
(A very object-oriented and plugin-based 2d game engine)
For the latest info, see http://edge2d.googlecode.com
Copyright (c) 2007-2008 The EDGE Team
Also see acknowledgements in Readme.html
This program 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 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 Lesser General Public License for more details.
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 EDGE_GRAPHICS_H
#define EDGE_GRAPHICS_H
#include "EdgeCompile.h"
#include "EdgeColor.h"
#include "EdgeWindow.h"
#include <string>
using std::string;
namespace Edge
{
class Window;
class Image;
/**
* RenderMode
*
*/
enum ERenderMode
{
RM_COLORADD = 1,
RM_COLORMUL = 0,
RM_ALPHABLEND = 2,
RM_ALPHAADD = 0,
RM_DEFAULT = RM_COLORMUL | RM_ALPHABLEND
};
/**
* Graphics
*
* The manager class which will contact with the low level graphics api
*/
class EDGE_EXPORT Graphics : public WindowListener
{
public:
/**
* Constructor
*
*/
Graphics() {}
/**
* Destructor
*
*/
virtual ~Graphics() {}
/**
* init function
*
*/
virtual bool initiate( Window *window, int width, int height,
bool bWindowed = true, int bits = 32) = 0;
/**
* release
*
*/
virtual void release() = 0;
/**
* reset the screen display mode.Donot call this function directly, instead you
* should call EdgeEngine::resetWindow function.
*
*/
virtual void reset( int width, int height, bool bWindowed = true, int bits = 32 ) {}
/**
* beginScene
*
* begin to render, when you use some 3d hardware graphics plugin, you must call this
* function before you render anything.
*/
virtual bool beginScene() = 0;
/**
* endScene
*
* it will end the rendering and present the whole scene
*/
virtual void endScene() = 0;
/**
* clear
*
* it will clear the screen
*/
virtual void clear( const Color &color ) = 0;
/**
* setRenderTarget
*
* when calling this function, everything will be rendered on the target
* until you call restoreScreenTarget
*/
virtual void setRenderTarget( Image *target ) = 0;
/**
* restoreScreenTarget
*
* when calling this function, everything will be rendered on the screen
*/
virtual void restoreScreenTarget() = 0;
/**
* renderLine
*
*/
virtual void renderLine( float x1, float y1, float x2, float y2, const Color &color = Color()) = 0;
/**
* renderRectangle
*
*/
virtual void renderRect( float left, float top, float right, float bottom, const Color &color = Color() ) = 0;
/**
* renderImage, you donot need to call this function to render an image,
* just call Image::render to render itself.
*
* this function is always called by an Image object.
*/
virtual void renderImage( const Image *image ) = 0;
/**
* renderText, you donot need to call this function to render texts, just call Font::render
*
*
*/
virtual void renderFont() {}
/**
* getType, identify this Grpahics plugin 's type, i.e : D3D8
*
*/
virtual string &getType() = 0;
/**
* getCustomData, custom data means, i.e, in D3D8Graphics, you can use this function
* to get the IDirect3DDevice object.
*
*/
virtual void getCustomData( const string &type, void *pOutData ) {}
/**
* add some special data
*
*/
virtual void addCustomData( const string &type, void *pInData ) {}
/**
* remove some special data
*
*/
virtual void removeCustomData( const string &type, void *pInData ) {}
};
}
#endif
| [
"[email protected]@539dfdeb-0f3d-0410-9ace-d34ff1985647"
]
| [
[
[
1,
186
]
]
]
|
ea82fea22cbefc01fb610edb104ea89979a369f4 | e02fa80eef98834bf8a042a09d7cb7fe6bf768ba | /TEST_MyGUI_Source/MyGUIEngine/include/MyGUI_MultiListFactory.h | 886bc233e1992d12fa28e0de99e34618063d910d | []
| no_license | MyGUI/mygui-historical | fcd3edede9f6cb694c544b402149abb68c538673 | 4886073fd4813de80c22eded0b2033a5ba7f425f | refs/heads/master | 2021-01-23T16:40:19.477150 | 2008-03-06T22:19:12 | 2008-03-06T22:19:12 | 22,805,225 | 2 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 821 | h | /*!
@file
@author Albert Semenov
@date 04/2008
@module
*/
#ifndef __MYGUI_MULTI_LIST_FACTORY_H__
#define __MYGUI_MULTI_LIST_FACTORY_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_WidgetFactoryInterface.h"
#include "MyGUI_WidgetDefines.h"
namespace MyGUI
{
namespace factory
{
class _MyGUIExport MultiListFactory : public WidgetFactoryInterface
{
public:
MultiListFactory();
~MultiListFactory();
// реализация интерфейса фабрики
const Ogre::String& getType();
WidgetPtr createWidget(const Ogre::String& _skin, const IntCoord& _coord, Align _align, CroppedRectanglePtr _parent, WidgetCreator * _creator, const Ogre::String& _name);
};
} // namespace factory
} // namespace MyGUI
#endif // __MYGUI_MULTI_LIST_FACTORY_H__
| [
"[email protected]"
]
| [
[
[
1,
34
]
]
]
|
e76627c4630b18c67f38a20413fd3b7618f91097 | 9324000ac1cb567bd4862547cbdccf0923446095 | /foliage/leaf_sound/leaf_sound.cpp | b008f0ebc95d81ef1adf58a95b748a6456bc6222 | []
| no_license | mguillemot/kamaku.foliage | cf63d49e1e5ddd7c30b75acfc1841028d109cba4 | 18c225346916e240bc19bf5570a8c414bbb4153b | refs/heads/master | 2016-08-03T20:09:17.929309 | 2007-09-04T18:15:17 | 2007-09-04T18:15:17 | 2,226,835 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,860 | cpp | #include <iostream>
#include <memory>
#include "leaf_sound.hpp"
Foliage::Sound *Foliage::SoundManager::_bg = NULL;
Foliage::Sound *Foliage::SoundManager::_sfx = NULL;
#ifdef __PPC__
#include <xac97_l.h>
#include <xparameters.h>
#include <xintc_l.h>
#include <xexception_l.h>
void Foliage::SoundManager::AC97_Callback(void *useless)
{
Uint32 sample_sfx, sample_bg, sample_mixed;
for (Sint32 i = 0; i < 256; i++)
{
sample_bg = (_bg != NULL) ? _bg->getNextSample() : 0;
sample_sfx = (_sfx != NULL) ? _sfx->getNextSample() : 0;
sample_mixed = mixSamples(sample_bg, sample_sfx);
XAC97_WriteFifo(XPAR_AUDIO_CODEC_BASEADDR, sample_mixed);
}
if (_bg != NULL && _bg->ended())
{
_bg = NULL;
}
if (_sfx != NULL && _sfx->ended())
{
_sfx = NULL;
}
}
void Foliage::SoundManager::init()
{
// hard reset & initialization
XAC97_HardReset(XPAR_AUDIO_CODEC_BASEADDR);
XAC97_InitAudio(XPAR_AUDIO_CODEC_BASEADDR, AC97_ANALOG_LOOPBACK);
XAC97_DisableInput(XPAR_AUDIO_CODEC_BASEADDR, AC97_MIC_INPUT);
XAC97_DisableInput(XPAR_AUDIO_CODEC_BASEADDR, AC97_LINE_INPUT);
XAC97_AwaitCodecReady(XPAR_AUDIO_CODEC_BASEADDR);
// volume settings
XAC97_WriteReg(XPAR_AUDIO_CODEC_BASEADDR, AC97_MasterVol, AC97_VOL_MAX);
XAC97_WriteReg(XPAR_AUDIO_CODEC_BASEADDR, AC97_AuxOutVol, AC97_VOL_MUTE);
XAC97_WriteReg(XPAR_AUDIO_CODEC_BASEADDR, AC97_MasterVolMono, AC97_VOL_MUTE);
XAC97_WriteReg(XPAR_AUDIO_CODEC_BASEADDR, AC97_PCBeepVol, AC97_VOL_MUTE);
XAC97_WriteReg(XPAR_AUDIO_CODEC_BASEADDR, AC97_PhoneInVol, AC97_VOL_MUTE);
XAC97_WriteReg(XPAR_AUDIO_CODEC_BASEADDR, AC97_MicVol, AC97_VOL_MUTE);
XAC97_WriteReg(XPAR_AUDIO_CODEC_BASEADDR, AC97_LineInVol, AC97_VOL_MUTE);
XAC97_WriteReg(XPAR_AUDIO_CODEC_BASEADDR, AC97_CDVol, AC97_VOL_MUTE);
XAC97_WriteReg(XPAR_AUDIO_CODEC_BASEADDR, AC97_VideoVol, AC97_VOL_MUTE);
XAC97_WriteReg(XPAR_AUDIO_CODEC_BASEADDR, AC97_AuxInVol, AC97_VOL_MUTE);
XAC97_WriteReg(XPAR_AUDIO_CODEC_BASEADDR, AC97_PCMOutVol, AC97_VOL_MAX);
XAC97_AwaitCodecReady(XPAR_AUDIO_CODEC_BASEADDR);
// VRA mode OFF
XAC97_WriteReg(XPAR_AUDIO_CODEC_BASEADDR, AC97_ExtendedAudioStat, 0);
// clear FIFOs
XAC97_ClearFifos(XPAR_AUDIO_CODEC_BASEADDR);
// interrupt
XIntc_RegisterHandler(XPAR_OPB_INTC_0_BASEADDR,
XPAR_OPB_INTC_0_AUDIO_CODEC_INTERRUPT_INTR,
(XInterruptHandler)Foliage::SoundManager::AC97_Callback,
NULL);
XAC97_mSetControl(XPAR_AUDIO_CODEC_BASEADDR, AC97_ENABLE_IN_FIFO_INTERRUPT);
std::cout << " * sound manager initialized" << std::endl;
}
void Foliage::SoundManager::disableSound()
{
XAC97_mSetControl(XPAR_AUDIO_CODEC_BASEADDR, 0);
std::cout << "LEAF_sound: sound disabled" << std::endl;
}
#else
SDL_AudioSpec Foliage::SoundManager::_audioSpec;
Uint32 mixbuffer[256];
void Foliage::SoundManager::SDL_Audio_Callback(void *userdata, Uint8 *stream, Sint32 len)
{
if (len != (_audioSpec.samples * 4))
{
std::cout << "Invalid audio callback buffer length: " << len << std::endl;
return;
}
Uint32 sample_sfx, sample_bg, sample_mixed;
Uint32 *buf = (Uint32 *)stream;
for (Sint32 i = 0; i < _audioSpec.samples; i++)
{
sample_bg = (_bg != NULL) ? _bg->getNextSample() : 0;
sample_sfx = (_sfx != NULL) ? _sfx->getNextSample() : 0;
sample_mixed = mixSamples(sample_bg, sample_sfx);
*(buf++) = sample_mixed;
}
if (_bg != NULL && _bg->ended())
{
_bg = NULL;
}
if (_sfx != NULL && _sfx->ended())
{
_sfx = NULL;
}
}
void Foliage::SoundManager::init()
{
_audioSpec.freq = 48000;
_audioSpec.format = AUDIO_S16SYS;
_audioSpec.channels = 2;
_audioSpec.samples = 2048;
_audioSpec.callback = SDL_Audio_Callback;
_audioSpec.userdata = NULL;
SDL_OpenAudio(&_audioSpec, NULL);
std::cout << " * sound manager initialized" << std::endl;
}
void Foliage::SoundManager::disableSound()
{
SDL_CloseAudio();
std::cout << "LEAF_sound: sound disabled" << std::endl;
}
#endif
Uint32 Foliage::SoundManager::mixSamples(const Uint32 sample_bg, const Uint32 sample_sfx)
{
Sint32 g1 = (Sint32)((Sint16)(sample_bg >> 16));
Sint32 d1 = (Sint32)((Sint16)(sample_bg & 0xffff));
Sint32 g2 = (Sint32)((Sint16)(sample_sfx >> 16));
Sint32 d2 = (Sint32)((Sint16)(sample_sfx & 0xffff));
Sint32 g = (g1 + g2) >> 1;
Sint32 d = (d1 + d2) >> 1;
/* (no bound check needed since samples are /2)
if (g > 32767)
{
g = 32767;
}
else if (g < -32768)
{
g = -32768;
}
if (d > 32767)
{
d = 32767;
}
else if (d < -32768)
{
d = -32768;
}
*/
Uint32 sample_mixed = ((Uint32)g << 16);
sample_mixed |= ((Uint32)d & 0xffff);
return sample_mixed;
}
void Foliage::SoundManager::playBg(Foliage::Sound *bg)
{
bg->rewind();
_bg = bg;
}
void Foliage::SoundManager::playSfx(Foliage::Sound *sfx)
{
sfx->rewind();
_sfx = sfx;
}
| [
"erhune@1bdb3d1c-df69-384c-996e-f7b9c3edbfcf",
"Erhune@1bdb3d1c-df69-384c-996e-f7b9c3edbfcf"
]
| [
[
[
1,
4
],
[
8,
8
],
[
14,
21
],
[
23,
79
],
[
81,
81
],
[
86,
86
],
[
109,
109
]
],
[
[
5,
7
],
[
9,
13
],
[
22,
22
],
[
80,
80
],
[
82,
85
],
[
87,
108
],
[
110,
172
]
]
]
|
775fd45da1856c86658d9f7e29091817c25a1824 | 14298a990afb4c8619eea10988f9c0854ec49d29 | /PowerBill四川电信专用版本/ibill_source/ThreadSubmitToDB.cpp | 7ecdd87d02f5d5c51ab458eadf2f27839032ee08 | []
| no_license | sridhar19091986/xmlconvertsql | 066344074e932e919a69b818d0038f3d612e6f17 | bbb5bbaecbb011420d701005e13efcd2265aa80e | refs/heads/master | 2021-01-21T17:45:45.658884 | 2011-05-30T12:53:29 | 2011-05-30T12:53:29 | 42,693,560 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 19,030 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "ThreadSubmitToDB.h"
#include <StrUtils.hpp>
#include "public.h"
#include "DBConfig.h"
#pragma package(smart_init)
//将话单提交到数据库
//---------------------------------------------------------------------------
// Important: Methods and properties of objects in VCL can only be
// used in a method called using Synchronize, for example:
//
// Synchronize(UpdateCaption);
//
// where UpdateCaption could look like:
//
// void __fastcall TThreadSubmitToDB::UpdateCaption()
// {
// Form1->Caption = "Updated in a thread";
// }
//---------------------------------------------------------------------------
__fastcall TThreadSubmitToDB::TThreadSubmitToDB(bool CreateSuspended)
: TThread(CreateSuspended)
{
ErrorMessage = "";
SQLCommandList = NULL;
MaxMessageLine = 20;
MaxError = "0";
}
//---------------------------------------------------------------------------
void __fastcall TThreadSubmitToDB::Execute()
{
//---- Place thread code here ----
switch(DBType)
{
case DB_ORACLE:
SubmitToOracle();
break;
case DB_SQLSERVER:
SubmitToSQLServer();
break;
case DB_MYSQL:
SubmitToMySQL();
break;
default:
break;
}
if(hWnd != NULL)
SendMessage(hWnd,MSG_THREAD_COMPLETED,(WPARAM)this,0);
}
bool __fastcall TThreadSubmitToDB::SubmitToMySQL()
{
SECURITY_ATTRIBUTES se = {0};
se.nLength = sizeof(se);
se.bInheritHandle = true;
se.lpSecurityDescriptor = NULL;
CreatePipe(&hReadPipe,&hWritePipe,&se,0);
STARTUPINFO si = {0};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE;
si.hStdOutput = hWritePipe;
si.hStdError = hWritePipe;
memset(&pi,sizeof(pi),0);
//AnsiString Text;
//mysqlimport -prl --fields-enclosed-by= --fields-terminated-by=,
// mysql --local c:\hdhd_test_bills1.tmp --user=root --port=3306 --password=root --host=127.0.0.1
AnsiString Command = ToolPath + " -prl --fields-enclosed-by= --fields-terminated-by=, "
+ DataBaseName + " --local " + TempFileName +
" --user=" + DBUserName + " --password=" + DBPassword + " --host=" + DBServer +
" --port=" + ServerPort;
MessageTextList->Add("执行命令:" + ToolPath + " -prl --fields-enclosed-by= --fields-terminated-by=, "
+ DataBaseName + " --local " + TempFileName +
" --user=" + DBUserName + " --password=******* --host=" + DBServer +
" --port=" + ServerPort);
if(SlentMode)
{
printf("%s\n","执行命令:" + ToolPath + " -prl --fields-enclosed-by= --fields-terminated-by=, "
+ DataBaseName + " " + TempFileName +
" --user=" + DBUserName + " --password=******* --host=" + DBServer +
" --port=" + ServerPort);
}
if(CreateProcess(NULL,Command.c_str(),&se,&se,true,NORMAL_PRIORITY_CLASS,NULL,WorkDir.c_str(),&si,&pi))
{
bool bContinue = CloseHandle(hWritePipe);
hWritePipe = NULL;
char chBuffer[1025];
unsigned long Bytesread;
AnsiString Text;
MessageTextList->Add("MySQL批量复制进程已启动,请等待...");
while(bContinue)
{
bContinue = ReadFile(hReadPipe,&chBuffer[0],1024,&Bytesread,NULL);
try
{
chBuffer[Bytesread] = 0;
if(strlen(&chBuffer[0]) > 0)
{
Text = chBuffer;
}
if(Text != ""&&UpperCase(MessageTextList->Text).Pos("RECORDS") < 1)
{
MessageTextList->Add(Text);
}
}
catch(...)
{
}
chBuffer[0] = 0;
}
WaitForSingleObject(pi.hProcess,INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
CloseHandle(hReadPipe);
pi.hProcess = NULL;
hReadPipe = NULL;
if(UpperCase(MessageTextList->Text).Pos("RECORDS") < 1)
{
ErrorMessage = "提交数据失败,请查看状态窗口中的出错信息.";
return false;
}
else
{
SendMessage(hWnd,MSG_SET_PROCESS_POS,TotalRecordCount,0);
int k = 0;
int n;
for(int n = MessageTextList->Count - 1;n > -1;n--)
{
Text = MessageTextList->Strings[n];
int pos = Text.Pos("Records: ");
if(pos > 0)
{
k = StrToIntEx(Text.SubString(pos + strlen("Records: "),Text.Length() - strlen("Records: ")).c_str());
if(TotalRecordCount - k > StrToInt(MaxError))
{
ErrorMessage = "提交的数据行数与转换的行数不一致,且差异超出了允许的错误范围(最多" + MaxError + ").转换的数据行数为:" +
IntToStr(TotalRecordCount) +
",实际提交的行数为:" + IntToStr(k) + ".";
}
break;
}
}
if(n == -1)
{
ErrorMessage = "找不到MySQLImport关键字(Records).导入失败.";
}
//如果导入成功,则继续执行SQL语句
if(ErrorMessage == "" && SQLCommandList != NULL)
{
for(int n = 0;n < SQLCommandList->Count;n++)
{
try
{
if(SlentMode)
{
printf("正在执行语句:%s\n",SQLCommandList->Strings[n]);
}
MessageTextList->Add("正在执行语句:" + SQLCommandList->Strings[n]);
ADOConnection->Execute(SQLCommandList->Strings[n]);
}
catch(...){}
}
}
try
{
MessageTextList->Add("*********************************数据提交报告*********************************");
MessageTextList->Add("完成时间:" + FormatDateTime("yyyy-mm-dd hh:nn:ss",Now()) + ".");
MessageTextList->Add("目标表:" + DestTableName);
MessageTextList->Add("临时文件:" + TempFileName);
MessageTextList->Add("共转换了" + IntToStr(TotalRecordCount) + "条记录,导入了" + IntToStr(k) + "条记录.");
}
catch(...)
{
}
return true;
}
}
else
{
CloseHandle(hWritePipe);
CloseHandle(hReadPipe);
ErrorMessage = "创建MySQLImport进程失败.请检查是否安装了MySQL客户端软件和ibill.ini中[ExternalTools]的MySQLImport是否配置正确.";
return false;
}
}
//---------------------------------------------------------------------------
#define BCP_KEY_WORD1 "合计送出: "
#define BCP_KEY_WORD2 "已复制了 "
#define BCP_KEY_WORD3 " 行。"
int __fastcall TThreadSubmitToDB::GetRowsForBCP(const AnsiString & Text)
{
int Result = -1;
int pos = StrRScan(Text.c_str(),BCP_KEY_WORD1);
if(pos > -1)
{
Result = StrToIntEx(Text.SubString(pos + strlen(BCP_KEY_WORD1) + 1,
Text.Length() - pos - strlen(BCP_KEY_WORD1) - 1).c_str());
}
return Result;
}
//---------------------------------------------------------------------------
bool __fastcall TThreadSubmitToDB::SubmitToSQLServer()
{
SECURITY_ATTRIBUTES se = {0};
se.nLength = sizeof(se);
se.bInheritHandle = true;
se.lpSecurityDescriptor = NULL;
CreatePipe(&hReadPipe,&hWritePipe,&se,0);
STARTUPINFO si = {0};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE;
si.hStdOutput = hWritePipe;
si.hStdError = hWritePipe;
memset(&pi,sizeof(pi),0);
//AnsiString Text;
//bcp pubs..hdhd_test_bills1 in c:\convert.tmp -Usa -Pwbzx9801 -S133.57.9.21 -fc:\convert.fmt
AnsiString Command =
ToolPath + " " + DataBaseName + ".." + DestTableName + " in " + TempFileName +
" -U" + DBUserName + " -P" + DBPassword + " -S" + DBServer +
" -f" + ExtractFilePath(TempFileName) + DestTableName + ".fmt" +
" -m" + MaxError;
MessageTextList->Add("执行命令:" + ToolPath + " " + DataBaseName + ".." + DestTableName + " in " + TempFileName +
" -U" + DBUserName + " -P******** -S" + DBServer +
" -f" + ExtractFilePath(TempFileName) + DestTableName + ".fmt" +
" -m" + MaxError);
if(SlentMode)
{
printf("%s\n","执行命令:" + ToolPath + " " + DataBaseName + ".." + DestTableName + " in " + TempFileName +
" -U" + DBUserName + " -P******** -S" + DBServer +
" -f" + ExtractFilePath(TempFileName) + DestTableName + ".fmt" +
" -m" + MaxError);
}
if(CreateProcess(NULL,Command.c_str(),&se,&se,true,NORMAL_PRIORITY_CLASS,NULL,WorkDir.c_str(),&si,&pi))
{
bool bContinue = CloseHandle(hWritePipe);
hWritePipe = NULL;
char chBuffer[2049];
unsigned long Bytesread;
AnsiString Text;
int pos = 0;
while(bContinue)
{
bContinue = ReadFile(hReadPipe,&chBuffer[0],2048,&Bytesread,NULL);
try
{
chBuffer[Bytesread] = 0;
if(strlen(&chBuffer[0]) > 0)
{
Text = chBuffer;
}
//MessageBox(0,Text.c_str(),"",MB_OK);
if(Text != "")
{
//if(MessageTextList->Count > MaxMessageLine)
// MessageTextList->Clear();
if(SlentMode)
printf("%s\n",Text);
MessageTextList->Add(Text);
}
pos = GetRowsForBCP(Text);
if(pos > -1)
{
SendMessage(hWnd,MSG_SET_PROCESS_POS,pos,0);
}
if(Text.Pos("时钟时间") > 0)
break;
}
catch(...)
{
}
chBuffer[0] = 0;
}
WaitForSingleObject(pi.hProcess,INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
CloseHandle(hReadPipe);
pi.hProcess = NULL;
hReadPipe = NULL;
if(UpperCase(MessageTextList->Text).Pos("ERROR") > 0)
{
ErrorMessage = "提交数据失败,请查看状态窗口中的出错信息.";
return false;
}
else
{
SendMessage(hWnd,MSG_SET_PROCESS_POS,TotalRecordCount,0);
int n;
for(n = MessageTextList->Count - 1;n > -1;n--)
{
Text = MessageTextList->Strings[n];
pos = Text.Pos(BCP_KEY_WORD2);
if(pos > 0)
{
pos = StrToIntEx(Text.SubString(pos + strlen(BCP_KEY_WORD2),Text.Length() - strlen(BCP_KEY_WORD2)).c_str());
if(TotalRecordCount - pos > StrToInt(MaxError))
{
ErrorMessage = "提交的数据行数与转换的行数不一致,且差异超出了允许的错误范围(最多" + MaxError + ").转换的数据行数为:" +
IntToStr(TotalRecordCount) +
",实际提交的行数为:" + IntToStr(pos) + ".";
}
break;
}
}
if(n == -1)
{
ErrorMessage = "找不到BCP关键字,导入失败.";
}
//如果导入成功,则继续执行SQL语句
if(ErrorMessage == "" && SQLCommandList != NULL)
{
for(int n = 0;n < SQLCommandList->Count;n++)
{
try
{
if(SlentMode)
{
printf("正在执行语句:%s\n",SQLCommandList->Strings[n]);
}
MessageTextList->Add("正在执行语句:" + SQLCommandList->Strings[n]);
ADOConnection->Execute(SQLCommandList->Strings[n]);
}
catch(...){}
}
}
try
{
MessageTextList->Add("*********************************数据提交报告*********************************");
MessageTextList->Add("完成时间:" + FormatDateTime("yyyy-mm-dd hh:nn:ss",Now()) + ".");
MessageTextList->Add("目标表:" + DestTableName);
MessageTextList->Add("临时文件:" + TempFileName);
MessageTextList->Add("共转换了" + IntToStr(TotalRecordCount) + "条记录,导入了" + IntToStr(pos) + "条记录.");
}
catch(...)
{
}
return true;
}
}
else
{
CloseHandle(hWritePipe);
CloseHandle(hReadPipe);
ErrorMessage = "创建BCP进程失败.请检查是否安装了SQLServer客户端软件和ibill.ini中[ExternalTools]的bcppath是否配置正确.";
return false;
}
}
//---------------------------------------------------------------------------
#define SQLLDR_KEY_WORD1 "达到提交点,逻辑记录计数"
int __fastcall TThreadSubmitToDB::GetRowsForSQLLDR(const AnsiString & Text)
{
int Result = -1;
if(Text.Pos(SQLLDR_KEY_WORD1) > 0)
{
Result = StrToIntEx(Text.SubString(strlen(SQLLDR_KEY_WORD1) + 1,Text.Length() - strlen(SQLLDR_KEY_WORD1) + 1).c_str());
}
return Result;
}
//---------------------------------------------------------------------------
bool __fastcall TThreadSubmitToDB::SubmitToOracle()
{
SECURITY_ATTRIBUTES se = {0};
se.nLength = sizeof(se);
se.bInheritHandle = true;
se.lpSecurityDescriptor = NULL;
CreatePipe(&hReadPipe,&hWritePipe,&se,0);
STARTUPINFO si = {0};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE;
si.hStdOutput = hWritePipe;
si.hStdError = hWritePipe;
memset(&pi,sizeof(pi),0);
if(CreateProcess(NULL,(ToolPath + " " + DBUserName + "/" + DBPassword + "@" + DBServer +
" control=\"" + TempFileName + "\" errors=" + MaxError).c_str(),&se,&se,true,NORMAL_PRIORITY_CLASS,NULL,WorkDir.c_str(),&si,&pi))
{
bool bContinue = CloseHandle(hWritePipe);
hWritePipe = NULL;
char chBuffer[2049];
unsigned long Bytesread;
AnsiString Text;
int pos = 0;
while(bContinue)
{
bContinue = ReadFile(hReadPipe,&chBuffer[0],2048,&Bytesread,NULL);
try
{
chBuffer[Bytesread] = 0;
if(strlen(&chBuffer[0]) > 0)
{
Text = chBuffer;
}
//Text = AnsiReplaceStr(AnsiReplaceStr(Text,"\r",""),"\n","");
if(Text != "")
{
if(MessageTextList->Count > MaxMessageLine)
MessageTextList->Clear();
if(SlentMode)
{
printf("%s\n",Text);
}
MessageTextList->Add(Text);
}
pos = GetRowsForSQLLDR(Text);
if(pos > -1)
{
SendMessage(hWnd,MSG_SET_PROCESS_POS,pos,0);
}
}
catch(...)
{
}
}
WaitForSingleObject(pi.hProcess,INFINITE);
CloseHandle(pi.hProcess);
pi.hProcess = NULL;
CloseHandle(pi.hThread);
CloseHandle(hReadPipe);
hReadPipe = NULL;
if(MessageTextList->Text.Pos("SQL*Loader-") > 0)
{
ErrorMessage = "提交数据失败,请查看状态窗口中的出错信息.";
return false;
}
else
{
int n;
AnsiString str;// = "逻辑记录计数";
/*for(n = MessageTextList->Count - 1;n > -1;n--)
{
Text = MessageTextList->Strings[n];
pos = Text.Pos(str);
if(pos > 0)
{
pos = StrToIntEx(Text.SubString(pos + str.Length(),Text.Length() - str.Length() + 1).c_str());
SendMessage(hWnd,MSG_SET_PROCESS_POS,pos,0);
if(pos != TotalRecordCount)
{
ErrorMessage = "提交的数据行数与转换的行数不一致.转换的数据行数为:" +
IntToStr(TotalRecordCount) + ",实际提交的行数为:" + IntToStr(pos) + ".";
}
break;
}
}
if(n == -1)
{
ErrorMessage = "找不到SQLLDR关键字.导入失败.";
}*/
//分析日志文件
TStringList * LogFile = new TStringList;
LogFile->LoadFromFile(ExtractFilePath(Application->ExeName) + DestTableName + ".log");
//if(LogFile->Pos("
str = "成功";
for(n = LogFile->Count - 1;n > -1;n--)
{
Text = LogFile->Strings[n];
int pos1 = Text.Pos(str);
if(pos1 > 0)
{
pos1 = StrToIntEx(Text.c_str());//Text.SubString(pos1 + str.Length(),Text.Length() - str.Length() + 1).c_str());
if(TotalRecordCount - pos1 > StrToInt(MaxError))
{
ErrorMessage = "共有" + IntToStr(TotalRecordCount) + "行需要导入,但实际上只载入了" + IntToStr(pos1) + "行.";
}
break;
}
}
if(n == -1)
{
ErrorMessage = "找不到SQLLDR关键字,无法分析日志.";
}
delete LogFile;
//如果导入成功,则继续执行SQL语句
if(ErrorMessage == "" && SQLCommandList != NULL)
{
for(int n = 0;n < SQLCommandList->Count;n++)
{
try
{
if(SlentMode)
{
printf("正在执行语句:%s\n",SQLCommandList->Strings[n]);
}
MessageTextList->Add("正在执行语句:" + SQLCommandList->Strings[n]);
ADOConnection->Execute(SQLCommandList->Strings[n]);
}
catch(...){}
}
}
//MessageTextList->Clear();
try
{
for(int n = 0;n < 10;n++)
{
try
{
MessageTextList->LoadFromFile(ExtractFilePath(Application->ExeName) + DestTableName + ".log");
break;
}
catch(...)
{
}
}
MessageTextList->Insert(0,"*********************************数据提交报告*********************************");
MessageTextList->Insert(1,"完成时间:" + FormatDateTime("yyyy-mm-dd hh:nn:ss",Now()) + ".");
MessageTextList->Insert(2,"目标表:" + DestTableName);
MessageTextList->Insert(3,"临时文件:" + TempFileName);
MessageTextList->Insert(4,"共转换了" + IntToStr(TotalRecordCount) + "条记录,导入了" + IntToStr(pos) + "条记录.");
MessageTextList->Insert(5,"以下是Oracle 的 SQLLDR 生成的报告:");
}
catch(...)
{
}
return true;
}
}
else
{
CloseHandle(hWritePipe);
CloseHandle(hReadPipe);
ErrorMessage = "创建SQLLDR进程失败.请检查是否安装了Oracle客户端软件和ibill.ini中[ExternalTools]的sqlldrpath是否配置正确.";
return false;
}
}
| [
"cn.wei.hp@e7bd78f4-57e5-8052-e4e7-673d445fef99"
]
| [
[
[
1,
534
]
]
]
|
8d70a80c3aa4f05fda1f4f010955d83bdc66cb42 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.2/bctestlocalizer/inc/bctestlocalizerview.h | e7972b700d34c58ea5a9fc0a52810a92cbb27c49 | []
| 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 | 2,017 | h | /*
* Copyright (c) 2006 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: BC Test for BCTestLocalizer API.
*
*/
#ifndef C_BCTESTLOCALIZERVIEW_H
#define C_BCTESTLOCALIZERVIEW_H
#include <aknview.h>
const TUid KBCTestLocalizerViewId = { 1 };
class CBCTestLocalizerContainer;
class CBCTestUtil;
/**
* Application UI class
*
* @lib bctestutil.lib
*/
class CBCTestLocalizerView : public CAknView
{
public: // Constructors and destructor
/**
* Symbian static 2nd constructor
*/
static CBCTestLocalizerView* NewL();
/**
* dtor
*/
virtual ~CBCTestLocalizerView();
public: // from CAknView
/**
* Return view Id.
*/
TUid Id() const;
/**
* From CAknView, HandleCommandL.
* @param aCommand Command to be handled.
*/
void HandleCommandL( TInt aCommand );
protected: // from CAknView
/**
* When view is activated, do something
*/
void DoActivateL( const TVwsViewId&, TUid, const TDesC8& );
/**
* When view is deactivated, do something
*/
void DoDeactivate();
private: // constructor
/**
* C++ default constructor
*/
CBCTestLocalizerView();
/**
* symbian 2nd ctor
*/
void ConstructL();
private: // data
/**
* pointor to the BC Test framework utility.
* own
*/
CBCTestUtil* iTestUtil;
/**
* pointor to the container.
* own
*/
CBCTestLocalizerContainer* iContainer;
};
#endif // C_BCTESTLOCALIZERVIEW_H
// End of File
| [
"none@none"
]
| [
[
[
1,
103
]
]
]
|
87ca090117a2fec54f86ca111e701a5e5b7c5747 | 1c7a59d0c11a63605e234e8d4b01365cc3ae1090 | /src/Data/Graph.cpp | 7b757796e4d174893aeb628324674f6f03cdb049 | []
| no_license | TomasHurban/3dsoftviz | 67cc0bec79778a8ba955df3e2403b8df486a14c3 | d94719599abedba86d449bbee6a6bc74333e37a1 | refs/heads/master | 2021-01-24T05:25:05.776927 | 2010-12-04T22:17:48 | 2010-12-04T22:17:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,088 | cpp | /*!
* Graph.cpp
* Projekt 3DVisual
*/
#include "Data/Graph.h"
#include "Data/GraphLayout.h"
Data::Graph::Graph(qlonglong graph_id, QString name, QSqlDatabase* conn, QMap<qlonglong,osg::ref_ptr<Data::Node> > *nodes, QMap<qlonglong,osg::ref_ptr<Data::Edge> > *edges,QMap<qlonglong,osg::ref_ptr<Data::Node> > *metaNodes, QMap<qlonglong,osg::ref_ptr<Data::Edge> > *metaEdges, QMap<qlonglong,Data::Type*> *types)
{
//tento konstruktor je uz zastaraly a neda sa realne pouzit - uzly musia mat priradeny graph, ktory sa prave vytvarat, rovnako edge, type, metatype (ten musi mat naviac aj layout, ktory opat musi mat graph)
this->inDB = false;
this->graph_id = graph_id;
this->name = name;
this->conn = conn;
/*foreach(qlonglong i, layouts.keys()) {
qDebug() << layouts.value(i)->toString();
}*/
this->nodes = nodes;
foreach(qlonglong i,nodes->keys()) {
this->nodesByType.insert(nodes->value(i)->getType()->getId(),nodes->value(i));
}
this->edges = edges;
foreach(qlonglong i,edges->keys()) {
this->edgesByType.insert(edges->value(i)->getType()->getId(),edges->value(i));
}
this->types = types;
this->metaEdges = metaEdges;
foreach(qlonglong i,metaEdges->keys()) {
this->metaEdgesByType.insert(metaEdges->value(i)->getType()->getId(),metaEdges->value(i));
}
this->metaNodes = metaNodes;
foreach(qlonglong i,metaNodes->keys()) {
this->metaNodesByType.insert(metaNodes->value(i)->getType()->getId(),metaNodes->value(i));
}
this->selectedLayout = NULL;
this->ele_id_counter = this->getMaxEleIdFromElements();
this->layout_id_counter = 0; //POZOR toto asi treba inak poriesit, teraz to predpoklada ze ziadne layouty nemame co je spravne, lenze bacha na metatypy, ktore layout mat musia !
this->frozen = false;
this->typesByName = new QMultiMap<QString, Data::Type*>();
if(this->types!=NULL && this->types->size()>0) {
foreach(qlonglong i, this->types->keys()) {
this->typesByName->insert(this->types->value(i)->getName(), this->types->value(i));
}
}
}
Data::Graph::Graph(qlonglong graph_id, QString name, qlonglong layout_id_counter, qlonglong ele_id_counter, QSqlDatabase* conn)
{
this->inDB = false;
this->graph_id = graph_id;
this->name = name;
this->ele_id_counter = ele_id_counter;
this->layout_id_counter = layout_id_counter;
this->conn = conn;
this->selectedLayout = NULL;
//pre Misa
this->nodes = new QMap<qlonglong,osg::ref_ptr<Data::Node> >();
this->edges = new QMap<qlonglong,osg::ref_ptr<Data::Edge> >();
this->types = new QMap<qlonglong,Data::Type*>();
this->metaEdges = new QMap<qlonglong,osg::ref_ptr<Data::Edge> >();
this->metaNodes = new QMap<qlonglong,osg::ref_ptr<Data::Node> >();
this->frozen = false;
this->typesByName = new QMultiMap<QString, Data::Type*>();
}
Data::Graph::~Graph(void)
{
//uvolnime vsetky Nodes, Edges, metaNodes, metaEdges... su cez osg::ref_ptr takze staci clearnut
this->nodes->clear();
delete this->nodes;
this->nodes = NULL;
this->metaNodes->clear();
delete this->metaNodes;
this->metaNodes = NULL;
this->edges->clear();
delete this->edges;
this->edges = NULL;
this->metaEdges->clear();
delete this->metaEdges;
this->metaEdges = NULL;
//tieto zatial iba vyprazdnime - tu bude treba spavit logiku, ktora deletne tie, ktore nie su v nodes, metanodes, metaedges, edges a types TODO!!!
//v zasade, ak nam funguje DB pripojenie, tak tu nebudu ziadne uzly ktore uz mame v nodes, edges, metanodes ... treba ich deletnut
//ak nam db nefunguje, tak uzly ktore su tu budu aj v nodes, metatypes, edges...
this->newTypes.clear();
this->newNodes.clear();
this->newEdges.clear();
this->metaEdgesByType.clear();
this->metaNodesByType.clear();
this->nodesByType.clear();
this->edgesByType.clear();
this->typesByName->clear();
delete this->typesByName;
this->typesByName = NULL;
//uvolnime types - treba iterovat a kazde jedno deletnut samostatne
QMap<qlonglong, Data::Type*>::iterator it = this->types->begin();
Data::Type* type;
while (it!=this->types->end()) {
type = it.value();
it = this->types->erase(it);
delete type;
type = NULL;
}
this->types->clear();
delete this->types;
this->types = NULL;
//uvolnime vsetky layouty
QMap<qlonglong, Data::GraphLayout*>::iterator it2 = this->layouts.begin();
Data::GraphLayout* l;
this->selectedLayout = NULL;
while (it2!=this->layouts.end()) {
l = it2.value();
it2 = this->layouts.erase(it2);
delete l;
l = NULL;
}
this->layouts.clear();
//DB konekcia sa deletovat nebude (kedze tu riesi Manager)
this->conn = NULL;
}
Data::GraphLayout* Data::Graph::addLayout(QString layout_name)
{
bool error;
if(this->layouts.isEmpty()) { //na zaciatok ak ziadne ine layouty nemame, sa pokusime nacitat layouty z DB
this->layouts = this->getLayouts(&error);
}
Data::GraphLayout* layout = Model::GraphLayoutDAO::addLayout(layout_name, this, this->conn);
if(layout==NULL && (this->conn==NULL || !this->conn->isOpen())) { //nepodarilo sa vytvorit GraphLayout - nejaky problem s pripojenim na DB;
//vytvorime si nahradny layout aby sme mohli bezat aj bez pripojenia k DB
layout = new Data::GraphLayout(this->incLayoutIdCounter(),this,layout_name,this->conn);
} else if(layout==NULL) { //nepodarilo sa vytvorit Layout, nejaky problem s pridavanim do DB
return NULL;
} else { //vytvorili sme si GraphLayout a je v DB
this->layout_id_counter = layout->getId(); //zvysenie counter ID layoutov (counter je pre pripad, ze by nam vypadlo spojenie ked sa budeme pokusat urobit novy layout)
}
this->layouts.insert(layout->getId(),layout);
return layout;
}
QMap<qlonglong, Data::GraphLayout*> Data::Graph::getLayouts(bool* error)
{
if(this->layouts.isEmpty()) { //ak ziadne layouty nemame, skusime ich nacitat z DB, ak uz nejake mame, tak sme tento krok uz vykonali
this->layouts = Model::GraphLayoutDAO::getLayouts(this, this->conn, error);
if(!this->layouts.isEmpty()) { //nastavime spravne layout_id_counter
QMapIterator<qlonglong, Data::GraphLayout*> i(this->layouts);
i.toBack();
if(i.hasPrevious()) {
this->layout_id_counter = i.previous().value()->getId();
}
}
}
return this->layouts;
}
bool Data::Graph::removeLayout(Data::GraphLayout* layout)
{
if(Model::GraphLayoutDAO::removeLayout(layout, this->conn) || !layout->isInDB()) {
//layout sa podarilo odstranit z DB alebo v DB vobec nebol -> odstranime vsetky MetaType, ktore patria danemu layout
if(layout==this->selectedLayout) this->selectLayout(NULL);
this->layouts.remove(layout->getId());
}
return false;
}
QString Data::Graph::setName(QString name)
{
QString newName = Model::GraphDAO::setName(name,this,this->conn);
if(newName!=NULL || (conn==NULL || !conn->isOpen())) { //nastavime nove meno ak sa nam ho podarilo nastavit v DB, alebo ak nemame vobec pripojenie k DB (pre offline verziu)
this->name = newName;
}
return this->name;
}
osg::ref_ptr<Data::Node> Data::Graph::addNode(QString name, Data::Type* type, osg::Vec3f position)
{
osg::ref_ptr<Data::Node> node = new Data::Node(this->incEleIdCounter(), name, type, this, position);
this->newNodes.insert(node->getId(),node);
if(type!=NULL && type->isMeta()) {
this->metaNodes->insert(node->getId(),node);
this->metaNodesByType.insert(type->getId(),node);
} else {
this->nodes->insert(node->getId(),node);
this->nodesByType.insert(type->getId(),node);
}
return node;
}
osg::ref_ptr<Data::Edge> Data::Graph::addEdge(QString name, osg::ref_ptr<Data::Node> srcNode, osg::ref_ptr<Data::Node> dstNode, Data::Type* type, bool isOriented)
{
if(isParralel(srcNode, dstNode))
{
//adding multi edge to graph
addMultiEdge(name, srcNode, dstNode, type, isOriented, NULL);
}
else
{
//adding single edge to graph
osg::ref_ptr<Data::Edge> edge = new Data::Edge(this->incEleIdCounter(), name, this, srcNode, dstNode, type, isOriented);
edge->linkNodes(&this->newEdges);
if((type!=NULL && type->isMeta()) || ((srcNode->getType()!=NULL && srcNode->getType()->isMeta()) || (dstNode->getType()!=NULL && dstNode->getType()->isMeta())))
{
//ak je type meta, alebo je meta jeden z uzlov (ma type meta)
edge->linkNodes(this->metaEdges);
this->metaEdgesByType.insert(type->getId(),edge);
} else
{
edge->linkNodes(this->edges);
}
return edge;
}
return NULL;
}
void Data::Graph::addMultiEdge(QString name, osg::ref_ptr<Data::Node> srcNode, osg::ref_ptr<Data::Node> dstNode, Data::Type* type, bool isOriented, osg::ref_ptr<Data::Edge> replacedSingleEdge)
{
Data::Type* mtype;
Data::Type* metype;
QList<Data::Type*> mtypes = getTypesByName(Data::GraphLayout::MULTI_NODE_TYPE);
if(mtypes.isEmpty())
{
//adding META_NODE_TYPE settings if necessary
QMap<QString, QString> *settings = new QMap<QString, QString>;
settings->insert("scale", "5");
settings->insert("textureFile", Util::ApplicationConfig::get()->getValue("Viewer.Textures.Node"));
settings->insert("color.R", "1");
settings->insert("color.G", "1");
settings->insert("color.B", "1");
settings->insert("color.A", "1");
mtype = this->addType(Data::GraphLayout::MULTI_NODE_TYPE, settings);
}
else
{
mtype = mtypes[0];
}
QList<Data::Type*> metypes = getTypesByName(Data::GraphLayout::MULTI_EDGE_TYPE);
if(mtypes.isEmpty())
{
//adding META_EDGE_TYPE settings if necessary
QMap<QString, QString> *settings = new QMap<QString, QString>;
settings->insert("scale", "Viewer.Textures.EdgeScale");
settings->insert("textureFile", Util::ApplicationConfig::get()->getValue("Viewer.Textures.Edge"));
settings->insert("color.R", "1");
settings->insert("color.G", "1");
settings->insert("color.B", "1");
settings->insert("color.A", "1");
metype = this->addType(Data::GraphLayout::MULTI_EDGE_TYPE, settings);
}
else
{
metype = metypes[0];
}
//adding MULTI edges w/ MULTI node
osg::ref_ptr<Data::Node> parallelNode = addNode("PNode", mtype);
osg::ref_ptr<Data::Edge> edge1 = new Data::Edge(this->incEleIdCounter(), name, this, srcNode, parallelNode, metype, isOriented);
edge1->linkNodes(this->edges);
this->edgesByType.insert(type->getId(),edge1);
osg::ref_ptr<Data::Edge> edge2 = new Data::Edge(this->incEleIdCounter(), name, this, parallelNode, dstNode, metype, isOriented);
edge2->linkNodes(this->edges);
this->edgesByType.insert(type->getId(),edge2);
if(replacedSingleEdge!= NULL)
{
removeEdge(replacedSingleEdge);
}
}
osg::ref_ptr<Data::Node> Data::Graph::getMultiEdgeNeighbour(osg::ref_ptr<Data::Edge> multiEdge)
{
osg::ref_ptr<Data::Node> multiNode = NULL;
if(multiEdge->getSrcNode()->getType()->getName()=="multiNode")
multiNode = multiEdge->getSrcNode();
if(multiEdge->getDstNode()->getType()->getName()=="multiNode")
multiNode = multiEdge->getDstNode();
if(multiNode == NULL)
return NULL;
QMap<qlonglong, osg::ref_ptr<Data::Edge> >::iterator i = multiNode->getEdges()->begin();
while (i != multiNode->getEdges()->end())
{
if((*i)->getId()!= multiEdge->getId())
{
if((*i)->getSrcNode()->getType()->getName()!= "multiNode")
{
return (*i)->getSrcNode();
}
else
{
return (*i)->getDstNode();
}
}
i++;
}
return NULL;
}
bool Data::Graph::isParralel(osg::ref_ptr<Data::Node> srcNode, osg::ref_ptr<Data::Node> dstNode)
{
QMap<qlonglong, osg::ref_ptr<Data::Edge> >::iterator i = srcNode->getEdges()->begin();
bool isMulti = false;
while (i != srcNode->getEdges()->end())
{
if ((srcNode->getId() == (*i)->getSrcNode()->getId() && dstNode->getId() == (*i)->getDstNode()->getId()) || (srcNode->getId() == (*i)->getDstNode()->getId() && dstNode->getId() == (*i)->getSrcNode()->getId()))
{
isMulti= true;
this->addMultiEdge((*i)->getName(), (*i)->getSrcNode(), (*i)->getDstNode(), (*i)->getType(), (*i)->isOriented(), (*i));
break;
}
else
{
osg::ref_ptr<Data::Node> neghbourNode = getMultiEdgeNeighbour((*i));
if(neghbourNode!= NULL && (neghbourNode->getId() == (*i)->getSrcNode()->getId() || neghbourNode->getId() == (*i)->getDstNode()->getId()))
{
isMulti= true;
break;
}
}
i++;
}
return isMulti;
}
Data::Type* Data::Graph::addType(QString name, QMap <QString, QString> *settings)
{
Data::Type* type = new Data::Type(this->incEleIdCounter(),name, this, settings);
this->newTypes.insert(type->getId(),type);
this->types->insert(type->getId(),type);
this->typesByName->insert(type->getName(),type);
return type;
}
Data::MetaType* Data::Graph::addMetaType(QString name, QMap <QString, QString> *settings)
{
if(this->selectedLayout == NULL) {
qDebug() << "[Data::Graph::addMetaType] Could not create MetaType. No GraphLayout selected.";
return NULL;
}
Data::MetaType* type = new Data::MetaType(this->incEleIdCounter(),name, this, this->selectedLayout, settings);
this->newTypes.insert(type->getId(),type);
this->types->insert(type->getId(),type);
this->typesByName->insert(type->getName(),type);
return type;
}
Data::GraphLayout* Data::Graph::selectLayout( Data::GraphLayout* layout )
{
if(layout==NULL || (layout!=NULL && layout->getGraph()!=NULL && layout->getGraph()==this)) {
if(this->selectedLayout!=layout) {
this->selectedLayout = layout;
QMap<qlonglong, Data::Type*>::iterator it = this->types->begin();
Data::Type* t;
while (it!=this->types->end()) {
t=it.value();
if(t->isMeta() && ((Data::MetaType* ) t)->getLayout()!=layout) {
it = this->types->erase(it);
this->newTypes.remove(t->getId());
delete t;
t = NULL;
} else it++;
}
}
}
return this->selectedLayout;
}
qlonglong Data::Graph::getMaxEleIdFromElements()
{
qlonglong max = 0;
if(this->nodes!=NULL && !this->nodes->isEmpty()) {
QMap<qlonglong, osg::ref_ptr<Data::Node> >::iterator iNodes = this->nodes->end();
iNodes--;
if(iNodes.key()>max) max = iNodes.key();
}
if(this->nodes!=NULL && !this->types->isEmpty()) {
QMap<qlonglong, Data::Type*>::iterator iTypes = this->types->end();
iTypes--;
if(iTypes.key()>max) max = iTypes.key();
}
if(this->nodes!=NULL && !this->edges->isEmpty()) {
QMap<qlonglong, osg::ref_ptr<Data::Edge> >::iterator iEdges = this->edges->end();
iEdges--;
if(iEdges.key()>max) max = iEdges.key();
}
if(this->nodes!=NULL && !this->metaNodes->isEmpty()) {
QMap<qlonglong, osg::ref_ptr<Data::Node> >::iterator iMetaNodes = this->metaNodes->end();
iMetaNodes--;
if(iMetaNodes.key()>max) max = iMetaNodes.key();
}
if(this->nodes!=NULL && !this->metaEdges->isEmpty()) {
QMap<qlonglong, osg::ref_ptr<Data::Edge> >::iterator iMetaEdges = this->metaEdges->end();
iMetaEdges--;
if(iMetaEdges.key()>max) max = iMetaEdges.key();
}
return max;
}
QString Data::Graph::toString() const
{
QString str;
QTextStream(&str) << "graph id:" << graph_id << " name:" << name << " max current ele ID:" << ele_id_counter;
return str;
}
QList<Data::Type*> Data::Graph::getTypesByName(QString name)
{
return this->typesByName->values(name);
}
Data::Type* Data::Graph::getNodeMetaType()
{
if(this->selectedLayout==NULL) return NULL;
if(this->selectedLayout->getMetaSetting(Data::GraphLayout::META_NODE_TYPE) == NULL)
{
QMap<QString, QString> *settings = new QMap<QString, QString>;
settings->insert("scale", Util::ApplicationConfig::get()->getValue("Viewer.Textures.DefaultNodeScale"));
settings->insert("textureFile", Util::ApplicationConfig::get()->getValue("Viewer.Textures.MetaNode"));
settings->insert("color.R", "0.8");
settings->insert("color.G", "0.1");
settings->insert("color.B", "0.1");
settings->insert("color.A", "0.8");
Data::MetaType* type = this->addMetaType(Data::GraphLayout::META_NODE_TYPE, settings);
this->selectedLayout->setMetaSetting(Data::GraphLayout::META_NODE_TYPE,QString::number(type->getId()));
return type;
} else {
qlonglong typeId = this->selectedLayout->getMetaSetting(Data::GraphLayout::META_NODE_TYPE).toLongLong();
if(this->types->contains(typeId)) return this->types->value(typeId);
return NULL;
}
}
Data::Type* Data::Graph::getNodeMultiType()
{
QMap<QString, QString> *settings = new QMap<QString, QString>;
settings->insert("scale", Util::ApplicationConfig::get()->getValue("Viewer.Textures.DefaultNodeScale"));
settings->insert("textureFile", Util::ApplicationConfig::get()->getValue("Viewer.Textures.MetaNode"));
settings->insert("color.R", "0.8");
settings->insert("color.G", "0.1");
settings->insert("color.B", "0.1");
settings->insert("color.A", "0.8");
Data::MetaType* type = this->addMetaType(Data::GraphLayout::MULTI_NODE_TYPE, settings);
//this->selectedLayout->setMetaSetting(Data::GraphLayout::META_NODE_TYPE,QString::number(type->getId()));
return type;
}
Data::Type* Data::Graph::getEdgeMetaType()
{
if(this->selectedLayout==NULL) return NULL;
if(this->selectedLayout->getMetaSetting(Data::GraphLayout::META_EDGE_TYPE)==NULL) {
Data::MetaType* type = this->addMetaType(Data::GraphLayout::META_EDGE_TYPE);
this->selectedLayout->setMetaSetting(Data::GraphLayout::META_EDGE_TYPE,QString::number(type->getId()));
return type;
} else {
qlonglong typeId = this->selectedLayout->getMetaSetting(Data::GraphLayout::META_EDGE_TYPE).toLongLong();
if(this->types->contains(typeId)) return this->types->value(typeId);
return NULL;
}
}
void Data::Graph::removeType( Data::Type* type )
{
if(type!=NULL && type->getGraph()==this) {
if(!type->isInDB() || Model::TypeDAO::removeType(type, this->conn)) {
this->types->remove(type->getId());
this->newTypes.remove(type->getId());
this->typesByName->remove(type->getName());
if(type->isMeta()) {
if(this->getNodeMetaType()==type) { //type je MetaTypom uzlov layoutu
this->selectedLayout->removeMetaSetting(Data::GraphLayout::META_NODE_TYPE);
}
if(this->getEdgeMetaType()==type) { //type je MetaTypom hran layoutu
this->selectedLayout->removeMetaSetting(Data::GraphLayout::META_EDGE_TYPE);
}
}
//vymazeme vsetky hrany resp. metahrany daneho typu
this->removeAllEdgesOfType(type);
//vymazeme vsetky uzly daneho typu
this->removeAllNodesOfType(type);
}
}
}
void Data::Graph::removeAllEdgesOfType(Data::Type* type )
{
QList<osg::ref_ptr<Data::Edge> > edgesToKill;
if(type->isMeta()) edgesToKill = this->metaEdgesByType.values(type->getId());
else edgesToKill = this->edgesByType.values(type->getId());
if(!edgesToKill.isEmpty()) {
for(qlonglong i=0;i<edgesToKill.size();i++) {
this->removeEdge(edgesToKill.at(i));
}
edgesToKill.clear();
}
}
void Data::Graph::removeAllNodesOfType( Data::Type* type )
{
QList<osg::ref_ptr<Data::Node> > nodesToKill;
if(type->isMeta()) nodesToKill = this->metaNodesByType.values(type->getId()); //vyberieme vsetky uzly daneho typu
else nodesToKill = this->nodesByType.values(type->getId());
if(!nodesToKill.isEmpty()) {
for(qlonglong i=0;i<nodesToKill.size();i++) { //prejdeme kazdy jeden uzol
this->removeNode(nodesToKill.at(i));
}
nodesToKill.clear();
}
}
void Data::Graph::removeEdge( osg::ref_ptr<Data::Edge> edge)
{
if(edge!=NULL && edge->getGraph()==this) {
if(!edge->isInDB() || Model::EdgeDAO::removeEdge(edge, this->conn)) {
this->edges->remove(edge->getId());
this->metaEdges->remove(edge->getId());
this->newEdges.remove(edge->getId());
this->edgesByType.remove(edge->getType()->getId(),edge);
this->metaEdgesByType.remove(edge->getType()->getId(),edge);
edge->unlinkNodes();
}
}
}
void Data::Graph::removeNode( osg::ref_ptr<Data::Node> node )
{
if(node!=NULL && node->getGraph()==this) {
if(!node->isInDB() || Model::NodeDAO::removeNode(node, this->conn)) {
this->nodes->remove(node->getId());
this->metaNodes->remove(node->getId());
this->newNodes.remove(node->getId());
this->nodesByType.remove(node->getType()->getId(),node);
this->metaNodesByType.remove(node->getType()->getId(),node);
node->removeAllEdges();
//zistime ci nahodou dany uzol nie je aj typom a osetrime specialny pripad ked uzol je sam sebe typom (v DB to znamena, ze uzol je ROOT uzlom/typom, teda uz nemoze mat ziaden iny typ)
if(this->types->contains(node->getId())) {
this->removeType(this->types->value(node->getId()));
}
}
}
}
| [
"kapec@genepool.(none)",
"[email protected]"
]
| [
[
[
1,
226
],
[
250,
250
],
[
309,
309
],
[
380,
511
],
[
528,
631
]
],
[
[
227,
249
],
[
251,
308
],
[
310,
379
],
[
512,
527
]
]
]
|
fe6364055474af139d0287b82496b2fc06fdbe96 | d76a67033e3abf492ff2f22d38fb80de804c4269 | /src/box2d/Contact.cpp | 52bb5eec3d5d87742403c8fd13421fc25c5eaa1a | [
"Zlib"
]
| permissive | truthwzl/lov8 | 869a6be317b7d963600f2f88edaefdf9b5996f2d | 579163941593bae481212148041e0db78270c21d | refs/heads/master | 2021-01-10T01:58:59.103256 | 2009-12-16T16:00:09 | 2009-12-16T16:00:09 | 36,340,451 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,138 | cpp | #include "Contact.h"
namespace love_box2d
{
Contact::Contact(const b2ContactPoint * point)
: point(*point)
{
}
Contact::~Contact()
{
}
int Contact::getPosition(lua_State * L)
{
love::luax_assert_argc(L, 0, 0);
lua_pushnumber(L, point.position.x);
lua_pushnumber(L, point.position.y);
return 2;
}
Vec2df Contact::getPosition() {
return point.position;
}
int Contact::getVelocity(lua_State * L)
{
love::luax_assert_argc(L, 0, 0);
lua_pushnumber(L, point.velocity.x);
lua_pushnumber(L, point.velocity.y);
return 2;
}
Vec2df Contact::getVelocity() {
return point.velocity;
}
int Contact::getNormal(lua_State * L)
{
love::luax_assert_argc(L, 0, 0);
lua_pushnumber(L, point.normal.x);
lua_pushnumber(L, point.normal.y);
return 2;
}
Vec2df Contact::getNormal() {
return point.normal;
}
float Contact::getSeparation() const
{
return point.separation;
}
float Contact::getFriction() const
{
return point.friction;
}
float Contact::getRestitution() const
{
return point.restitution;
}
} // love_box2d
| [
"m4rvin2005@8b5f54a0-8722-11de-9e21-49812d2d8162"
]
| [
[
[
1,
66
]
]
]
|
92817ae55ea2bb1f191a6a52f73d1a109f9fb324 | 028d79ad6dd6bb4114891b8f4840ef9f0e9d4a32 | /src/drivers/cabal.cpp | bb9e0f799e7ff86eb7dddaaa6a021582ba12be8e | []
| no_license | neonichu/iMame4All-for-iPad | 72f56710d2ed7458594838a5152e50c72c2fb67f | 4eb3d4ed2e5ccb5c606fcbcefcb7c5a662ace611 | refs/heads/master | 2020-04-21T07:26:37.595653 | 2011-11-26T12:21:56 | 2011-11-26T12:21:56 | 2,855,022 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,254 | cpp | #include "../vidhrdw/cabal.cpp"
/******************************************************************
Cabal Bootleg
(c)1998 Red Corp
driver by Carlos A. Lozano Baides
68000 + Z80
The original uses 2xYM3931 for sound
The bootleg uses YM2151 + 2xZ80 used as ADPCM players
MEMORY MAP
0x000000 - 0x03ffff ROM
0x040000 - 0x0437ff RAM
0x043800 - 0x0437ff VRAM (Sprites)
0x060000 - 0x0607ff VRAM (Tiles)
0x080000 - 0x0803ff VRAM (Background)
0x0A0000 - 0xA0000f Input Ports
0x0C0040 - 0x0c0040 Watchdog??
0x0C0080 - 0x0C0080 Watchdog??
0x0E0000 - 0x0E07ff COLORRAM (----BBBBGGGGRRRR)
0x0E8000 - 0x0E800f Output Ports/Input Ports
VRAM(Background)
0x80000 - 32 bytes (16 tiles)
0x80040 - 32 bytes (16 tiles)
0x80080 - 32 bytes (16 tiles)
0x800c0 - 32 bytes (16 tiles)
0x80100 - 32 bytes (16 tiles)
...
0x803c0 - 32 bytes (16 tiles)
VRAM(Tiles)
0x60000-0x607ff (1024 tiles 8x8 tiles, 2 bytes every tile)
VRAM(Sprites)
0x43800-0x43bff (128 sprites, 8 bytes every sprite)
COLORRAM(Colors)
0xe0000-0xe07ff (1024 colors, ----BBBBGGGGRRRR)
******************************************************************/
#include "driver.h"
#include "vidhrdw/generic.h"
#include "cpu/z80/z80.h"
static int cabal_sound_command1, cabal_sound_command2;
extern void cabal_vh_screenrefresh( struct osd_bitmap *bitmap, int fullrefresh );
static void cabal_init_machine( void ) {
cabal_sound_command1 = cabal_sound_command2 = 0xff;
}
static READ_HANDLER( cabal_background_r ){
return READ_WORD (&videoram[offset]);
}
static WRITE_HANDLER( cabal_background_w ){
int oldword = READ_WORD(&videoram[offset]);
int newword = COMBINE_WORD(oldword,data);
if( oldword != newword ){
WRITE_WORD(&videoram[offset],newword);
dirtybuffer[offset/2] = 1;
}
}
/******************************************************************************************/
static struct YM2151interface ym2151_interface =
{
1, /* 1 chip */
3579580, /* 3.58 MHZ ? */ /* 4 MHZ in raine */
{ YM3012_VOL(80,MIXER_PAN_LEFT,80,MIXER_PAN_RIGHT) },
{ 0 }
};
struct ADPCMinterface adpcm_interface =
{
2, /* total number of ADPCM decoders in the machine */
8000, /* playback frequency */
REGION_SOUND1, /* memory region where the samples come from */
0, /* initialization function */
{40,40}
};
static void cabal_play_adpcm( int channel, int which ){
if( which!=0xff ){
unsigned char *RAM = memory_region(REGION_SOUND1);
int offset = channel*0x10000;
int start, len;
which = which&0x7f;
if( which ){
which = which*2+0x100;
start = RAM[offset+which] + 256*RAM[offset+which+1];
len = (RAM[offset+start]*256 + RAM[offset+start+1])*2;
start+=2;
ADPCM_play( channel,offset+start,len );
}
}
}
static READ_HANDLER( cabal_coin_r ) {
static int coin = 0;
int val = readinputport( 3 );
if ( !( val & 0x04 ) ){
if ( coin == 0 ){
coin = 1;
return val;
}
} else {
coin = 0;
}
return val | 0x04;
}
static READ_HANDLER( cabal_io_r ) {
// logerror("INPUT a000[%02x] \n", offset);
switch (offset){
case 0x0: return readinputport(4) + (readinputport(5)<<8); /* DIPSW */
case 0x8: return 0xff + (readinputport(0)<<8);/* IN0 */
case 0x10: return readinputport(1) + (readinputport(2)<<8); /* IN1,IN2 */
default: return (0xffff);
}
}
static WRITE_HANDLER( cabal_sndcmd_w ) {
switch (offset) {
case 0x0:
cabal_sound_command1 = data;
cpu_cause_interrupt( 1, Z80_NMI_INT );
break;
case 0x2: /* ?? */
cabal_sound_command2 = data & 0xff;
break;
case 0x8: /* ?? */
break;
}
}
static struct MemoryReadAddress readmem_cpu[] = {
{ 0x00000, 0x3ffff, MRA_ROM },
{ 0x40000, 0x437ff, MRA_RAM },
{ 0x43c00, 0x4ffff, MRA_RAM },
{ 0x43800, 0x43bff, MRA_RAM },
{ 0x60000, 0x607ff, MRA_BANK1 }, /* text layer */
{ 0x80000, 0x801ff, cabal_background_r }, /* background layer */
{ 0x80200, 0x803ff, MRA_BANK2 },
{ 0xa0000, 0xa0012, cabal_io_r },
{ 0xe0000, 0xe07ff, paletteram_word_r },
{ 0xe8000, 0xe800f, cabal_coin_r },
{ -1 }
};
static struct MemoryWriteAddress writemem_cpu[] = {
{ 0x00000, 0x3ffff, MWA_ROM },
{ 0x40000, 0x437ff, MWA_RAM },
{ 0x43800, 0x43bff, MWA_RAM, &spriteram, &spriteram_size },
{ 0x43c00, 0x4ffff, MWA_RAM },
{ 0x60000, 0x607ff, MWA_BANK1, &colorram },
{ 0x80000, 0x801ff, cabal_background_w, &videoram, &videoram_size },
{ 0x80200, 0x803ff, MWA_BANK2 },
{ 0xc0040, 0xc0041, MWA_NOP }, /* ??? */
{ 0xc0080, 0xc0081, MWA_NOP }, /* ??? */
{ 0xe0000, 0xe07ff, paletteram_xxxxBBBBGGGGRRRR_word_w, &paletteram},
{ 0xe8000, 0xe800f, cabal_sndcmd_w },
{ -1 }
};
/*********************************************************************/
static READ_HANDLER( cabal_snd_r )
{
switch(offset){
case 0x08: return cabal_sound_command2;
case 0x0a: return cabal_sound_command1;
default: return(0xff);
}
}
static WRITE_HANDLER( cabal_snd_w )
{
switch( offset ){
case 0x00: cabal_play_adpcm( 0, data ); break;
case 0x02: cabal_play_adpcm( 1, data ); break;
}
}
static struct MemoryReadAddress readmem_sound[] =
{
{ 0x0000, 0x1fff, MRA_ROM },
{ 0x2000, 0x2fff, MRA_RAM },
{ 0x4000, 0x400d, cabal_snd_r },
{ 0x400f, 0x400f, YM2151_status_port_0_r },
{ 0x8000, 0xffff, MRA_ROM },
{ -1 }
};
static struct MemoryWriteAddress writemem_sound[] =
{
{ 0x0000, 0x1fff, MWA_ROM },
{ 0x2000, 0x2fff, MWA_RAM },
{ 0x4000, 0x400d, cabal_snd_w },
{ 0x400e, 0x400e, YM2151_register_port_0_w },
{ 0x400f, 0x400f, YM2151_data_port_0_w },
{ 0x6000, 0x6000, MWA_NOP }, /*???*/
{ 0x8000, 0xffff, MWA_ROM },
{ -1 }
};
static struct MemoryReadAddress cabalbl_readmem_sound[] =
{
{ 0x0000, 0x1fff, MRA_ROM },
{ 0x2000, 0x2fff, MRA_RAM },
{ 0x4000, 0x400d, cabal_snd_r },
{ 0x400f, 0x400f, YM2151_status_port_0_r },
{ 0x8000, 0xffff, MRA_ROM },
{ -1 }
};
static struct MemoryWriteAddress cabalbl_writemem_sound[] =
{
{ 0x0000, 0x1fff, MWA_ROM },
{ 0x2000, 0x2fff, MWA_RAM },
{ 0x4000, 0x400d, cabal_snd_w },
{ 0x400e, 0x400e, YM2151_register_port_0_w },
{ 0x400f, 0x400f, YM2151_data_port_0_w },
{ 0x6000, 0x6000, MWA_NOP }, /*???*/
{ 0x8000, 0xffff, MWA_ROM },
{ -1 }
};
/* ADPCM CPU (common) */
#if 0
static struct MemoryReadAddress cabalbl_readmem_adpcm[] = {
{ 0x0000, 0xffff, MRA_ROM },
{ -1 }
};
static struct MemoryWriteAddress cabalbl_writemem_adpcm[] = {
{ 0x0000, 0xffff, MWA_NOP },
{ -1 }
};
#endif
/***************************************************************************/
INPUT_PORTS_START( cabal )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER2 )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 )
PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN2 */
PORT_BIT( 0x0f, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_PLAYER2)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON3 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 )
PORT_START /* IN3 */
PORT_BIT( 0x03, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0xf8, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* DIPSW1 */
PORT_DIPNAME( 0x0f, 0x0e, DEF_STR( Coinage ) )
PORT_DIPSETTING( 0x0a, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x0b, "3 Coins/1 Credit 5/2" )
PORT_DIPSETTING( 0x0c, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x0d, "2 Coins/1 Credit 3/2" )
PORT_DIPSETTING( 0x01, DEF_STR( 4C_3C ) )
PORT_DIPSETTING( 0x0e, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x03, "2 Coins/2 Credits 3/4" )
PORT_DIPSETTING( 0x02, DEF_STR( 3C_3C ) )
PORT_DIPSETTING( 0x0f, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x04, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x09, DEF_STR( 1C_4C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 1C_6C ) )
PORT_DIPSETTING( 0x07, DEF_STR( 1C_8C ) )
PORT_DIPSETTING( 0x06, "1 Coin/10 Credits" )
PORT_DIPSETTING( 0x05, "1 Coin/12 Credits" )
PORT_DIPSETTING( 0x00, "Free 99 Credits" )
/* 0x10 is different from the Free 99 Credits.
When you start the game the credits decrease using the Free 99,
while they stay at 99 using the 0x10 dip. */
PORT_DIPNAME( 0x10, 0x10, DEF_STR( Free_Play ) )
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x20, 0x20, "Invert Buttons" )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x80, "Trackball" )
PORT_DIPSETTING( 0x80, "Small" )
PORT_DIPSETTING( 0x00, "Large" )
PORT_START /* DIPSW2 */
PORT_DIPNAME( 0x03, 0x03, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x02, "2" )
PORT_DIPSETTING( 0x03, "3" )
PORT_DIPSETTING( 0x01, "5" )
PORT_BITX( 0, 0x00, IPT_DIPSWITCH_SETTING | IPF_CHEAT, "Infinite", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x0c, "20k 50k" )
PORT_DIPSETTING( 0x08, "30k 100k" )
PORT_DIPSETTING( 0x04, "50k 150k" )
PORT_DIPSETTING( 0x00, "70K" )
PORT_DIPNAME( 0x30, 0x30, DEF_STR( Difficulty ) )
PORT_DIPSETTING( 0x30, "Easy" )
PORT_DIPSETTING( 0x20, "Normal" )
PORT_DIPSETTING( 0x10, "Hard" )
PORT_DIPSETTING( 0x00, "Very Hard" )
PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x80, DEF_STR( Demo_Sounds ) )
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x80, DEF_STR( On ) )
INPUT_PORTS_END
static struct GfxLayout text_layout =
{
8,8, /* 8*8 characters */
1024, /* 1024 characters */
2, /* 4 bits per pixel */
{ 0,4 },//0x4000*8+0, 0x4000*8+4, 0, 4 },
{ 3, 2, 1, 0, 8+3, 8+2, 8+1, 8+0},
{ 0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16 },
16*8 /* every char takes 16 consecutive bytes */
};
static struct GfxLayout tile_layout =
{
16,16, /* 16*16 tiles */
4*1024, /* 1024 tiles */
4, /* 4 bits per pixel */
{ 0, 4, 0x40000*8+0, 0x40000*8+4 },
{ 3, 2, 1, 0, 8+3, 8+2, 8+1, 8+0,
32*8+3, 32*8+2, 32*8+1, 32*8+0, 33*8+3, 33*8+2, 33*8+1, 33*8+0 },
{ 0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16,
8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16 },
64*8
};
static struct GfxLayout sprite_layout =
{
16,16, /* 16*16 sprites */
4*1024, /* 1024 sprites */
4, /* 4 bits per pixel */
{ 0, 4, 0x40000*8+0, 0x40000*8+4 }, /* the two bitplanes for 4 pixels are packed into one byte */
{ 3, 2, 1, 0, 8+3, 8+2, 8+1, 8+0,
16+3, 16+2, 16+1, 16+0, 24+3, 24+2, 24+1, 24+0 },
{ 30*16, 28*16, 26*16, 24*16, 22*16, 20*16, 18*16, 16*16,
14*16, 12*16, 10*16, 8*16, 6*16, 4*16, 2*16, 0*16 },
64*8 /* every sprite takes 64 consecutive bytes */
};
static struct GfxDecodeInfo cabal_gfxdecodeinfo[] = {
{ REGION_GFX1, 0, &text_layout, 0, 1024/4 },
{ REGION_GFX2, 0, &tile_layout, 32*16, 16 },
{ REGION_GFX3, 0, &sprite_layout, 16*16, 16 },
{ -1 }
};
static struct MachineDriver machine_driver_cabal =
{
{
{
CPU_M68000,
12000000, /* 12 Mhz */
readmem_cpu,writemem_cpu,0,0,
m68_level1_irq,1
},
{
CPU_Z80 | CPU_AUDIO_CPU,
4000000, /* 4 Mhz */
readmem_sound,writemem_sound,0,0,
interrupt,1
},
},
60, DEFAULT_REAL_60HZ_VBLANK_DURATION,
1, /* CPU slices per frame */
cabal_init_machine, /* init machine */
/* video hardware */
256, 256, { 0, 255, 16, 255-16 },
cabal_gfxdecodeinfo,
1024,1024,
0,
VIDEO_TYPE_RASTER | VIDEO_MODIFIES_PALETTE,
0,
generic_vh_start,
generic_vh_stop,
cabal_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
};
static struct MachineDriver machine_driver_cabalbl =
{
{
{
CPU_M68000,
12000000, /* 12 Mhz */
readmem_cpu,writemem_cpu,0,0,
m68_level1_irq,1
},
{
CPU_Z80 | CPU_AUDIO_CPU,
4000000, /* 4 Mhz */
cabalbl_readmem_sound,cabalbl_writemem_sound,0,0,
interrupt,1
},
},
60, DEFAULT_REAL_60HZ_VBLANK_DURATION,
10, /* CPU slices per frame */
cabal_init_machine, /* init machine */
/* video hardware */
256, 256, { 0, 255, 16, 255-16 },
cabal_gfxdecodeinfo,
1024,1024,
0,
VIDEO_TYPE_RASTER | VIDEO_MODIFIES_PALETTE,
0,
generic_vh_start,
generic_vh_stop,
cabal_vh_screenrefresh,
/* sound hardware */
SOUND_SUPPORTS_STEREO,0,0,0,
{
{
SOUND_YM2151,//_ALT,
&ym2151_interface
},
{
SOUND_ADPCM,
&adpcm_interface
}
}
};
ROM_START( cabal )
ROM_REGION( 0x50000, REGION_CPU1 ) /* 64k for cpu code */
ROM_LOAD_EVEN( "h7_512.bin", 0x00000, 0x10000, 0x8fe16fb4 )
ROM_LOAD_ODD ( "h6_512.bin", 0x00000, 0x10000, 0x6968101c )
ROM_LOAD_EVEN( "k7_512.bin", 0x20000, 0x10000, 0x562031a2 )
ROM_LOAD_ODD ( "k6_512.bin", 0x20000, 0x10000, 0x4fda2856 )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for sound cpu code */
ROM_LOAD( "4-3n", 0x0000, 0x2000, 0x4038eff2 )
ROM_LOAD( "3-3p", 0x8000, 0x8000, 0xd9defcbf )
ROM_REGION( 0x4000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "t6_128.bin", 0x00000, 0x04000, 0x1ccee214 ) /* characters */
/* the gfx ROMs were missing in this set, I'm using the ones from */
/* the bootleg */
ROM_REGION( 0x80000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "cabal_17.bin", 0x00000, 0x10000, 0x3b6d2b09 ) /* tiles, planes0,1 */
ROM_LOAD( "cabal_16.bin", 0x10000, 0x10000, 0x77bc7a60 )
ROM_LOAD( "cabal_18.bin", 0x20000, 0x10000, 0x0bc50075 )
ROM_LOAD( "cabal_19.bin", 0x30000, 0x10000, 0x67e4fe47 )
ROM_LOAD( "cabal_15.bin", 0x40000, 0x10000, 0x1023319b ) /* tiles, planes2,3 */
ROM_LOAD( "cabal_14.bin", 0x50000, 0x10000, 0x420b0801 )
ROM_LOAD( "cabal_12.bin", 0x60000, 0x10000, 0x543fcb37 )
ROM_LOAD( "cabal_13.bin", 0x70000, 0x10000, 0xd28d921e )
ROM_REGION( 0x80000, REGION_GFX3 | REGIONFLAG_DISPOSE )
ROM_LOAD( "cabal_05.bin", 0x00000, 0x10000, 0x4e49c28e ) /* sprites, planes0,1 */
ROM_LOAD( "cabal_06.bin", 0x10000, 0x10000, 0x6a0e739d )
ROM_LOAD( "cabal_07.bin", 0x20000, 0x10000, 0x581a50c1 )
ROM_LOAD( "cabal_08.bin", 0x30000, 0x10000, 0x702735c9 )
ROM_LOAD( "cabal_04.bin", 0x40000, 0x10000, 0x34d3cac8 ) /* sprites, planes2,3 */
ROM_LOAD( "cabal_03.bin", 0x50000, 0x10000, 0x7065e840 )
ROM_LOAD( "cabal_02.bin", 0x60000, 0x10000, 0x0e1ec30e )
ROM_LOAD( "cabal_01.bin", 0x70000, 0x10000, 0x55c44764 )
ROM_REGION( 0x20000, REGION_SOUND1 ) /* Samples? */
ROM_LOAD( "2-1s", 0x00000, 0x10000, 0x850406b4 )
ROM_LOAD( "1-1u", 0x10000, 0x10000, 0x8b3e0789 )
ROM_END
ROM_START( cabal2 )
ROM_REGION( 0x50000, REGION_CPU1 ) /* 64k for cpu code */
ROM_LOAD_EVEN( "9-7h", 0x00000, 0x10000, 0xebbb9484 )
ROM_LOAD_ODD ( "7-6h", 0x00000, 0x10000, 0x51aeb49e )
ROM_LOAD_EVEN( "8-7k", 0x20000, 0x10000, 0x4c24ed9a )
ROM_LOAD_ODD ( "6-6k", 0x20000, 0x10000, 0x681620e8 )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for sound cpu code */
ROM_LOAD( "4-3n", 0x0000, 0x2000, 0x4038eff2 )
ROM_LOAD( "3-3p", 0x8000, 0x8000, 0xd9defcbf )
ROM_REGION( 0x4000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "5-6s", 0x00000, 0x04000, 0x6a76955a ) /* characters */
/* the gfx ROMs were missing in this set, I'm using the ones from */
/* the bootleg */
ROM_REGION( 0x80000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "cabal_17.bin", 0x00000, 0x10000, 0x3b6d2b09 ) /* tiles, planes0,1 */
ROM_LOAD( "cabal_16.bin", 0x10000, 0x10000, 0x77bc7a60 )
ROM_LOAD( "cabal_18.bin", 0x20000, 0x10000, 0x0bc50075 )
ROM_LOAD( "cabal_19.bin", 0x30000, 0x10000, 0x67e4fe47 )
ROM_LOAD( "cabal_15.bin", 0x40000, 0x10000, 0x1023319b ) /* tiles, planes2,3 */
ROM_LOAD( "cabal_14.bin", 0x50000, 0x10000, 0x420b0801 )
ROM_LOAD( "cabal_12.bin", 0x60000, 0x10000, 0x543fcb37 )
ROM_LOAD( "cabal_13.bin", 0x70000, 0x10000, 0xd28d921e )
ROM_REGION( 0x80000, REGION_GFX3 | REGIONFLAG_DISPOSE )
ROM_LOAD( "cabal_05.bin", 0x00000, 0x10000, 0x4e49c28e ) /* sprites, planes0,1 */
ROM_LOAD( "cabal_06.bin", 0x10000, 0x10000, 0x6a0e739d )
ROM_LOAD( "cabal_07.bin", 0x20000, 0x10000, 0x581a50c1 )
ROM_LOAD( "cabal_08.bin", 0x30000, 0x10000, 0x702735c9 )
ROM_LOAD( "cabal_04.bin", 0x40000, 0x10000, 0x34d3cac8 ) /* sprites, planes2,3 */
ROM_LOAD( "cabal_03.bin", 0x50000, 0x10000, 0x7065e840 )
ROM_LOAD( "cabal_02.bin", 0x60000, 0x10000, 0x0e1ec30e )
ROM_LOAD( "cabal_01.bin", 0x70000, 0x10000, 0x55c44764 )
ROM_REGION( 0x20000, REGION_SOUND1 ) /* Samples? */
ROM_LOAD( "2-1s", 0x00000, 0x10000, 0x850406b4 )
ROM_LOAD( "1-1u", 0x10000, 0x10000, 0x8b3e0789 )
ROM_END
ROM_START( cabalbl )
ROM_REGION( 0x50000, REGION_CPU1 ) /* 64k for cpu code */
ROM_LOAD_EVEN( "cabal_24.bin", 0x00000, 0x10000, 0x00abbe0c )
ROM_LOAD_ODD ( "cabal_22.bin", 0x00000, 0x10000, 0x78c4af27 )
ROM_LOAD_EVEN( "cabal_23.bin", 0x20000, 0x10000, 0xd763a47c )
ROM_LOAD_ODD ( "cabal_21.bin", 0x20000, 0x10000, 0x96d5e8af )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for sound cpu code */
ROM_LOAD( "cabal_11.bin", 0x0000, 0x10000, 0xd308a543 )
ROM_REGION( 0x4000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "5-6s", 0x00000, 0x04000, 0x6a76955a ) /* characters */
ROM_REGION( 0x80000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "cabal_17.bin", 0x00000, 0x10000, 0x3b6d2b09 ) /* tiles, planes0,1 */
ROM_LOAD( "cabal_16.bin", 0x10000, 0x10000, 0x77bc7a60 )
ROM_LOAD( "cabal_18.bin", 0x20000, 0x10000, 0x0bc50075 )
ROM_LOAD( "cabal_19.bin", 0x30000, 0x10000, 0x67e4fe47 )
ROM_LOAD( "cabal_15.bin", 0x40000, 0x10000, 0x1023319b ) /* tiles, planes2,3 */
ROM_LOAD( "cabal_14.bin", 0x50000, 0x10000, 0x420b0801 )
ROM_LOAD( "cabal_12.bin", 0x60000, 0x10000, 0x543fcb37 )
ROM_LOAD( "cabal_13.bin", 0x70000, 0x10000, 0xd28d921e )
ROM_REGION( 0x80000, REGION_GFX3 | REGIONFLAG_DISPOSE )
ROM_LOAD( "cabal_05.bin", 0x00000, 0x10000, 0x4e49c28e ) /* sprites, planes0,1 */
ROM_LOAD( "cabal_06.bin", 0x10000, 0x10000, 0x6a0e739d )
ROM_LOAD( "cabal_07.bin", 0x20000, 0x10000, 0x581a50c1 )
ROM_LOAD( "cabal_08.bin", 0x30000, 0x10000, 0x702735c9 )
ROM_LOAD( "cabal_04.bin", 0x40000, 0x10000, 0x34d3cac8 ) /* sprites, planes2,3 */
ROM_LOAD( "cabal_03.bin", 0x50000, 0x10000, 0x7065e840 )
ROM_LOAD( "cabal_02.bin", 0x60000, 0x10000, 0x0e1ec30e )
ROM_LOAD( "cabal_01.bin", 0x70000, 0x10000, 0x55c44764 )
ROM_REGION( 0x20000, REGION_SOUND1 )
ROM_LOAD( "cabal_09.bin", 0x00000, 0x10000, 0x4ffa7fe3 ) /* Z80 code/adpcm data */
ROM_LOAD( "cabal_10.bin", 0x10000, 0x10000, 0x958789b6 ) /* Z80 code/adpcm data */
ROM_END
GAMEX( 1988, cabal, 0, cabal, cabal, 0, ROT0, "Tad (Fabtek license)", "Cabal (US set 1)", GAME_NOT_WORKING | GAME_IMPERFECT_SOUND | GAME_NO_COCKTAIL )
GAMEX( 1988, cabal2, cabal, cabal, cabal, 0, ROT0, "Tad (Fabtek license)", "Cabal (US set 2)", GAME_NOT_WORKING | GAME_IMPERFECT_SOUND | GAME_NO_COCKTAIL )
GAMEX( 1988, cabalbl, cabal, cabalbl, cabal, 0, ROT0, "bootleg", "Cabal (bootleg)", GAME_IMPERFECT_SOUND | GAME_NO_COCKTAIL )
| [
"[email protected]"
]
| [
[
[
1,
599
]
]
]
|
9a1b95db9a80b8bc6084ac50ffad8414608c6ea5 | 34d807d2bc616a23486af858647301af98b6296e | /ccbot/chatevent.cpp | da83fa57cd2aae9cd77f9eabd784eaa0a82e306d | [
"LicenseRef-scancode-warranty-disclaimer"
]
| no_license | Mofsy/ccbot | 65cf5bb08c211cdce2001a36db8968844fce2e05 | f171351c99cce4059a82a23399e7c4587f37beb5 | refs/heads/master | 2020-12-28T21:39:19.297873 | 2011-03-01T00:44:46 | 2011-03-01T00:44:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 49,830 | cpp | /*
Copyright [2009] [Joško Nikolić]
Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
HEAVILY MODIFIED PROJECT BASED ON GHOST++: http://forum.codelain.com
GHOST++ CODE IS PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/
*/
#include "ccbot.h"
#include "socket.h"
#include "util.h"
#include "language.h"
#include "ccbotdb.h"
#include "bnetprotocol.h"
#include "bnet.h"
#include <cstdio>
#include <cstdlib>
void CBNET :: ProcessChatEvent( CIncomingChatEvent *chatEvent )
{
CBNETProtocol :: IncomingChatEvent Event = chatEvent->GetChatEvent( );
string User = chatEvent->GetUser( ), lowerUser = chatEvent->GetUser( ), Message = chatEvent->GetMessage( );
transform( lowerUser.begin( ), lowerUser.end( ), lowerUser.begin( ), (int(*)(int))tolower );
unsigned char Access = m_CCBot->m_DB->AccessCheck( m_Server, lowerUser );
if( Access == 255 )
Access = 0;
bool Output = ( Event == CBNETProtocol :: CONSOLE_INPUT );
bool Whisper = ( Event == CBNETProtocol :: EID_WHISPER );
bool ClanMember = IsClanMember( m_UserName );
if( Event == CBNETProtocol :: EID_TALK )
CONSOLE_Print( "[LOCAL: " + m_ServerAlias + ":" + m_CurrentChannel + "][" + User + "] " + Message );
else if( Event == CBNETProtocol :: EID_WHISPER )
CONSOLE_Print( "[WHISPER: " + m_ServerAlias + "][" + User + "] " + Message );
else if( Event == CBNETProtocol :: EID_EMOTE )
CONSOLE_Print( "[EMOTE: " + m_ServerAlias + ":" + m_CurrentChannel + "][" + User + "] " + Message );
if( Event == CBNETProtocol :: EID_TALK || Event == CBNETProtocol :: EID_WHISPER || Event == CBNETProtocol :: EID_EMOTE || Event == CBNETProtocol :: CONSOLE_INPUT )
{
// Anti-Spam
// TODO: improve this to be more robust and efficient
if( m_AntiSpam && !Message.empty( ) && Message[0] != m_CommandTrigger[0] && Access < 5 && IsInChannel( User ) && User != m_UserName )
{
string message = Message;
transform( message.begin( ), message.end( ), message.begin( ), (int(*)(int))tolower );
uint32_t SpamCacheSize = m_Channel.size( ) * 3;
if( m_SpamCache.size( ) > SpamCacheSize )
m_SpamCache.erase( m_SpamCache.begin( ) );
m_SpamCache.insert( pair<string, string>( lowerUser, message ) );
int mesgmatches = 0, nickmatches = 0;
for( multimap<string, string> :: iterator i = m_SpamCache.begin( ); i != m_SpamCache.end( ); ++i )
{
if( (*i).first == lowerUser )
++nickmatches;
if( (*i).second.find( message ) )
++mesgmatches;
}
if( mesgmatches > 2 || nickmatches > 3 )
SendChatCommand( "/kick " + User + " Anti-Spam", Output );
}
// Swearing kick
if ( m_SwearingKick && !Message.empty( ) && !Match( User, m_HostbotName ) && !m_CCBot->m_DB->SafelistCheck( m_Server, User ) && IsInChannel( User ) && Access < 5 )
{
string message = Message;
transform( message.begin( ), message.end( ), message.begin( ), (int(*)(int))tolower );
for( uint32_t i = 0; i < m_CCBot->m_SwearList.size( ); ++i )
{
if( message.find( m_CCBot->m_SwearList[i] ) != string :: npos )
QueueChatCommand( m_CCBot->m_Language->SwearKick( User, m_CCBot->m_SwearList[i] ), Output );
}
}
// ?TRIGGER
if( Match( Message, "?trigger" ) )
{
QueueChatCommand( m_CCBot->m_Language->CommandTrigger( m_CommandTrigger ), User, Whisper, Output );
}
else if( !Message.empty( ) && Message[0] == m_CommandTrigger[0] && Event != CBNETProtocol :: EID_EMOTE )
{
// extract the command trigger, the command, and the payload
// e.g. "!say hello world" -> command: "say", payload: "hello world"
string Command, Payload;
string :: size_type PayloadStart = Message.find( " " );
if( PayloadStart != string :: npos )
{
Command = Message.substr( 1, PayloadStart - 1 );
Payload = Message.substr( PayloadStart + 1 );
}
else
Command = Message.substr( 1 );
transform( Command.begin( ), Command.end( ), Command.begin( ), (int(*)(int))tolower );
/********************************
************ COMMANDS ***********
********************************/
//
// !ACCEPT
//
if( Command == "accept" && Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "accept" ) && m_ActiveInvitation )
{
m_Socket->PutBytes( m_Protocol->SEND_SID_CLANINVITATIONRESPONSE( m_Protocol->GetClanTag( ), m_Protocol->GetInviter( ), true ) );
QueueChatCommand( m_CCBot->m_Language->InvitationAccepted( ), User, Whisper, Output );
SendGetClanList( );
m_ActiveInvitation = false;
}
//
// !ACCESS
//
else if( Command == "access" && Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "access" ) )
{
SendChatCommand( "/w " + User + " " + m_CCBot->m_Language->HasFollowingAccess( UTIL_ToString( Access ) ), Output );
for( unsigned char n = 0; n <= Access; ++n )
{
string Commands;
vector<string> m_CommandList = m_CCBot->m_DB->CommandList( n );
for( vector<string> :: iterator i = m_CommandList.begin( ); i != m_CommandList.end( ); ++i )
Commands = Commands + m_CommandTrigger + (*i) + ", ";
Commands = Commands.substr( 0, Commands.size( ) -2 );
if( m_CommandList.size ( ) )
SendChatCommand( "/w " + User + " [" + UTIL_ToString( n ) + "]: " + Commands, Output );
else
break;
}
}
//
// !ADDSAFELIST
// !ADDS
//
else if( ( Command == "addsafelist" || Command == "adds" ) && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "addsafelist" ) )
{
if( m_CCBot->m_DB->SafelistCheck( m_Server, Payload ) )
QueueChatCommand( m_CCBot->m_Language->UserAlreadySafelisted( Payload ), User, Whisper, Output );
else
{
if( m_CCBot->m_DB->SafelistAdd( m_Server, Payload ) )
QueueChatCommand( m_CCBot->m_Language->UserSafelisted( Payload ), User, Whisper, Output );
else
QueueChatCommand( m_CCBot->m_Language->ErrorSafelisting( Payload ), User, Whisper, Output );
}
}
//
// !ANNOUNCE
//
else if( Command == "announce" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "announce" ) )
{
string Interval, AnnounceMessage;
stringstream SS;
SS << Payload;
SS >> Interval;
if( !SS.eof( ) )
{
getline( SS, AnnounceMessage );
string :: size_type Start = AnnounceMessage.find_first_not_of( " " );
if( Start != string :: npos )
AnnounceMessage = AnnounceMessage.substr( Start );
}
if( ( UTIL_ToInt32( Interval ) > 0 ) && AnnounceMessage.size( ) )
{
m_Announce = true;
m_AnnounceMsg = AnnounceMessage;
m_AnnounceInterval = UTIL_ToInt32( Interval );
if( m_AnnounceInterval < 3 )
m_AnnounceInterval = 4;
QueueChatCommand( m_CCBot->m_Language->AnnounceEnabled( Interval ), User, Whisper, Output );
}
else if( Interval == "off" && m_Announce == true )
{
m_Announce = false;
QueueChatCommand( m_CCBot->m_Language->AnnounceDisabled( ), User, Whisper, Output );
}
}
//
// !BAN
// !ADDBAN
//
else if( ( Command == "ban" || Command == "addban" ) && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "ban" ) )
{
string Victim, Reason;
stringstream SS;
SS << Payload;
SS >> Victim;
unsigned char VictimAccess = m_CCBot->m_DB->AccessCheck( m_Server, Victim );
if( VictimAccess == 255 )
VictimAccess = 0;
if( Access >= VictimAccess && !IsClanShaman( Victim ) && !IsClanChieftain( Victim ) )
{
QueueChatCommand( "/ban " + Payload, false );
m_CCBot->m_DB->AccessSet( m_Server, Victim, 0 );
if( !SS.eof( ) )
{
getline( SS, Reason );
string :: size_type Start = Reason.find_first_not_of( " " );
if( Start != string :: npos )
Reason = Reason.substr( Start );
}
CDBBan *Ban = m_CCBot->m_DB->BanCheck( m_Server, Victim );
if( Ban )
{
QueueChatCommand( m_CCBot->m_Language->UserAlreadyBanned( Victim, Ban->GetAdmin( ) ), User, Whisper, Output );
delete Ban;
}
else
{
if( m_CCBot->m_DB->BanAdd( m_Server, Victim, User, Reason ) )
QueueChatCommand( m_CCBot->m_Language->SuccesfullyBanned( Victim, User ), User, Whisper, Output );
else
QueueChatCommand( m_CCBot->m_Language->ErrorBanningUser( Victim ), User, Whisper, Output );
}
}
else
QueueChatCommand( "Cannot ban higher clan ranks and people with higher access.", User, Whisper, Output );
}
//
// !CHECK
//
else if( Command == "check" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "checkban" ) )
{
CDBBan *Ban = m_CCBot->m_DB->BanCheck( m_Server, Payload );
unsigned char VictimAccess = m_CCBot->m_DB->AccessCheck( m_Server, Payload );
if( VictimAccess == 255 )
VictimAccess = 0;
if( IsClanMember( Payload ) )
{
if( IsClanPeon( Payload ) )
{
if( Ban )
QueueChatCommand( Payload + " is in clan, rank Peon, with [" + UTIL_ToString( VictimAccess ) + "] access and banned from channel.", User, Whisper, Output );
else
QueueChatCommand( Payload + " is in clan, rank Peon, with [" + UTIL_ToString( VictimAccess ) + "] access.", User, Whisper, Output );
}
else if( IsClanGrunt( Payload ) )
{
if( Ban )
QueueChatCommand( Payload + " is in clan, rank Grunt, with [" + UTIL_ToString( VictimAccess ) + "] access and is banned from channel.", User, Whisper, Output );
else
QueueChatCommand( Payload + " is in clan, rank Grunt with [" + UTIL_ToString( VictimAccess ) + "] access.", User, Whisper, Output );
}
else if( IsClanShaman( Payload ) )
QueueChatCommand( Payload + " is in clan, rank Shaman, with [" + UTIL_ToString( VictimAccess ) + "] access.", User, Whisper, Output );
else if( IsClanChieftain( Payload ) )
QueueChatCommand( Payload + " is in clan, rank Chieftain, with [" + UTIL_ToString( VictimAccess ) + "] access.", User, Whisper, Output );
}
else
{
if( !Ban )
QueueChatCommand( Payload + " is not a clan member and has [" + UTIL_ToString( VictimAccess ) + "] access.", User, Whisper, Output );
else
QueueChatCommand( Payload + " is banned from the channel, not a clan member and has [" + UTIL_ToString( VictimAccess ) + "] access.", User, Whisper, Output );
}
}
//
// !SETACCESS
//
else if( Command == "setaccess" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "setaccess" ) )
{
bool CanSetAccess = true;
// extract the username and the access which we are setting
// ie. !setaccess 8 Panda -> username "Panda" , access "8"
uint32_t Temp;
string UserName;
stringstream SS;
SS << Payload;
SS >> Temp;
if( SS.fail( ) || SS.eof( ) )
{
QueueChatCommand( "Bad input - use form " + m_CommandTrigger + "setaccess <access 0-10> <name>", User, Whisper, Output );
}
else
{
getline( SS, UserName );
string :: size_type Start = UserName.find_first_not_of( " " );
if( Start != string :: npos )
UserName = UserName.substr( Start );
unsigned char NewAccess = Temp, OldAccess = m_CCBot->m_DB->AccessCheck( m_Server, UserName );
if( NewAccess > 10 )
NewAccess = 10;
if( OldAccess == 255 )
OldAccess = 0;
if( Match( User, UserName ) && NewAccess > Access )
{
QueueChatCommand( "Cannot raise your own access.", User, Whisper, Output );
CanSetAccess = false;
}
if( NewAccess >= Access && !Match( UserName, User ) && NewAccess != 10 )
{
QueueChatCommand( "Cannot set access level higher or equal then your own.", User, Whisper, Output );
CanSetAccess = false;
}
if( OldAccess > NewAccess && !Match( UserName, User ) && OldAccess >= Access )
{
CanSetAccess = false;
QueueChatCommand( "Cannot set access level higher or equal then your own.", User, Whisper, Output );
}
if( OldAccess > Access && !Match( UserName, User ) )
{
CanSetAccess = false;
QueueChatCommand( "Cannot set access level higher or equal then your own.", User, Whisper, Output );
}
if( CanSetAccess )
{
if( m_CCBot->m_DB->AccessSet( m_Server, UserName, NewAccess ) )
QueueChatCommand( "Added user [" + UserName + "] with access of [" + UTIL_ToString( NewAccess ) + "]", User, Whisper, Output );
else
QueueChatCommand( "Error adding user [" + UserName + "] with access of [" + UTIL_ToString( NewAccess ) + "]", User, Whisper, Output );
}
}
}
//
// !CHECKACCESS
//
else if( Command == "checkaccess" && Access >= m_CCBot->m_DB->CommandAccess( "checkaccess" ) )
{
if( Payload.empty( ) )
Payload = User;
if( m_CCBot->m_DB->AccessCheck( m_Server, Payload ) != 255 )
QueueChatCommand( "User [" + Payload + "] has access of [" + UTIL_ToString( m_CCBot->m_DB->AccessCheck( m_Server, Payload ) ) + "].", User, Whisper, Output );
else
QueueChatCommand( "User [" + Payload + "] has access of [0].", User, Whisper, Output );
}
//
// !COUNTACCESS
//
else if( Command == "countaccess" && Access >= m_CCBot->m_DB->CommandAccess( "countaccess" ) )
{
if( Payload.empty( ) )
Payload = "0";
else if( UTIL_ToInt32( Payload ) > 10 )
Payload = "10";
uint32_t Count = m_CCBot->m_DB->AccessCount( m_Server, UTIL_ToInt32( Payload ) );
if( Count == 0 )
QueueChatCommand( "There are no users with access of [" + Payload + "]", User, Whisper, Output );
else if( Count == 1 )
QueueChatCommand( "There is only one user with access of [" + Payload + "]", User, Whisper, Output );
else
QueueChatCommand( "There are [" + UTIL_ToString( Count ) + "] users with access [" + Payload + "]", User, Whisper, Output );
}
//
// !DELACCESS
//
else if( Command == "delaccess" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "delaccess" ) )
{
if( !m_CCBot->m_DB->AccessCheck( m_Server, Payload ) )
QueueChatCommand( "User has no set access.", User, Whisper, Output );
else
{
if( m_CCBot->m_DB->AccessRemove( Payload ) )
QueueChatCommand( "Deleted user [" + Payload + "]'s set access." , User, Whisper, Output );
else
QueueChatCommand( "Error deleting user [" + Payload + "]'s access.", User, Whisper, Output );
}
}
//
// !CHECKSAFELIST
// !CHECKS
//
if( ( Command == "checksafelist" || Command == "checks" ) && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "checksafelist" ) )
{
if( m_CCBot->m_DB->SafelistCheck( m_Server, Payload ) )
QueueChatCommand( m_CCBot->m_Language->UserIsSafelisted( Payload ), User, Whisper, Output );
else
QueueChatCommand( m_CCBot->m_Language->UserNotSafelisted( Payload ), User, Whisper, Output );
}
//
// !COMMAND
//
else if( Command == "command" && !Payload.empty( ) && ( Access >= m_CCBot->m_DB->CommandAccess( "command" ) ) )
{
transform( Payload.begin( ), Payload.end( ), Payload.begin( ), (int(*)(int))tolower );
bool Exists = false;
for( map<string, unsigned char> :: iterator i = m_CCBot->m_Commands.begin( ); i != m_CCBot->m_Commands.end( ); ++i )
{
if( (*i).first == Payload )
Exists = true;
}
if( Exists )
QueueChatCommand( "Access needed for the [" + Payload + "] command is [" + UTIL_ToString( m_CCBot->m_DB->CommandAccess( Payload ) ) + "]", User, Whisper, Output );
else
QueueChatCommand( "Error checking access for [" + Payload + "] command, doesn't exist.", User, Whisper, Output );
}
//
// !SETCOMMAND
//
else if( Command == "setcommand" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "setcommand" ) )
{
bool Exists = false;
uint32_t NewAccess;
string command;
stringstream SS;
SS << Payload;
SS >> NewAccess;
if( SS.fail( ) || SS.eof( ) )
{
QueueChatCommand( "Bad input - use form " + m_CommandTrigger + "setcommand <access 0-10> <command>", User, Whisper, Output );
}
else
{
getline( SS, command );
string :: size_type Start = command.find_first_not_of( " " );
if( Start != string :: npos )
command = command.substr( Start );
if( NewAccess > 10 )
NewAccess = 10;
for( map<string, unsigned char> :: iterator i = m_CCBot->m_Commands.begin( ); i != m_CCBot->m_Commands.end( ); ++i )
if( (*i).first == command )
Exists = true;
if( Exists )
{
if( m_CCBot->m_DB->CommandSetAccess( command, NewAccess ) )
QueueChatCommand( "Updated [" + command + "] with access of [" + UTIL_ToString( NewAccess ) + "]", User, Whisper, Output );
else
QueueChatCommand( "Error updating access for [" + command + "] with access of [" + UTIL_ToString( NewAccess ) + "]", User, Whisper, Output );
}
else
QueueChatCommand( "Unable to set access for [" + command + "] because it doesn't exist.", User, Whisper, Output );
}
}
//
// !CLEARQUEUE
// !CQ
//
else if( ( Command == "clearqueue" || Command == "cq" ) && Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "clearqueue" ) )
{
while( !m_ChatCommands.empty( ) )
m_ChatCommands.pop( );
QueueChatCommand( m_CCBot->m_Language->MessageQueueCleared( ), User, Whisper, Output );
}
//
// !COUNTBANS
//
else if( Command == "countbans" && Access >= m_CCBot->m_DB->CommandAccess( "countbans" ) )
{
uint32_t Count = m_CCBot->m_DB->BanCount( m_Server );
if( Count == 0 )
QueueChatCommand( "There are no banned users from the channel.", User, Whisper, Output );
else if( Count == 1 )
QueueChatCommand( "There is one banned user from the channel.", User, Whisper, Output );
else
QueueChatCommand( "There are " + UTIL_ToString( Count ) + " banned users from the channel.", User, Whisper, Output );
}
//
// !COUNTSAFELIST
// !COUNTS
//
else if( ( Command == "countsafelist" || Command == "counts" ) && Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "countsafelist" ) )
{
uint32_t Count = m_CCBot->m_DB->SafelistCount( m_Server );
if( Count == 0 )
QueueChatCommand( "There are no safelisted users.", User, Whisper, Output );
else if( Count == 1 )
QueueChatCommand( "There is one safelisted user.", User, Whisper, Output );
else
QueueChatCommand( "There are " + UTIL_ToString( Count ) + " users safelisted.", User, Whisper, Output );
}
//
// !CHANNEL
//
else if( ( Command == "channel" || Command == "join" ) && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "channel" ) )
{
QueueChatCommand( "/join " + Payload, false );
m_CurrentChannel = Payload;
}
//
// !REJOIN
//
else if( Command == "rejoin" && Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "channel" ) )
{
QueueChatCommand( "/rejoin", false );
}
//
// !CHANLIST
//
else if( Command == "chanlist" && Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "chanlist" ) )
{
string tempText;
for( vector<CUser *> :: iterator i = m_Channel.begin( ); i != m_Channel.end( ); ++i )
tempText = tempText + (*i)->GetUser( ) + ", ";
if( tempText.length( ) >= 2 )
tempText = tempText.substr( 0, tempText.length( ) - 2 );
QueueChatCommand( "Users in channel [" + UTIL_ToString( m_Channel.size( ) ) + "]: " + tempText + ".", User, Whisper, Output );
}
//
// !CLANLIST
//
else if( Command == "clanlist" && Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "clanlist" ) && ClanMember )
{
string Chieftains = "Chieftains: ", Shamans = "Shamans: ", Grunts = "Grunts: ", Peons = "Peons: ";
for( vector<CIncomingClanList *> :: iterator i = m_Clans.begin( ); i != m_Clans.end( ); ++i )
{
if( (*i)->GetRank( ) == "Recruit" )
Peons = Peons + (*i)->GetName( ) + ", ";
else if( (*i)->GetRank( ) == "Peon" )
Peons = Peons + (*i)->GetName( ) + ", ";
else if( (*i)->GetRank( ) == "Grunt" )
Grunts = Grunts + (*i)->GetName( ) + ", ";
else if( (*i)->GetRank( ) == "Shaman" )
Shamans = Shamans + (*i)->GetName( ) + ", ";
else if( (*i)->GetRank( ) == "Chieftain" )
Chieftains = Chieftains + (*i)->GetName( ) + ", ";
}
if( Chieftains.size( ) > 12 )
{
if( Chieftains.size( ) > 179 )
{
SendChatCommand( "/w " + User + " " + Chieftains.substr( 0, 179 ), Output );
SendChatCommand( "/w " + User + " " + Chieftains.substr( 179, 180 ), Output );
}
else
SendChatCommand( "/w " + User + " " + Chieftains.substr( 0, Chieftains.size( )-2 ), Output );
}
if( Shamans.size( ) > 9 )
{
if( Shamans.size( ) > 179 )
{
SendChatCommand( "/w " + User + " " + Shamans.substr( 0, 179 ), Output );
SendChatCommand( "/w " + User + " " + Shamans.substr( 179, 180 ), Output );
}
else
SendChatCommand( "/w " + User + " " + Shamans.substr( 0, Shamans.size( )-2), Output );
}
if( Grunts.size( ) > 8 )
{
if( Grunts.size( ) > 179 )
{
SendChatCommand( "/w " + User + " " + Grunts.substr( 0, 179 ), Output );
SendChatCommand( "/w " + User + " " + Grunts.substr( 179, 180 ), Output );
}
else
SendChatCommand( "/w " + User + " " + Grunts.substr( 0, Grunts.size( )-2), Output );
}
if( Peons.size( ) > 7 )
{
if( Peons.size( ) > 179 )
{
SendChatCommand( "/w " + User + " " + Peons.substr( 0, 179 ), Output );
SendChatCommand( "/w " + User + " " + Peons.substr( 179, 180 ), Output );
}
else
SendChatCommand( "/w " + User + " " + Peons.substr( 0, Peons.size( )-2), Output );
}
}
//
// !DELBAN
// !UNBAN
//
else if( ( Command == "delban" || Command == "unban" ) && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "unban" ) )
{
string Victim, Reason;
stringstream SS;
SS << Payload;
SS >> Victim;
if( m_CCBot->m_DB->BanRemove( m_Server, Victim ) )
{
QueueChatCommand( "[" + Victim + "] successfully unbanned from the channel by " + User + ".", User, Whisper, Output );
QueueChatCommand( "/unban " + Victim, false );
}
else
QueueChatCommand( "Error unbanning [" + Victim + "] from the channel.", User, Whisper, Output );
}
//
// !DELSAFELIST
// !DELS
//
else if( ( Command == "delsafelist" || Command == "dels" ) && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "delsafelist" ) )
{
if( !m_CCBot->m_DB->SafelistCheck( m_Server, Payload ) )
QueueChatCommand( "User " + Payload + " is not safelisted.", User, Whisper, Output );
else
{
if( m_CCBot->m_DB->SafelistRemove( m_Server, Payload ) )
QueueChatCommand( "User " + Payload + " is deleted from safelist.", User, Whisper, Output );
else
QueueChatCommand( "Error deleting user " + Payload + " from the safelist.", User, Whisper, Output );
}
}
//
// !EXIT
// !QUIT
//
else if( ( Command == "exit" || Command == "quit" ) && Access >= m_CCBot->m_DB->CommandAccess( "exit" ) )
{
m_Exiting = true;
}
//
// !GAMES
//
else if( Command == "games" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "games" ) )
{
if( Match( Payload, "on" ) )
{
QueueChatCommand( m_CCBot->m_Language->GameAnnouncerEnabled( ), User, Whisper, Output );
m_AnnounceGames = true;
}
else if( Match( Payload, "off" ) )
{
QueueChatCommand( m_CCBot->m_Language->GameAnnouncerDisabled( ), User, Whisper, Output );
m_AnnounceGames = false;
}
}
//
// !GETCLAN
//
else if( Command == "getclan" && Access >= m_CCBot->m_DB->CommandAccess( "getclan" ) && ClanMember )
{
SendGetClanList( );
QueueChatCommand( m_CCBot->m_Language->UpdatedClanList( ), User, Whisper, Output );
QueueWhisperCommand( m_CCBot->m_Language->ReceivedClanMembers( UTIL_ToString( m_Clans.size( ) ) ), User, Output );
}
//
// !CHIEFTAIN
//
else if( Command == "chieftain" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "chieftain" ) && IsClanChieftain( m_UserName ) && ClanMember )
{
if( IsClanMember( Payload ) )
{
m_Socket->PutBytes( m_Protocol->SEND_SID_CLANMAKECHIEFTAIN( Payload ) );
m_LastKnown = Payload;
}
else
QueueChatCommand( m_CCBot->m_Language->MustBeAClanMember( Payload ), User, Whisper, Output );
}
//
// !GREET
//
else if( Command == "greet" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "greet" ) )
{
if( Match( Payload, "off" ) )
{
QueueChatCommand( m_CCBot->m_Language->GreetingDisabled( ), User, Whisper, Output );
m_GreetUsers = false;
}
else if( Match( Payload, "on" ) )
{
QueueChatCommand( m_CCBot->m_Language->GreetingEnabled( ), User, Whisper, Output );
m_GreetUsers = true;
}
}
//
// !GRUNT
//
else if( Command == "grunt" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "grunt" ) && ClanMember )
{
if( IsClanShaman( m_UserName ) || IsClanChieftain( m_UserName ) )
{
SendClanChangeRank( Payload, CBNETProtocol :: CLAN_MEMBER );
SendGetClanList( );
QueueChatCommand( m_CCBot->m_Language->ChangedRank( Payload, "Grunt" ), User, Whisper, Output );
}
else
QueueChatCommand( "Bot's account needs to be at least Shaman to perform this action.", User, Whisper, Output );
}
//
// !KICK
//
else if( Command == "kick" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "kick" ) )
{
string Victim, Reason;
stringstream SS;
SS << Payload;
SS >> Victim;
bool Found = false;
if ( !( Victim = GetUserFromNamePartial( Victim ) ).empty( ) )
Found = true;
if( Found && !IsClanShaman( Victim ) && !IsClanChieftain( Victim ) && !m_CCBot->m_DB->SafelistCheck( m_Server, Victim ) )
{
if( !SS.eof( ) )
{
getline( SS, Reason );
string :: size_type Start = Reason.find_first_not_of( " " );
if( Start != string :: npos )
Reason = Reason.substr( Start );
}
ImmediateChatCommand( "/kick " + Victim + " " + Reason, false );
}
else if ( !Found )
QueueChatCommand( "Can kick only users in channel.", User, Whisper, Output );
else
QueueChatCommand( "Clan shamans, chieftains and safelisted users cannot be kicked.", User, Whisper, Output );
}
//
// !LOCKDOWN
//
else if( Command == "lockdown" && !Match( "off", Payload ) && Access >= m_CCBot->m_DB->CommandAccess( "lockdown" ) )
{
if( Payload.empty( ) )
m_AccessRequired = Access;
else
{
stringstream SS;
SS << Payload;
SS >> m_AccessRequired;
}
m_IsLockdown = true;
QueueChatCommand( m_CCBot->m_Language->LockdownEnabled( UTIL_ToString( m_AccessRequired ) ), User, Whisper, Output );
}
//
// !LOCKDOWN OFF
//
else if( Command == "lockdown" && Match( "off", Payload ) && m_IsLockdown && Access >= m_CCBot->m_DB->CommandAccess( "lockdown" ) )
{
m_IsLockdown = false;
QueueChatCommand( m_CCBot->m_Language->LockdownDisabled( ), User, Whisper, Output );
for( vector<string> :: iterator i = m_Lockdown.begin( ); i != m_Lockdown.end( ); ++i )
ImmediateChatCommand( "/unban " + *i, false );
m_Lockdown.clear( );
}
//
// !MOTD (clan message of the day)
//
else if( Command == "motd" && Access >= m_CCBot->m_DB->CommandAccess( "motd" ) && ClanMember )
{
m_Socket->PutBytes( m_Protocol->SEND_SID_CLANSETMOTD( Payload ) );
QueueChatCommand( m_CCBot->m_Language->SetMOTD( Payload ), User, Whisper, Output );
}
//
// !PEON
//
else if( Command == "peon" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "peon" ) && ClanMember )
{
if( IsClanShaman( m_UserName ) || IsClanChieftain( m_UserName ) )
{
SendClanChangeRank( Payload, CBNETProtocol :: CLAN_PARTIAL_MEMBER );
QueueChatCommand( m_CCBot->m_Language->ChangedRank( Payload, "Peon" ), User, Whisper, Output );
}
else
QueueChatCommand( "Bot's account needs to be at least Shaman to perform this action.", User, Whisper, Output );
}
//
// !REMOVE (from clan)
//
else if( Command == "remove" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "remove" ) && ClanMember )
{
if( !IsClanChieftain( Payload ) && !IsClanShaman( Payload ) )
{
m_Socket->PutBytes( m_Protocol->SEND_SID_CLANREMOVEMEMBER( Payload ) );
m_Removed = Payload;
m_UsedRemove = User;
}
else
QueueChatCommand( "Removing Chieftains and Shamans is prohibited.", User, Whisper, Output );
}
//
// !RELOAD
//
else if( Command == "reload" && Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "reload" ) )
{
SendGetClanList( );
m_CCBot->UpdateSwearList( );
m_CCBot->ReloadConfigs( );
QueueChatCommand( m_CCBot->m_Language->CFGReloaded( ), User, Whisper, Output );
}
//
// !SAY
//
else if( Command == "say" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "say" ) )
{
if( Access > 8 || Payload[0] != '/' )
QueueChatCommand( Payload, false );
else
QueueChatCommand( m_CCBot->m_Language->NotAllowedUsingSay( ), User, Whisper, Output );
}
//
// !SAYBNET
//
else if( Command == "saybnet" && Access >= m_CCBot->m_DB-> CommandAccess( "say" ) && Payload.find( " " ) != string :: npos )
{
string :: size_type CommandStart = Payload.find( " " );
string server = Payload.substr( 0, CommandStart );
string command = Payload.substr( CommandStart + 1 );
vector<CBNET *> :: iterator i = m_CCBot->GetServerFromNamePartial( server );
if( i != m_CCBot->m_BNETs.end( ) )
{
if( Access > 8 || command[0] != '/' )
(*i)->QueueChatCommand( command, false );
else if( Payload[0] == '/' )
QueueChatCommand( m_CCBot->m_Language->NotAllowedUsingSay( ), User, Whisper, Output );
}
else
QueueChatCommand( m_CCBot->m_Language->UnableToPartiallyMatchServer( ), User, Whisper, Output );
}
//
// !SAYBNETS
//
else if( Command == "saybnets" && !Payload.empty( ) && Access >= m_CCBot->m_DB-> CommandAccess( "say" ) )
{
for( vector<CBNET *> :: iterator i = m_CCBot->m_BNETs.begin( ); i != m_CCBot->m_BNETs.end( ); ++i )
{
if( Access > 8 || Payload[0] != '/' )
(*i)->QueueChatCommand( Payload, false );
else if( (*i)->GetServer( ) == m_Server )
QueueChatCommand( m_CCBot->m_Language->NotAllowedUsingSay( ), User, Whisper, Output );
}
}
//
// !SHAMAN
//
else if( Command == "shaman" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "shaman" ) && ClanMember )
{
if( IsClanChieftain( m_UserName ) )
{
SendClanChangeRank( Payload, CBNETProtocol :: CLAN_OFFICER );
QueueChatCommand( m_CCBot->m_Language->ChangedRank( Payload, "Shaman" ), User, Whisper, Output );
}
else
QueueChatCommand( "Bot's account needs to be Chieftain to perform this action.", User, Whisper, Output );
}
//
// !SQUELCH
// !IGNORE
//
else if( ( Command == "squelch" || Command == "ignore" ) && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "squelch" ) )
{
if( GetSquelched( Payload ) == m_Squelched.end( ) )
{
QueueChatCommand( "/ignore " + Payload, false );
QueueChatCommand( "Ignoring user " + Payload + ".", User, Whisper, Output );
string Victim = Payload;
transform( Victim.begin( ), Victim.end( ), Victim.begin( ), (int(*)(int))tolower );
m_Squelched.push_back( Victim );
}
else
QueueChatCommand( "User [" + Payload + "] is already ignored.", User, Whisper, Output );
}
//
// !SQUELCHLIST
// !SL
//
else if( ( Command == "squelchlist" || Command == "sl" ) && Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "squelch" ) )
{
if ( m_Squelched.size( ) )
{
string tempText;
for( vector<string> :: iterator i = m_Squelched.begin( ); i != m_Squelched.end( ); ++i )
{
if( (*i).size( ) > 0 )
tempText = tempText + (*i) + ", ";
}
QueueChatCommand( "Squelched users: " + tempText.substr( 0, tempText.size( )- 2 ) + ".", User, Whisper, Output );
}
else
QueueChatCommand( "There are no squelched users." , User, Whisper, Output );
}
//
// !TOPIC
//
else if( Command == "topic" && Access >= m_CCBot->m_DB->CommandAccess( "topic" ) )
{
QueueChatCommand( "/topic " + m_CurrentChannel + " \"" + Payload + "\"", false );
QueueChatCommand( m_CCBot->m_Language->SetTopic( Payload ), User, Whisper, Output );
}
//
// !UNSQUELCH
// !UNIGNORE
//
else if( ( Command == "unsquelch" || Command == "unignore" ) && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "squelch" ) )
{
if( GetSquelched( Payload ) != m_Squelched.end( ) )
{
m_Squelched.erase( GetSquelched( Payload ) );
QueueChatCommand( "Unignoring user " + Payload + ".", User, Whisper, Output );
}
else
QueueChatCommand( "User " + Payload + " is not ignored.", User, Whisper, Output );
}
//
// !UPTIME
//
else if( Command == "uptime" && Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "uptime" ) )
{
string date;
uint64_t time = GetTime( ) - m_CCBot->m_Uptime;
if( time >= 86400 )
{
uint32_t days = time / 86400;
time -= days * 86400;
date = UTIL_ToString( days ) + "d ";
}
if( time >= 3600 )
{
uint32_t hours = time / 3600;
time -= hours * 3600;
date += UTIL_ToString( hours ) + "h ";
}
if( time >= 60 )
{
uint32_t minutes = time / 60;
time -= minutes * 60;
date += UTIL_ToString( minutes ) + "m ";
}
date += UTIL_ToString( (uint32_t) time ) + "s";
QueueChatCommand( m_CCBot->m_Language->Uptime( m_UserName, date ), User, Whisper, Output );
}
//
// !CHECKBAN
//
else if( Command == "checkban" && Access >= m_CCBot->m_DB->CommandAccess( "checkban" ) )
{
if( Payload.empty( ) )
User = Payload;
CDBBan *Ban = m_CCBot->m_DB->BanCheck( m_Server, Payload );
if( Ban )
{
if( Ban->GetReason( ).empty( ) )
QueueChatCommand( "User [" + Payload + "] was banned on " + Ban->GetDate( ) + " by " + Ban->GetAdmin( ) + ".", User, Whisper, Output );
else
QueueChatCommand( "User [" + Payload + "] was banned on " + Ban->GetDate( ) + " because \"" + Ban->GetReason( ) + "\" by " + Ban->GetAdmin( ) + ".", User, Whisper, Output );
delete Ban;
Ban = NULL;
}
else
QueueChatCommand( "User [" + Payload + "] is not banned.", User, Whisper, Output );
}
//
// !GN8
//
else if( Command == "gn8" && Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "gn8" ) )
QueueChatCommand( m_CCBot->m_Language->GN8( User ), false );
//
// !INVITE
//
else if( Command == "invite" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "invite" ) && ClanMember && IsInChannel( Payload ) )
{
if( !IsClanMember( Payload ) )
{
if( IsClanShaman( m_UserName ) || IsClanChieftain( m_UserName ) )
{
m_LastKnown = GetUserFromNamePartial( Payload );
m_Socket->PutBytes( m_Protocol->SEND_SID_CLANINVITATION( Payload ) );
QueueChatCommand( "Clan invitation was sent.", User, Whisper, Output );
}
else
QueueChatCommand( "Bot needs to have at least a Shaman rank to invite.", User, Whisper, Output );
}
else
QueueChatCommand( "You can't invite people already in clan!", User, Whisper, Output );
}
//
// !JOINCLAN
// !JOIN
//
else if( ( Command == "joinclan" || Command == "join" ) && Payload.empty( ) && !IsClanMember( User ) && IsInChannel( User ) && ClanMember )
{
if( m_SelfJoin )
{
if( IsClanShaman( m_UserName ) || IsClanChieftain( m_UserName ) )
{
m_LastKnown = User;
m_Socket->PutBytes( m_Protocol->SEND_SID_CLANINVITATION( User ) );
SendGetClanList( );
}
}
else
QueueChatCommand( m_CCBot->m_Language->CommandDisabled( ), User, Whisper, Output );
}
//
// !ONLINE
// !O
//
else if( ( Command == "online" || Command == "o" ) && Access >= m_CCBot->m_DB->CommandAccess( "online" ) && ClanMember )
{
string Online;
uint32_t OnlineNumber = 0;
for( unsigned int i = 0; i < m_Clans.size( ); ++i )
{
if( m_Clans[i]->GetStatus( ) == "Online" && !Match( m_Clans[i]->GetName( ), m_UserName ) && !Match( m_Clans[i]->GetName( ), m_HostbotName ) )
{
Online = Online + m_Clans[i]->GetName( ) + ", ";
++OnlineNumber;
}
}
if( OnlineNumber == 0 )
SendChatCommand( "/w " + User + " " + "There are no " + m_ClanTag + " members online.", Output );
else if( Online.size( ) < 156 )
SendChatCommand( "/w " + User + " " + m_ClanTag + " members online [" + UTIL_ToString(OnlineNumber) + "]: " + Online.substr( 0, Online.size( )-2) , Output );
else
{
SendChatCommand( "/w " + User + " " + m_ClanTag + " members online [" + UTIL_ToString(OnlineNumber) + "]: " + Online.substr( 0,155 ), Output );
SendChatCommand( "/w " + User + " " + Online.substr( 155, Online.size( )-157 ), Output );
}
}
//
// !SLAP
//
else if ( Command == "slap" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "slap" ) )
{
if ( GetUserFromNamePartial( Payload ).size( ) )
Payload = GetUserFromNamePartial( Payload );
if( Payload == User )
Payload = "himself";
switch( rand( ) % 6 )
{
case 0: QueueChatCommand( User + " slaps " + Payload + " around a bit with a large trout.", false );
break;
case 1: QueueChatCommand( User + " slaps " + Payload + " around a bit with a pink Macintosh.", false );
break;
case 2: QueueChatCommand( User + " throws a Playstation 3 at " + Payload + ".", false );
break;
case 3: QueueChatCommand( User + " drives a car over " + Payload + ".", false );
break;
case 4: QueueChatCommand( User + " finds " + Payload + " on uglypeople.com.", false );
break;
case 5: QueueChatCommand( User + " searches google.com for \"goatsex + " + Payload + "\". " + UTIL_ToString( rand( ) ) + " hits WEEE!", false );
break;
}
}
//
// !SPIT
//
else if ( Command == "spit" && !Payload.empty( ) && IsInChannel( User ) && Access >= m_CCBot->m_DB->CommandAccess( "spit" ) )
{
if ( GetUserFromNamePartial( Payload ).size( ) )
Payload = GetUserFromNamePartial( Payload );
switch( rand( ) % 6 )
{
case 0: QueueChatCommand( User + " spits " + Payload + " but misses completely!", false );
break;
case 1: QueueChatCommand( User + " spits " + Payload + " and hits him in the eye!", false );
break;
case 2: QueueChatCommand( User + " spits " + Payload + " and hits him in his mouth!", false );
break;
case 3: QueueChatCommand( User + " spits " + Payload + " and nails it into his ear!", false );
break;
case 4: QueueChatCommand( User + " spits " + Payload + " but he accidentally hits himself!", false );
break;
case 5: QueueChatCommand( Payload + " counterspits " + User + ". Lame.", false );
break;
}
}
//
// !SERVE
//
else if ( Command == "serve" && !Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "serve" ) )
{
string Victim, Object;
stringstream SS;
SS << Payload;
SS >> Victim;
if( !SS.eof( ) )
{
getline( SS, Object );
string :: size_type Start = Object.find_first_not_of( " " );
if( Start != string :: npos )
Object = Object.substr( Start );
}
if ( GetUserFromNamePartial( Victim ).size( ) )
Victim = GetUserFromNamePartial( Victim );
QueueChatCommand( User + " serves " + Victim + " a " + Object + ".", false );
}
//
// !STATUS
//
else if ( Command == "status" && Payload.empty( ) && Access >= m_CCBot->m_DB->CommandAccess( "status" ) )
{
string message = "Status: ";
for( vector<CBNET *> :: iterator i = m_CCBot->m_BNETs.begin( ); i != m_CCBot->m_BNETs.end( ); ++i )
{
message += (*i)->GetUserName( ) + ( (*i)->GetLoggedIn( ) ? " [Online], " : " [Offline], " );
}
QueueChatCommand( message.substr( 0, message.size( ) - 2 ) + ".", User, Whisper, Output );
}
//
// !VERSION
//
else if( Command == "version" && Payload.empty( ) )
QueueChatCommand( m_CCBot->m_Language->Version( m_CCBot->m_Version ), User, Whisper, Output );
//
// !PING
//
else if( Command == "ping" && Access >= m_CCBot->m_DB->CommandAccess( "ping" ) )
{
if( Payload.empty( ) )
Payload = User;
else if( GetUserFromNamePartial( Payload ).size( ) )
Payload = GetUserFromNamePartial( Payload );
CUser *Result = GetUserByName( Payload );
if( Result )
QueueChatCommand( m_CCBot->m_Language->Ping( Result->GetUser( ), UTIL_ToString( Result->GetPing( ) ) , m_ServerAlias ), User, Whisper, Output );
else
QueueChatCommand( m_CCBot->m_Language->CannotAccessPing( ), User, Whisper, Output );
}
//
// !RESTART
//
else if( Command == "restart" && Access >= m_CCBot->m_DB->CommandAccess( "restart" ) )
{
m_Exiting = true;
// gRestart is defined in ccbot.cpp
extern bool gRestart;
gRestart = true;
return;
}
}
}
else if( Event == CBNETProtocol :: EID_INFO )
{
CONSOLE_Print( "[INFO: " + m_ServerAlias + "] " + Message );
if( m_AnnounceGames && m_Channel.size( ) >= 2 )
{
if( Message.find( "is using Warcraft III Frozen Throne and is currently in game" ) != string :: npos || Message.find( "is using Warcraft III Frozen Throne and is currently in private game" ) != string :: npos || Message.find( "is using Warcraft III The Frozen Throne in game" ) != string :: npos )
{
string user = Message.substr( 0, Message.find_first_of(" ") );
if( !Match( user, m_HostbotName ) )
{
Message = Message.substr( Message.find_first_of("\"") + 1, Message.find_last_of("\"") - Message.find_first_of("\"") - 1 );
QueueChatCommand( m_CCBot->m_Language->AnnounceGame( user, Message ), false );
}
}
}
}
else if( Event == CBNETProtocol :: EID_JOIN )
{
// check if the user joined has been banned if yes ban him again and send him the reason the first time he tries to join
CDBBan *Ban = m_CCBot->m_DB->BanCheck( m_Server, User );
if( Ban )
{
string Info = "by " + Ban->GetAdmin( );
if( !Ban->GetReason( ).empty( ) )
Info += ": " + Ban->GetReason( );
Info += " on " + Ban->GetDate( );
SendChatCommand( "/ban " + User + " " + Info, false );
delete Ban;
}
else
{
// if there is a lockdown and the person can't join do not add it to the channel list and greet him - that's why we use bool CanJoinChannel
if( m_IsLockdown )
{
if( m_AccessRequired > Access && !Match( User, m_HostbotName ) )
{
SendChatCommand( "/ban " + User + " Lockdown: only users with " + UTIL_ToString( m_AccessRequired ) + "+ access can join", false );
if( GetLockdown( User ) == m_Lockdown.end( ) )
m_Lockdown.push_back( User );
return;
}
}
if( m_BanChat && Message == "TAHC" && !m_CCBot->m_DB->SafelistCheck( m_Server, User ) )
{
ImmediateChatCommand( "/kick " + User + " Chat clients are forbidden to enter the channel", false );
return;
}
// only greet in originally set channel
if( Match( m_CurrentChannel, m_FirstChannel ) && m_GreetUsers && !Match( User, m_HostbotName ) )
{
ImmediateChatCommand( m_CCBot->m_Language->WelcomeMessageLine1( m_FirstChannel, User ), false );
QueueChatCommand( m_CCBot->m_Language->WelcomeMessageLine2( m_FirstChannel, User ), false );
}
CUser *user = new CUser( User, lowerUser, chatEvent->GetPing( ), chatEvent->GetUserFlags( ) );
if( Message.size( ) >= 14 )
{
reverse( Message.begin( ), Message.end( ) );
user->SetClan( Message.substr( 0, Message.find_first_of(" ") ) );
}
if ( Access == 0 && IsClanMember( User ) && m_ClanDefaultAccess > 0 )
{
m_CCBot->m_DB->AccessSet( m_Server, User, m_ClanDefaultAccess );
CONSOLE_Print( "[ACCESS: " + m_ServerAlias + "] Setting [" + User + "] access to clan default of " + UTIL_ToString( m_ClanDefaultAccess ) );
}
CONSOLE_Print( "[CHANNEL: " + m_ServerAlias + ":" + m_CurrentChannel + "] user [" + User + "] joined the channel." );
m_Channel.push_back( user );
CONSOLE_ChannelWindowChanged( );
}
}
else if( Event == CBNETProtocol :: EID_LEAVE )
{
if ( m_AnnounceGames && !Match( m_HostbotName, User ) )
SendChatCommandHidden( "/whois " + User, false );
for( vector<CUser *> :: iterator i = m_Channel.begin( ); i != m_Channel.end( ); ++i )
{
if( (*i)->GetLowerUser( ) == lowerUser )
{
delete *i;
i = m_Channel.erase( i );
break;
}
}
CONSOLE_Print( "[CHANNEL: " + m_ServerAlias + ":" + m_CurrentChannel + "] user [" + User + "] left the channel." );
CONSOLE_ChannelWindowChanged( );
}
else if( Event == CBNETProtocol :: EID_ERROR )
{
CONSOLE_Print( "[ERROR: " + m_ServerAlias + "] " + Message );
if( Message == "You are banned from that channel." )
m_RejoinInterval = 300;
else if( Message == "Your message quota has been exceeded!" )
m_Delay += 1500;
}
else if( Event == CBNETProtocol :: EID_CHANNEL )
{
CONSOLE_Print( "[CHANNEL: " + m_ServerAlias + "] Joining channel [" + Message + "]" );
if( !Match( Message, m_CurrentChannel ) )
m_Rejoin = true;
else
{
m_Rejoin = false;
m_RejoinInterval = 15;
}
for( vector<CUser *> :: iterator i = m_Channel.begin( ); i != m_Channel.end( ); ++i )
delete *i;
m_Channel.clear( );
CONSOLE_ChannelWindowChanged( );
}
else if( Event == CBNETProtocol :: EID_SHOWUSER )
{
if( m_BanChat && Message == "TAHC" && !m_CCBot->m_DB->SafelistCheck( m_Server, User ) )
{
// this method ("CHAT" client checking) works exclusively on PvPGNs as Blizzard banned Telnet clients
ImmediateChatCommand( "/kick " + User + " Chat clients are banned from channel", false );
return;
}
CUser *user = new CUser( User, lowerUser, chatEvent->GetPing( ), chatEvent->GetUserFlags( ) );
if( Message.size( ) >= 14 )
{
reverse( Message.begin( ), Message.end( ) );
user->SetClan( Message.substr( 0, Message.find_first_of(" ") ) );
}
m_Channel.push_back( user );
CONSOLE_ChannelWindowChanged( );
}
CONSOLE_MainWindowChanged( );
}
| [
"[email protected]"
]
| [
[
[
1,
1484
]
]
]
|
d20864791b1cdf6bf20a55f46b6891948dd270b1 | be7df324d5509c7ebb368c884b53ea9445d32e4f | /GUI/Cardiac/patienttree.cpp | 83d981fbb2dea8ae0da35978bfd6ae4f9bcad582 | []
| no_license | shadimsaleh/thesis.code | b75281001aa0358282e9cceefa0d5d0ecfffdef1 | 085931bee5b07eec9e276ed0041d494c4a86f6a5 | refs/heads/master | 2021-01-11T12:20:13.655912 | 2011-10-19T13:34:01 | 2011-10-19T13:34:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,990 | cpp | #include <QtGui>
#include "patienttree.h"
patientTree::patientTree(QWidget *parent)
: QTreeWidget(parent)
{
QStringList labels;
// labels << tr("Patient") << tr("Study") << tr("Type / Protocol");
labels << tr("Subject") << tr("Protocol") << tr("Study ID") << tr("Series") << tr("Dimensions") << tr("Frames");
// header()->setResizeMode(QHeaderView::Stretch);
setHeaderLabels(labels);
patientIcon.addPixmap(QPixmap(":/res/images/patient.png"));
dataIcon.addPixmap ( QPixmap(":/res/images/data.png"));
}
bool patientTree::read(QIODevice *device)
{
QString errorStr;
int errorLine;
int errorColumn;
if (!domDocument.setContent(device, true, &errorStr, &errorLine,
&errorColumn)) {
QMessageBox::information(window(), tr("Patient Browser"),
tr("Parse error at line %1, column %2:\n%3")
.arg(errorLine)
.arg(errorColumn)
.arg(errorStr));
return false;
}
QDomElement root = domDocument.documentElement();
if (root.tagName() != "sbia") {
QMessageBox::information(window(), tr("Patient Browser"),
tr("The file is not a SBIA patient database file."));
return false;
} else if (root.hasAttribute("version")
&& root.attribute("version") != "1.0") {
QMessageBox::information(window(), tr("Patient Browser"),
tr("The version of the SBIA patient database is not supported"));
return false;
}
clear();
// disconnect(this, SIGNAL(itemChanged(QTreeWidgetItem *, int)),
// this, SLOT(updateDomElement(QTreeWidgetItem *, int)));
QDomElement child = root.firstChildElement("patient");
while (!child.isNull()) {
parsePatientElement(child);
child = child.nextSiblingElement("patient");
}
// connect(this, SIGNAL(itemChanged(QTreeWidgetItem *, int)),
// this, SLOT(updateDomElement(QTreeWidgetItem *, int)));
return true;
}
bool patientTree::write(QIODevice *device)
{
const int IndentSize = 4;
QTextStream out(device);
domDocument.save(out, IndentSize);
return true;
}
void patientTree::updateDomElement(QTreeWidgetItem *item, int column)
{
QDomElement element = domElementForItem.value(item);
if (!element.isNull()) {
switch (column) {
case 0: {
QDomElement oldTitleElement = element.firstChildElement("name");
QDomElement newTitleElement = domDocument.createElement("name");
QDomText newTitleText = domDocument.createTextNode(item->text(0));
newTitleElement.appendChild(newTitleText);
element.replaceChild(newTitleElement, oldTitleElement);
}
break;
case 1:
if (element.tagName() == "dataset")
element.setAttribute("protocol", item->text(1));
break;
case 2:
if (element.tagName() == "dataset")
element.setAttribute("study", item->text(2));
break;
case 3:
if (element.tagName() == "dataset")
element.setAttribute("series", item->text(3));
}
}
/* if (column == 0) {
QDomElement oldTitleElement = element.firstChildElement("title");
QDomElement newTitleElement = domDocument.createElement("title");
QDomText newTitleText = domDocument.createTextNode(item->text(0));
newTitleElement.appendChild(newTitleText);
element.replaceChild(newTitleElement, oldTitleElement);
} else {
if (element.tagName() == "bookmark")
element.setAttribute("href", item->text(1));
}
} */
}
void patientTree::parsePatientElement(const QDomElement &element,
QTreeWidgetItem *parentItem)
{
QTreeWidgetItem *item = createItem(element, parentItem);
QString title = element.firstChildElement("name").text();
if (title.isEmpty())
title = QObject::tr("Unknown Patient");
item->setFlags(item->flags() | Qt::ItemIsEditable);
item->setIcon(0, patientIcon);
item->setText(0, title);
bool folded = (element.attribute("folded") != "no");
setItemExpanded(item, !folded);
QDomElement child = element.firstChildElement();
while (!child.isNull()) {
if (child.tagName() == "dataset") {
QTreeWidgetItem *childItem = createItem(child, item);
QString proto = child.firstChildElement("protocol").text();
if (proto.isEmpty())
proto = QObject::tr("unknown protocol");
QString study = child.firstChildElement("study").text();
if (study.isEmpty())
study = QObject::tr("?");
QString series = child.firstChildElement("series").text();
if (series.isEmpty())
series = QObject::tr("?");
QString dims = child.firstChildElement("dimensions").text();
if (dims.isEmpty())
dims = QObject::tr("?x?x?");
QDomElement frames = child.firstChildElement("frames");
QString cnt = frames.attribute("count", "1");
// the thumbnail ...
QString tnail = tnailDir.absoluteFilePath(frames.firstChildElement("thumbnail").text());
childItem->setFlags(item->flags() | Qt::ItemIsEditable);
childItem->setIcon(0, dataIcon);
childItem->setText(1, proto);
childItem->setText(2, study);
childItem->setText(3, series);
childItem->setText(4, dims);
childItem->setText(5, cnt);
childItem->setData(0, Qt::WhatsThisRole, QPixmap::fromImage(QImage(tnail)) );
} else if (child.tagName() == "separator") {
QTreeWidgetItem *childItem = createItem(child, item);
childItem->setFlags(item->flags() & ~(Qt::ItemIsSelectable | Qt::ItemIsEditable));
childItem->setText(0, QString(30, 0xB7));
}
child = child.nextSiblingElement();
}
}
QTreeWidgetItem *patientTree::createItem(const QDomElement &element,
QTreeWidgetItem *parentItem)
{
QTreeWidgetItem *item;
if (parentItem) {
item = new QTreeWidgetItem(parentItem);
} else {
item = new QTreeWidgetItem(this);
}
domElementForItem.insert(item, element);
return item;
}
QDomElement patientTree::initNewRoot() {
domDocument= QDomDocument("sbia");
QDomElement root = domDocument.createElement("sbia");
root.setAttribute("version", "1.0");
domDocument.appendChild(root);
return domDocument.documentElement();
}
| [
"[email protected]"
]
| [
[
[
1,
200
]
]
]
|
d00dad67ccf0c64063fec60af927f975ae7d2373 | ce105c9e4ac9b1b77a160793e0c336826b936670 | /c++/dateing time/dateing time/main.cpp | 06e2ab9d7b2b0a62379b31aa3b72cc6d5780dd6f | []
| no_license | jmcgranahan/jusall-programinghw | a32909655cec085d459c2c567c2f1bed2b947612 | d6c5b54d0300a784dee0257364cd049f741cee81 | refs/heads/master | 2020-08-27T03:27:24.013332 | 2011-04-25T06:30:27 | 2011-04-25T06:30:27 | 40,640,139 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 677 | cpp | #include <iostream>
#include <ctime>
#include "MyTime.h"
#include "MyDate.h"
using namespace std;
void outputTime( MyTime & t1, MyTime & t2)
{
cout << "t1: " << t1 <<endl;
cout << "t2: " << t2 <<endl;
cout << "--------------------------------------" <<endl;
t1.SetTicks(0);
t2.SetTicks(0);
}
int main()
{
MyTime t1;
MyTime t2(1,2,3,4);
outputTime(t1,t2);
t1.AddHours(5);
t2.AddMinutes(4);
outputTime(t1,t2);
t1.AddSeconds(5);
t2.AddTicks(6);
outputTime(t1,t2);
t1.AddHours(5);
t2.AddTime(t1);
outputTime(t1,t2);
t1 = MyTime::Now();
t2= MyTime::Now();
cout << t2.Compare(t1) <<endl;
outputTime(t1,t2);
} | [
"biga05@c0f360ae-aefd-11de-b8dd-ab4b6ce6d521"
]
| [
[
[
1,
43
]
]
]
|
c6124fd640f5b3f7aaa02afaebf8b850532b7ad2 | bef7d0477a5cac485b4b3921a718394d5c2cf700 | /dingus/tools/NormalMapperFork/AtiOctree.cpp | 275d169b340c195ad4c78b239fd4280a9e44f5d7 | [
"MIT"
]
| permissive | TomLeeLive/aras-p-dingus | ed91127790a604e0813cd4704acba742d3485400 | 22ef90c2bf01afd53c0b5b045f4dd0b59fe83009 | refs/heads/master | 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,132 | cpp | //=============================================================================
// AtiOctree.cpp -- The implementation of the Octree routines.
//=============================================================================
// $File: //depot/3darg/Demos/Sushi/Math/AtiOctree.cpp $ $Revision: #4 $ $Author: gosselin $
//=============================================================================
// (C) 2003 ATI Research, Inc., All rights reserved.
//=============================================================================
#include <string.h>
#include "AtiOctree.h"
// The size of the initial stack for traversing the tree.
static const int32 ATI_INITIAL_OCTREE_STACK_SIZE = 64;
static const float32 ATI_BBOX_CUTOFF = 0.001f;
// EPSILON for cell creation, needs to be at least half as small as CUTOFF
static const float32 ATI_OCT_EPSILON = 0.000001f;
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Cell Routines.
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Construct a cell
///////////////////////////////////////////////////////////////////////////////
AtiOctreeCell::AtiOctreeCell (void)
{
memset (&m_boundingBox, 0, sizeof (AtiOctBoundingBox));
memset (&m_children, 0, sizeof (AtiOctreeCell*) * 8);
m_leaf = true;
m_numItems = 0;
m_item = NULL;
}
///////////////////////////////////////////////////////////////////////////////
// Destroy this cell, and only this cell!
///////////////////////////////////////////////////////////////////////////////
AtiOctreeCell::~AtiOctreeCell (void)
{
for (int32 c = 0; c < 8; c++)
{
delete m_children[c];
}
memset (&m_children, 0, sizeof (AtiOctreeCell*) * 8);
memset (&m_boundingBox, 0, sizeof (AtiOctBoundingBox));
m_numItems = 0;
delete [] m_item;
m_item = NULL;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Tree Routines.
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Destroy this cell, and only this cell!
///////////////////////////////////////////////////////////////////////////////
AtiOctree::AtiOctree (void)
{
m_root = NULL;
}
///////////////////////////////////////////////////////////////////////////////
// Destroy a tree
///////////////////////////////////////////////////////////////////////////////
AtiOctree::~AtiOctree (void)
{
delete m_root;
m_root = NULL;
}
///////////////////////////////////////////////////////////////////////////////
// Gets the bounding box for a given child.
///////////////////////////////////////////////////////////////////////////////
void
AtiOctree::GetBoundingBox (int32 childIndex, AtiOctBoundingBox *bbox,
AtiOctreeCell* child)
{
// Figure out min/maxs
switch (childIndex)
{
case ATI_OCT_TREE_CHILD_PX_PY_PZ:
child->m_boundingBox.minX = bbox->centerX - ATI_OCT_EPSILON;
child->m_boundingBox.maxX = bbox->centerX + bbox->halfX + ATI_OCT_EPSILON;
child->m_boundingBox.minY = bbox->centerY - ATI_OCT_EPSILON;
child->m_boundingBox.maxY = bbox->centerY + bbox->halfY + ATI_OCT_EPSILON;
child->m_boundingBox.minZ = bbox->centerZ - ATI_OCT_EPSILON;
child->m_boundingBox.maxZ = bbox->centerZ + bbox->halfZ + ATI_OCT_EPSILON;
break;
case ATI_OCT_TREE_CHILD_PX_NY_PZ:
child->m_boundingBox.minX = bbox->centerX - ATI_OCT_EPSILON;
child->m_boundingBox.maxX = bbox->centerX + bbox->halfX + ATI_OCT_EPSILON;
child->m_boundingBox.minY = bbox->centerY - bbox->halfY - ATI_OCT_EPSILON;
child->m_boundingBox.maxY = bbox->centerY + ATI_OCT_EPSILON;
child->m_boundingBox.minZ = bbox->centerZ - ATI_OCT_EPSILON;
child->m_boundingBox.maxZ = bbox->centerZ + bbox->halfZ + ATI_OCT_EPSILON;
break;
case ATI_OCT_TREE_CHILD_PX_PY_NZ:
child->m_boundingBox.minX = bbox->centerX - ATI_OCT_EPSILON;
child->m_boundingBox.maxX = bbox->centerX + bbox->halfX + ATI_OCT_EPSILON;
child->m_boundingBox.minY = bbox->centerY - ATI_OCT_EPSILON;
child->m_boundingBox.maxY = bbox->centerY + bbox->halfY + ATI_OCT_EPSILON;
child->m_boundingBox.minZ = bbox->centerZ - bbox->halfZ - ATI_OCT_EPSILON;
child->m_boundingBox.maxZ = bbox->centerZ + ATI_OCT_EPSILON;
break;
case ATI_OCT_TREE_CHILD_PX_NY_NZ:
child->m_boundingBox.minX = bbox->centerX - ATI_OCT_EPSILON;
child->m_boundingBox.maxX = bbox->centerX + bbox->halfX + ATI_OCT_EPSILON;
child->m_boundingBox.minY = bbox->centerY - bbox->halfY - ATI_OCT_EPSILON;
child->m_boundingBox.maxY = bbox->centerY + ATI_OCT_EPSILON;
child->m_boundingBox.minZ = bbox->centerZ - bbox->halfZ - ATI_OCT_EPSILON;
child->m_boundingBox.maxZ = bbox->centerZ + ATI_OCT_EPSILON;
break;
case ATI_OCT_TREE_CHILD_NX_PY_PZ:
child->m_boundingBox.minX = bbox->centerX - bbox->halfX - ATI_OCT_EPSILON;
child->m_boundingBox.maxX = bbox->centerX + ATI_OCT_EPSILON;
child->m_boundingBox.minY = bbox->centerY - ATI_OCT_EPSILON;
child->m_boundingBox.maxY = bbox->centerY + bbox->halfY + ATI_OCT_EPSILON;
child->m_boundingBox.minZ = bbox->centerZ - ATI_OCT_EPSILON;
child->m_boundingBox.maxZ = bbox->centerZ + bbox->halfZ + ATI_OCT_EPSILON;
break;
case ATI_OCT_TREE_CHILD_NX_NY_PZ:
child->m_boundingBox.minX = bbox->centerX - bbox->halfX - ATI_OCT_EPSILON;
child->m_boundingBox.maxX = bbox->centerX + ATI_OCT_EPSILON;
child->m_boundingBox.minY = bbox->centerY - bbox->halfY - ATI_OCT_EPSILON;
child->m_boundingBox.maxY = bbox->centerY + ATI_OCT_EPSILON;
child->m_boundingBox.minZ = bbox->centerZ - ATI_OCT_EPSILON;
child->m_boundingBox.maxZ = bbox->centerZ + bbox->halfZ + ATI_OCT_EPSILON;
break;
case ATI_OCT_TREE_CHILD_NX_PY_NZ:
child->m_boundingBox.minX = bbox->centerX - bbox->halfX - ATI_OCT_EPSILON;
child->m_boundingBox.maxX = bbox->centerX + ATI_OCT_EPSILON;
child->m_boundingBox.minY = bbox->centerY - ATI_OCT_EPSILON;
child->m_boundingBox.maxY = bbox->centerY + bbox->halfY + ATI_OCT_EPSILON;
child->m_boundingBox.minZ = bbox->centerZ - bbox->halfZ - ATI_OCT_EPSILON;
child->m_boundingBox.maxZ = bbox->centerZ + ATI_OCT_EPSILON;
break;
case ATI_OCT_TREE_CHILD_NX_NY_NZ:
child->m_boundingBox.minX = bbox->centerX - bbox->halfX - ATI_OCT_EPSILON;
child->m_boundingBox.maxX = bbox->centerX + ATI_OCT_EPSILON;
child->m_boundingBox.minY = bbox->centerY - bbox->halfY - ATI_OCT_EPSILON;
child->m_boundingBox.maxY = bbox->centerY + ATI_OCT_EPSILON;
child->m_boundingBox.minZ = bbox->centerZ - bbox->halfZ - ATI_OCT_EPSILON;
child->m_boundingBox.maxZ = bbox->centerZ + ATI_OCT_EPSILON;
break;
default:
// badness.
{int32 i = 0;}
break;
}
// Figure out center and half
AtiOctBoundingBox* b = &(child->m_boundingBox);
b->halfX = (b->maxX - b->minX) / 2.0f;
b->centerX = b->halfX + b->minX;
b->halfY = (b->maxY - b->minY) / 2.0f;
b->centerY = b->halfY + b->minY;
b->halfZ = (b->maxZ - b->minZ) / 2.0f;
b->centerZ = b->halfZ + b->minZ;
} // end of GetBoundingBox
///////////////////////////////////////////////////////////////////////////////
// Fill in the octree.
///////////////////////////////////////////////////////////////////////////////
bool8
AtiOctree::FillTree (int32 numItems, void* itemList,
AtiOctBoundingBox& boundingBox,
AtiPfnItemInBox fnItemInBox, int32 maxInBox,
AtiPfnOctProgress fnProgress)
{
// First create the root node
m_root = new AtiOctreeCell;
memcpy (&(m_root->m_boundingBox), &boundingBox, sizeof (AtiOctBoundingBox));
// Expand bounding box a little, just in case there's some floating point
// strangeness with planes lying on planes.
m_root->m_boundingBox.minX -= ATI_OCT_EPSILON;
m_root->m_boundingBox.minY -= ATI_OCT_EPSILON;
m_root->m_boundingBox.minZ -= ATI_OCT_EPSILON;
m_root->m_boundingBox.maxX += ATI_OCT_EPSILON;
m_root->m_boundingBox.maxY += ATI_OCT_EPSILON;
m_root->m_boundingBox.maxZ += ATI_OCT_EPSILON;
m_root->m_boundingBox.halfX = (m_root->m_boundingBox.maxX - m_root->m_boundingBox.minX) / 2.0f;
m_root->m_boundingBox.halfY = (m_root->m_boundingBox.maxY - m_root->m_boundingBox.minY) / 2.0f;
m_root->m_boundingBox.halfZ = (m_root->m_boundingBox.maxZ - m_root->m_boundingBox.minZ) / 2.0f;
// Allocate items list for root
m_root->m_numItems = 0;
m_root->m_item = new int32 [numItems];
if (m_root->m_item == NULL)
{
return FALSE;
}
memset (m_root->m_item, 0, sizeof (int32) * numItems);
// Fill in items for root.
for (int32 i = 0; i < numItems; i++)
{
// By calling this function when filling this array it lets the
// calling program weed out some items. Useful in ambient occlusion
// to have some items not block rays.
if (fnItemInBox (i, itemList, &(m_root->m_boundingBox)) == TRUE)
{
m_root->m_item[m_root->m_numItems] = i;
m_root->m_numItems++;
}
}
// Allocate a stack to hold the list of cells we are working with.
AtiOctreeCell** cell = new AtiOctreeCell* [ATI_INITIAL_OCTREE_STACK_SIZE];
if (cell == NULL)
{
return FALSE;
}
int32 maxCells = ATI_INITIAL_OCTREE_STACK_SIZE;
memset (cell, 0, sizeof (AtiOctreeCell*) * maxCells);
// Now partition
cell[0] = m_root;
int32 numCells = 1;
while (numCells > 0)
{
// Show some progress if requested.
if (fnProgress != NULL)
{
fnProgress (0.0f);
}
// Take the one off the stack.
numCells--;
AtiOctreeCell* currCell = cell[numCells];
// First see if we even need to create children
if ( (currCell->m_numItems < maxInBox) ||
(currCell->m_boundingBox.halfX <= ATI_BBOX_CUTOFF) ||
(currCell->m_boundingBox.halfY <= ATI_BBOX_CUTOFF) ||
(currCell->m_boundingBox.halfZ <= ATI_BBOX_CUTOFF) )
{
continue;
}
// Create children as needed and add them to our list.
for (int32 c = 0; c < 8; c++)
{
// First create a new cell.
currCell->m_children[c] = new AtiOctreeCell;
currCell->m_leaf = false;
if (currCell->m_children[c] == NULL)
{
delete [] cell;
return FALSE;
}
AtiOctreeCell* child = currCell->m_children[c];
//memset (child, 0, sizeof (AtiOctreeCell)); // Aras
// Allocate items, use parent since that's the maximum we can have.
child->m_numItems = 0;
child->m_item = new int32 [currCell->m_numItems];
if (child->m_item == NULL)
{
delete [] cell;
return NULL;
}
memset (child->m_item, 0, sizeof (int32) * currCell->m_numItems);
// Now figure out the bounding box.
GetBoundingBox (c, &currCell->m_boundingBox, child);
// Run through the items and see if they belong in this cell.
for (int32 i = 0; i < currCell->m_numItems; i++)
{
if (fnItemInBox (currCell->m_item[i], itemList,
&child->m_boundingBox) == TRUE)
{
child->m_item[child->m_numItems] = currCell->m_item[i];
child->m_numItems++;
}
} // end for number of items in the current cell.
// If we didn't find anything in the box, bail
if (child->m_numItems < 1)
{
delete currCell->m_children[c];
currCell->m_children[c] = NULL;
bool hasChildren = false;
for( int z = 0; z < 8; ++z ) {
if( currCell->m_children[z] != NULL ) {
hasChildren = true;
break;
}
}
if( !hasChildren )
currCell->m_leaf = true;
child = NULL;
continue;
}
// If we haven't reached our target item size add this into our list
if ( (child->m_numItems > maxInBox) ||
(currCell->m_boundingBox.halfX > ATI_BBOX_CUTOFF) ||
(currCell->m_boundingBox.halfY > ATI_BBOX_CUTOFF) ||
(currCell->m_boundingBox.halfZ > ATI_BBOX_CUTOFF) )
{
// Make sure we have enough room on our stack.
if (numCells >= maxCells)
{
maxCells += ATI_INITIAL_OCTREE_STACK_SIZE;
AtiOctreeCell** newCells = new AtiOctreeCell* [maxCells];
memset (newCells, 0, sizeof (AtiOctreeCell*) * maxCells);
memcpy (newCells, cell, sizeof (AtiOctreeCell*) * numCells);
delete [] cell;
cell = newCells;
newCells = NULL;
}
// Add this item into our list.
cell[numCells] = currCell->m_children[c];
numCells++;
}
child = NULL;
} // for c (number of children);
} // While we still have cells.
// Worked!
delete [] cell;
return TRUE;
} // end of FillTree
| [
"[email protected]"
]
| [
[
[
1,
341
]
]
]
|
0dca346efcb9ef5814a73f31872f593c9ea3fb53 | dd6f90768f81df0b4720173daefe04a9d8674e99 | / mycom/Source/MyComDlg.cpp | eaa0e2ca91c4a6bb32966aa53124963860618d98 | []
| no_license | Fansle/mycom | 31b6642bf8608feab7b1b99c4085def7fd85ad2d | 1fae1dcd97cd9a5b24feb84027a72b216e47428f | refs/heads/master | 2021-01-10T17:16:23.375024 | 2007-12-27T09:16:50 | 2007-12-27T09:16:50 | 54,310,582 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 8,213 | cpp | /*
* myCom App
* Http://mycom.googlecode.com
*
* About Dlg
*
* author: mrlong date:2007-12-22
*
* createdate: 2007-12-21
* last modification date 2007-12-22
*
* update:
*
*
*/
// MyComDlg.cpp : implementation file
//
#include "stdafx.h"
#include "MyCom.h"
#include "MyComDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
ON_WM_LBUTTONDOWN()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMyComDlg dialog
CMyComDlg::CMyComDlg(CWnd* pParent /*=NULL*/)
: CDialog(CMyComDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CMyComDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
BEGIN_MESSAGE_MAP(CMyComDlg, CDialog)
//{{AFX_MSG_MAP(CMyComDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_SIZE()
ON_BN_CLICKED(IDC_BTOPENCOM, OnBtOpenCom)
ON_WM_CLOSE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMyComDlg message handlers
BOOL CMyComDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
//网址
CString strWeb;
strWeb.LoadString(IDS_WEB);
if (!strWeb.IsEmpty())
{
pSysMenu->AppendMenu(MF_STRING, IDM_WEB, strWeb);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
WINDOWPLACEMENT WndStatus;
CRect rect;
int nCmdShow;
rect.left = AfxGetApp()->GetProfileInt("WNDSTATUS","LEFT",100);
rect.top = AfxGetApp()->GetProfileInt("WNDSTATUS","TOP",100);
rect.right = AfxGetApp()->GetProfileInt("WNDSTATUS","RIGHT",500);
rect.bottom = AfxGetApp()->GetProfileInt("WNDSTATUS","BOTTOM",400);
WndStatus.rcNormalPosition = rect;
WndStatus.flags= AfxGetApp()->GetProfileInt("WNDSTATUS","FLAG",0);
nCmdShow = AfxGetApp()->GetProfileInt("WNDSTATUS","SHOWCMD",SW_SHOW);
WndStatus.showCmd = nCmdShow;
WndStatus.ptMinPosition = CPoint(0,0);
SetWindowPlacement(&WndStatus);
m_ComAction = FALSE;
RefreshControl();
return TRUE; // return TRUE unless you set the focus to a control
}
void CMyComDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else if ((nID & 0xFFF0) == IDM_WEB)
{
MessageBox("web");
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CMyComDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
/* CWnd * pWnd = GetDlgItem(IDC_BTOPENCOM);
CDC * pDC = pWnd->GetDC();
pWnd->Invalidate();
pWnd->UpdateWindow();
pDC->SelectStockObject(BLACK_BRUSH);
pDC->Rectangle(0,0,10,10);
pWnd->ReleaseDC(pDC);
*/
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CMyComDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CMyComDlg::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
CButton * myB = (CButton * )GetDlgItem(IDC_BTSEND);
}
void CMyComDlg::OnBtOpenCom()
{
// TODO: Add your control notification handler code here
// open com or close com
if (m_ComAction)
{
CBitmap myBitmap;
myBitmap.LoadBitmap(IDB_BITMAPOPEN);
//m_ComPort.KillThreadClosePort();
//m_ComPort.StopMonitoring();
m_ComPort.ClosePort();
CButton * myb = ((CButton *)this->GetDlgItem(IDC_BTOPENCOM));
myb->SetWindowText(_T("打开串口"));
m_ComAction = FALSE;
}
else {
CBitmap myBitmap;
myBitmap.LoadBitmap(IDB_BITMAPOPEN);
CStatic * myPic = (CStatic *)GetDlgItem(IDC_STATIC);
myPic->SetBitmap(myBitmap);
m_ComPort.InitPort(this,1,57600,'N',8,1);
m_ComPort.StartMonitoring();
CButton * myb = ((CButton *)GetDlgItem(IDC_BTOPENCOM));
myb->SetWindowText(_T("关闭串口"));
m_ComAction = TRUE;
}
RefreshControl();
}
void CAboutDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
//CDialog::OnLButtonDown(nFlags, point);
CString myURL = "http://mycom.googlecode.com";
ShellExecute(NULL, _T("open"), myURL.operator LPCTSTR(), NULL, NULL, 2); // open web
}
void CMyComDlg::OnClose()
{
// TODO: Add your message handler code here and/or call default
WINDOWPLACEMENT WndStatus;
GetWindowPlacement(&WndStatus);
AfxGetApp()->WriteProfileInt("WNDSTATUS","FLAG",WndStatus.flags);
AfxGetApp()->WriteProfileInt("WNDSTATUS","SHOWCMD",WndStatus.showCmd);
AfxGetApp()->WriteProfileInt("WNDSTATUS","LEFT",WndStatus.rcNormalPosition.left);
AfxGetApp()->WriteProfileInt("WNDSTATUS","RIGHT",WndStatus.rcNormalPosition.right);
AfxGetApp()->WriteProfileInt("WNDSTATUS","TOP",WndStatus.rcNormalPosition.top);
AfxGetApp()->WriteProfileInt("WNDSTATUS","BOTTOM",WndStatus.rcNormalPosition.bottom);
CDialog::OnClose();
}
void CMyComDlg::RefreshControl(void)
{
// send botton
GetDlgItem(IDC_BTSEND)->EnableWindow(m_ComAction);
GetDlgItem(IDC_BTCOMMAND_A)->EnableWindow(m_ComAction);
GetDlgItem(IDC_BTCOMMAND_B)->EnableWindow(m_ComAction);
GetDlgItem(IDC_BTCOMMAND_C)->EnableWindow(m_ComAction);
GetDlgItem(IDC_BTCOMMAND_D)->EnableWindow(m_ComAction);
GetDlgItem(IDC_BTCOMMAND_E)->EnableWindow(m_ComAction);
GetDlgItem(IDC_BTCOMMAND_F)->EnableWindow(m_ComAction);
GetDlgItem(IDC_BTCOMMAND_G)->EnableWindow(m_ComAction);
GetDlgItem(IDC_BTCOMMAND_H)->EnableWindow(m_ComAction);
// com param
GetDlgItem(IDC_CBCOM)->EnableWindow(!m_ComAction);
GetDlgItem(IDC_CBBaud)->EnableWindow(!m_ComAction);
//GetDlgItem(IDC_STATICCOMIMG)->VisielbWindow(!m_ComAction);
}
| [
"mrlong.com@4b492708-d941-0410-bea8-19b0d5ba84a5"
]
| [
[
[
1,
303
]
]
]
|
2ba4612ce30fa26f70da7d9474711a2b5769f2f6 | 7f4230cae41e0712d5942960674bfafe4cccd1f1 | /code/IFCLoader.h | c3d51b601e2adad98941eda0bba06d3a8fdfd535 | [
"BSD-3-Clause"
]
| permissive | tonttu/assimp | c6941538b3b3c3d66652423415dea098be21f37a | 320a7a7a7e0422e4d8d9c2a22b74cb48f74b14ce | refs/heads/master | 2021-01-16T19:56:09.309754 | 2011-06-07T20:00:41 | 2011-06-07T20:00:41 | 1,295,427 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,852 | h | /*
Open Asset Import Library (ASSIMP)
----------------------------------------------------------------------
Copyright (c) 2006-2010, ASSIMP Development Team
All rights reserved.
Redistribution and use of this software 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 the ASSIMP team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the ASSIMP Development Team.
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.
----------------------------------------------------------------------
*/
/** @file IFC.h
* @brief Declaration of the Industry Foundation Classes (IFC) loader main class
*/
#ifndef INCLUDED_AI_IFC_LOADER_H
#define INCLUDED_AI_IFC_LOADER_H
#include "BaseImporter.h"
#include "LogAux.h"
namespace Assimp {
// TinyFormatter.h
namespace Formatter {
template <typename T,typename TR, typename A> class basic_formatter;
typedef class basic_formatter< char, std::char_traits<char>, std::allocator<char> > format;
}
namespace STEP {
class DB;
}
// -------------------------------------------------------------------------------------------
/** Load the IFC format, which is an open specification to describe building and construction
industry data.
See http://en.wikipedia.org/wiki/Industry_Foundation_Classes
*/
// -------------------------------------------------------------------------------------------
class IFCImporter : public BaseImporter, public LogFunctions<IFCImporter>
{
friend class Importer;
protected:
/** Constructor to be privately used by Importer */
IFCImporter();
/** Destructor, private as well */
~IFCImporter();
public:
// --------------------
bool CanRead( const std::string& pFile,
IOSystem* pIOHandler,
bool checkSig
) const;
protected:
// --------------------
void GetExtensionList(std::set<std::string>& app);
// --------------------
void SetupProperties(const Importer* pImp);
// --------------------
void InternReadFile( const std::string& pFile,
aiScene* pScene,
IOSystem* pIOHandler
);
private:
public:
// loader settings, publicy accessible via their corresponding AI_CONFIG constants
struct Settings
{
Settings()
: skipSpaceRepresentations()
, skipCurveRepresentations()
, useCustomTriangulation()
{}
bool skipSpaceRepresentations;
bool skipCurveRepresentations;
bool useCustomTriangulation;
};
private:
Settings settings;
}; // !class IFCImporter
} // end of namespace Assimp
#endif // !INCLUDED_AI_IFC_LOADER_H
| [
"aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f"
]
| [
[
[
1,
133
]
]
]
|
9187e8eb0c8e6e467ee2d4ea9412d20cadcd8a16 | 2e5fd1fc05c0d3b28f64abc99f358145c3ddd658 | /deps/quickfix/src/C++/SocketAcceptor.cpp | 830f2ea17e5cbebad9e008aed2af85875a950546 | [
"BSD-2-Clause"
]
| permissive | indraj/fixfeed | 9365c51e2b622eaff4ce5fac5b86bea86415c1e4 | 5ea71aab502c459da61862eaea2b78859b0c3ab3 | refs/heads/master | 2020-12-25T10:41:39.427032 | 2011-02-15T13:38:34 | 2011-02-15T20:50:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,960 | cpp | /****************************************************************************
** Copyright (c) quickfixengine.org All rights reserved.
**
** This file is part of the QuickFIX FIX Engine
**
** This file may be distributed under the terms of the quickfixengine.org
** license as defined by quickfixengine.org and appearing in the file
** LICENSE included in the packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.quickfixengine.org/LICENSE for licensing information.
**
** Contact [email protected] if any conditions of this licensing are
** not clear to you.
**
****************************************************************************/
#ifdef _MSC_VER
#include "stdafx.h"
#else
#include "config.h"
#endif
#include "CallStack.h"
#include "SocketAcceptor.h"
#include "Session.h"
#include "Settings.h"
#include "Utility.h"
#include "Exceptions.h"
namespace FIX
{
SocketAcceptor::SocketAcceptor( Application& application,
MessageStoreFactory& factory,
const SessionSettings& settings ) throw( ConfigError )
: Acceptor( application, factory, settings ),
m_pServer( 0 ) {}
SocketAcceptor::SocketAcceptor( Application& application,
MessageStoreFactory& factory,
const SessionSettings& settings,
LogFactory& logFactory ) throw( ConfigError )
: Acceptor( application, factory, settings, logFactory ),
m_pServer( 0 )
{
}
SocketAcceptor::~SocketAcceptor()
{
SocketConnections::iterator iter;
for ( iter = m_connections.begin(); iter != m_connections.end(); ++iter )
delete iter->second;
}
void SocketAcceptor::onConfigure( const SessionSettings& s )
throw ( ConfigError )
{ QF_STACK_PUSH(SocketAcceptor::onConfigure)
std::set<SessionID> sessions = s.getSessions();
std::set<SessionID>::iterator i;
for( i = sessions.begin(); i != sessions.end(); ++i )
{
const Dictionary& settings = s.get( *i );
settings.getLong( SOCKET_ACCEPT_PORT );
if( settings.has(SOCKET_REUSE_ADDRESS) )
settings.getBool( SOCKET_REUSE_ADDRESS );
if( settings.has(SOCKET_NODELAY) )
settings.getBool( SOCKET_NODELAY );
}
QF_STACK_POP
}
void SocketAcceptor::onInitialize( const SessionSettings& s )
throw ( RuntimeError )
{ QF_STACK_PUSH(SocketAcceptor::onInitialize)
short port = 0;
try
{
m_pServer = new SocketServer( 1 );
std::set<SessionID> sessions = s.getSessions();
std::set<SessionID>::iterator i = sessions.begin();
for( ; i != sessions.end(); ++i )
{
Dictionary settings = s.get( *i );
short port = (short)settings.getLong( SOCKET_ACCEPT_PORT );
const bool reuseAddress = settings.has( SOCKET_REUSE_ADDRESS ) ?
s.get().getBool( SOCKET_REUSE_ADDRESS ) : true;
const bool noDelay = settings.has( SOCKET_NODELAY ) ?
s.get().getBool( SOCKET_NODELAY ) : false;
const int sendBufSize = settings.has( SOCKET_SEND_BUFFER_SIZE ) ?
s.get().getLong( SOCKET_SEND_BUFFER_SIZE ) : 0;
const int rcvBufSize = settings.has( SOCKET_RECEIVE_BUFFER_SIZE ) ?
s.get().getLong( SOCKET_RECEIVE_BUFFER_SIZE ) : 0;
m_portToSessions[port].insert( *i );
m_pServer->add( port, reuseAddress, noDelay, sendBufSize, rcvBufSize );
}
}
catch( SocketException& e )
{
throw RuntimeError( "Unable to create, bind, or listen to port "
+ IntConvertor::convert( (unsigned short)port ) + " (" + e.what() + ")" );
}
QF_STACK_POP
}
void SocketAcceptor::onStart()
{ QF_STACK_PUSH(SocketAcceptor::onStart)
while ( !isStopped() && m_pServer && m_pServer->block( *this ) ) {}
if( !m_pServer )
return;
time_t start = 0;
time_t now = 0;
::time( &start );
while ( isLoggedOn() )
{
m_pServer->block( *this );
if( ::time(&now) -5 >= start )
break;
}
m_pServer->close();
delete m_pServer;
m_pServer = 0;
QF_STACK_POP
}
bool SocketAcceptor::onPoll( double timeout )
{ QF_STACK_PUSH(SocketAcceptor::onPoll)
if( !m_pServer )
return false;
time_t start = 0;
time_t now = 0;
if( isStopped() )
{
if( start == 0 )
::time( &start );
if( !isLoggedOn() )
{
start = 0;
return false;
}
if( ::time(&now) - 5 >= start )
{
start = 0;
return false;
}
}
m_pServer->block( *this, true, timeout );
return true;
QF_STACK_POP
}
void SocketAcceptor::onStop()
{ QF_STACK_PUSH(SocketAcceptor::onStop)
QF_STACK_POP
}
void SocketAcceptor::onConnect( SocketServer& server, int a, int s )
{ QF_STACK_PUSH(SocketAcceptor::onConnect)
if ( !socket_isValid( s ) ) return;
SocketConnections::iterator i = m_connections.find( s );
if ( i != m_connections.end() ) return;
int port = server.socketToPort( a );
Sessions sessions = m_portToSessions[port];
m_connections[ s ] = new SocketConnection( s, sessions, &server.getMonitor() );
std::stringstream stream;
stream << "Accepted connection from " << socket_peername( s ) << " on port " << port;
if( getLog() )
getLog()->onEvent( stream.str() );
QF_STACK_POP
}
void SocketAcceptor::onWrite( SocketServer& server, int s )
{ QF_STACK_PUSH(SocketAcceptor::onWrite)
SocketConnections::iterator i = m_connections.find( s );
if ( i == m_connections.end() ) return ;
SocketConnection* pSocketConnection = i->second;
if( pSocketConnection->processQueue() )
pSocketConnection->unsignal();
QF_STACK_POP
}
bool SocketAcceptor::onData( SocketServer& server, int s )
{ QF_STACK_PUSH(SocketAcceptor::onData)
SocketConnections::iterator i = m_connections.find( s );
if ( i == m_connections.end() ) return false;
SocketConnection* pSocketConnection = i->second;
return pSocketConnection->read( *this, server );
QF_STACK_POP
}
void SocketAcceptor::onDisconnect( SocketServer&, int s )
{ QF_STACK_PUSH(SocketAcceptor::onDisconnect)
SocketConnections::iterator i = m_connections.find( s );
if ( i == m_connections.end() ) return ;
SocketConnection* pSocketConnection = i->second;
Session* pSession = pSocketConnection->getSession();
if ( pSession ) pSession->disconnect();
delete pSocketConnection;
m_connections.erase( s );
QF_STACK_POP
}
void SocketAcceptor::onError( SocketServer& ) {}
void SocketAcceptor::onTimeout( SocketServer& )
{ QF_STACK_PUSH(SocketAcceptor::onInitialize)
SocketConnections::iterator i;
for ( i = m_connections.begin(); i != m_connections.end(); ++i )
i->second->onTimeout();
QF_STACK_POP
}
}
| [
"[email protected]"
]
| [
[
[
1,
249
]
]
]
|
232bd5c0f3d21ebb9cb7008366296642df25e92c | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/conjurer/conjurer/src/conjurer/ninguitoolprismarea_main.cc | 6cda4fda320fb2ec920b0bd67ab6f918469a9d5c | []
| 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 | 14,691 | cc | #include "precompiled/pchconjurerapp.h"
//------------------------------------------------------------------------------
// ninguitoolprismarea_main.cc
// (C) 2004 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "conjurer/ninguitoolprismarea.h"
#include "kernel/nkernelserver.h"
#include "ntrigger/nctriggershape.h"
#include "conjurer/objectplacingundocmd.h"
#include "conjurer/polygontriggerundocmd.h"
#include "nlevel/nlevel.h"
#include "nlevel/nlevelmanager.h"
#include "ndebug/nceditor.h"
#include "zombieentity/nctransform.h"
#include "input/ninputserver.h"
#include "nlayermanager/nlayermanager.h"
#include "mathlib/polygon.h"
#include "nworldinterface/nworldinterface.h"
#include "zombieentity/ncsubentity.h"
#include "zombieentity/ncsuperentity.h"
//------------------------------------------------------------------------------
nNebulaScriptClass(nInguiToolPrismArea, "ninguitool");
//------------------------------------------------------------------------------
const float screenVertexSize = 0.01f;
const float edgeRelativeSize = 0.01f;
//------------------------------------------------------------------------------
/**
*/
nInguiToolPrismArea::nInguiToolPrismArea():
prismHeight(0.0f),
triggerPosSet( false ),
selectedVertex( -1 )
{
// Default shader for line drawer
this->lineDrawer.SetShaderPath("shaders:defaulttool.fx");
this->label = "Place polygon area trigger";
this->pickWhileIdle = true;
this->triggerClassTypeName = "neareatrigger";
this->triggerClassName = this->triggerClassTypeName;
}
//------------------------------------------------------------------------------
/**
*/
nInguiToolPrismArea::~nInguiToolPrismArea()
{
// empty
}
//------------------------------------------------------------------------------
/**
@brief Handle input in a viewport.
*/
bool
nInguiToolPrismArea::HandleInput( nAppViewport* /*vp*/ )
{
// End the line
if ( nInputServer::Instance()->GetButton("return") )
{
this->FinishLine();
return true;
}
// Cancel the line
if ( nInputServer::Instance()->GetButton("cancel") )
{
this->CancelLine();
return true;
}
return false;
}
//------------------------------------------------------------------------------
/**
*/
float
nInguiToolPrismArea::Pick( nAppViewport* vp, vector2 mp, line3 ray )
{
float t = 0.0f;
if ( ! this->triggerPosSet )
{
t = nInguiToolPhyPick::Pick(vp, mp, ray);
if ( t <= 0.0f )
{
return -1.0f;
}
}
else
{
// Calculate position of new point to be added
plane p( vector3(0.0f, this->triggerPos.y, 0.0f), vector3(1.0f, this->triggerPos.y, 0.0f), vector3(0.0f, this->triggerPos.y, 1.0f) );
if ( p.intersect(ray, t) )
{
vector3 point = ray.ipol( t );
// Can be used when drawing the current position before adding to the line
this->lastPos = point;
}
else
{
t = -1.0f;
}
}
// Try to select a vertex for visual feedback
if ( this->GetState() <= nInguiTool::Inactive )
{
this->selectedVertex = this->SelectVertex( this->lastPos );
}
return t;
}
//------------------------------------------------------------------------------
/**
*/
bool
nInguiToolPrismArea::Apply( nTime /*dt*/ )
{
if ( ! this->triggerPosSet )
{
this->triggerPos = this->lastPos;
triggerPosSet = true;
}
else
{
if ( this->GetState() <= nInguiTool::Inactive )
{
// Try to select a vertex
this->selectedVertex = this->SelectVertex( this->lastPos );
// If didn't select any vertex..
if ( this->selectedVertex < 0 )
{
// Try to select an edge: inserts point
polygon pol( this->line );
int segment;
float d = pol.GetDistance2d( this->lastPos, segment );
if ( segment >= 0 && abs( d ) > 0.0f && abs( d ) < 1.0f + pol.GetSegmentWidth( segment ) * edgeRelativeSize )
{
// Insert new point and select it
int insertPos = ( segment + 1 ) % this->line.Size();
this->line.Insert( insertPos, this->lastPos );
this->selectedVertex = insertPos;
this->vertexSizes.Insert( insertPos, 1.0f );
}
else
{
// Create new point and select it
this->line.Append( this->lastPos );
this->selectedVertex = this->line.Size() - 1;
this->vertexSizes.Append( 1.0f );
}
}
}
// Move selected point
if ( this->selectedVertex >= 0 && this->selectedVertex < this->line.Size() )
{
this->line[ this->selectedVertex ] = this->lastPos;
}
// If line is not convex, remove selected point
polygon pol( this->line );
if ( this->selectedVertex >= 0 && this->line.Size() > 3 && ! pol.IsConvex() )
{
this->line.EraseQuick( this->selectedVertex );
this->vertexSizes.EraseQuick( this->selectedVertex );
this->selectedVertex = -1;
}
}
return true;
}
//------------------------------------------------------------------------------
/**
@brief Set height of prism
@param h Height. 0 means infinite (2D polygon test)
*/
void
nInguiToolPrismArea::SetHeight( float h )
{
if ( h < 0.0f)
{
h = 0.0f;
}
this->prismHeight = h;
}
//------------------------------------------------------------------------------
/**
*/
float
nInguiToolPrismArea::GetHeight()
{
return this->prismHeight;
}
//------------------------------------------------------------------------------
void
nInguiToolPrismArea::SetState( int s )
{
nInguiTool::SetState( s );
if ( s == nInguiTool::NotInited )
{
this->CancelLine();
}
}
//------------------------------------------------------------------------------
/**
@brief Called when tool has been selected
*/
void
nInguiToolPrismArea::OnSelected()
{
this->entityInstance = 0;
// Check if selection is a polygon area trigger
if ( 1 == this->refObjState->GetSelectionCount() )
{
nEntityObject * selectedEntityObject = this->refObjState->GetSelectedEntity( 0 );
if ( this->CanEditEntityObject( selectedEntityObject ) )
{
// Select the trigger for editing instead of creating a new one
this->entityInstance = selectedEntityObject;
// Get polygon vertices
ncTriggerShape* shape = selectedEntityObject->GetComponentSafe<ncTriggerShape>();
polygon polygon1 = shape->GetPolygon();
this->triggerPosSet = true;
this->triggerPos = selectedEntityObject->GetComponentSafe<ncTransform>()->GetPosition();
this->selectedVertex = polygon1.GetNumVertices() - 1;
// Fill edit line
this->line.Reset();
this->vertexSizes.Reset();
for ( int i = 0; i < polygon1.GetNumVertices(); i++ )
{
this->line.Append( polygon1.GetVertex( i ) + this->triggerPos );
this->vertexSizes.Append( 1.0f );
}
// Set trigger entity dirty
selectedEntityObject->SetObjectDirty( true );
}
}
}
//------------------------------------------------------------------------------
void
nInguiToolPrismArea::FinishLine()
{
if ( this->line.Size() < 3 || ! this->triggerPosSet )
{
// Can't create with < 3 points
this->CancelLine();
return;
}
if ( this->line.Size() > 3 )
{
polygon pol( this->line );
if ( ! pol.IsConvex() )
{
// Can't create this line (not convex)
return;
}
}
// Create trigger if didn't exist
bool triggerIsNew = false;
if ( ! this->entityInstance )
{
this->entityInstance = this->CreateTrigger();
triggerIsNew = true;
}
if ( ! this->entityInstance )
{
// Failure, trigger couldn't be created
return;
}
// Set trigger position
this->SetTriggerPosition();
ncTriggerShape* shape = this->entityInstance->GetComponentSafe<ncTriggerShape>();
n_assert( shape );
// Store old vertices
nArray<vector3> oldVertices;
if ( ! triggerIsNew )
{
const polygon & oldPolygon = shape->GetPolygon();
oldVertices = oldPolygon.GetVerticesReadOnly();
}
// Set trigger shape vertices
shape->SetPolygonVertices( this->line );
// Set prism height
if ( triggerIsNew )
{
shape->SetHeight( this->prismHeight );
}
// Make undo command
if ( ! this->entityInstance->GetComponent<ncSubentity>() )
{
UndoCmd* newCmd = 0;
if ( triggerIsNew )
{
newCmd = n_new( ObjectPlacingUndoCmd( this->entityInstance, this->GetLabel().Get() ) );
// Signal GUI that some entity could have been created or deleted
this->refObjState->SetEntityPlaced( this->entityInstance );
}
else
{
newCmd = n_new( PolygonTriggerUndoCmd( this->entityInstance, &oldVertices, &this->line ) );
}
if ( newCmd )
{
nString str = this->GetLabel();
newCmd->SetLabel( str );
nUndoServer::Instance()->NewCommand( newCmd );
}
}
// Update selection
this->refObjState->ResetSelection();
this->refObjState->AddEntityToSelection( this->entityInstance->GetId() );
// Reset tool
this->line.Reset();
this->selectedVertex = -1;
this->triggerPosSet = false;
this->entityInstance = 0;
this->vertexSizes.Reset();
if ( !this->isSticky )
{
this->refObjState->SelectToolAndSignalChange( nObjectEditorState::ToolSelection );
}
}
//------------------------------------------------------------------------------
/**
@brief Obtain class name and if it subentity and creates a trigger
@returns Created trigger
*/
nEntityObject *
nInguiToolPrismArea::CreateTrigger()
{
bool isSubentity = this->refObjState->GetSelectionMode() == nObjectEditorState::ModeSubentity;
// Create trigger
if ( isSubentity )
{
// Subentity
nEntityObject* superEnt = this->refObjState->GetSelectionModeEntity();
n_assert( superEnt );
return nWorldInterface::Instance()->NewLocalEntity( this->triggerClassName.Get(), this->triggerPos, true, superEnt );
}
else
{
// Normal entity
return nWorldInterface::Instance()->NewEntity( this->triggerClassName.Get(), this->triggerPos );
}
}
//------------------------------------------------------------------------------
/**
*/
void
nInguiToolPrismArea::SetTriggerPosition()
{
n_assert( this->entityInstance );
// Set trigger position
this->entityInstance->GetComponentSafe<ncTransform>()->SetPosition( this->triggerPos );
if ( this->entityInstance->GetComponent<ncSubentity>() )
{
this->entityInstance->GetComponentSafe<ncSubentity>()->UpdateRelativePosition();
}
// Make the line relative to first point
for ( int v = 0; v < this->line.Size(); v++ )
{
this->line[ v ] = this->line[ v ] - this->triggerPos;
}
}
//------------------------------------------------------------------------------
void
nInguiToolPrismArea::CancelLine()
{
this->line.Reset();
this->triggerPosSet = false;
this->selectedVertex = -1;
}
//------------------------------------------------------------------------------
/**
Get a vertex close to pos parameter
*/
int
nInguiToolPrismArea::SelectVertex(vector3 & pos) const
{
for ( int i = 0; i < this->line.Size(); i++ )
{
if ( ( pos - this->line[i] ).len() <= this->vertexSizes[i] )
{
return i;
}
}
return -1;
}
//------------------------------------------------------------------------------
/**
*/
void
nInguiToolPrismArea::Draw( nAppViewport* vp, nCamera2* /*camera*/ )
{
// Get gfx server pointer
nGfxServer2* gfxServer = nGfxServer2::Instance();
// Draw trigger pos
if ( triggerPosSet )
{
gfxServer->BeginShapes();
matrix44 m;
m.scale( vector3( 1.0f, 1.0f, 1.0f ) * 0.15f );
m.set_translation( this->triggerPos );
gfxServer->DrawShape( nGfxServer2::Sphere, m, vector4(1.0f, 1.0f, 1.0f, 1.f) );
gfxServer->EndShapes();
}
if ( this->line.Size() > 0 )
{
// Draw line
vector4 col(0.15f, 0.45f, 0.6f, 0.3f);
vector4 colSel(0.3f, 0.9f, 1.0f, 0.7f);
vector3 extr(0.0f, max( 0.2f, this->prismHeight ), 0.0f);
this->lineDrawer.DrawExtruded3DLine( &this->line[ 0 ], this->line.Size(), &col, 1, extr, true );
gfxServer->BeginShapes();
// Draw points
for ( int i = 0; i < this->line.Size(); i++ )
{
vector4 c = col;
if ( this->selectedVertex == i )
{
c = colSel;
}
this->vertexSizes[i] = this->Screen2WorldObjectSize( vp, this->line[ i ], screenVertexSize );
matrix44 m;
m.scale( vector3( 1.0f, 1.0f, 1.0f ) * this->vertexSizes[i] );
m.set_translation( this->line[ i ] );
gfxServer->DrawShape( nGfxServer2::Sphere, m, c );
}
gfxServer->EndShapes();
}
}
//------------------------------------------------------------------------------
/**
*/
bool
nInguiToolPrismArea::CanEditEntityObject( nEntityObject* anObject)
{
if ( anObject->IsA( this->triggerClassTypeName.Get() ) )
{
ncTriggerShape* shape = anObject->GetComponentSafe<ncTriggerShape>();
if ( strcmp(shape->GetShapeType(), "polygon") == 0 )
{
return true;
}
}
return false;
}
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
506
]
]
]
|
40cbd14a848bba5440cfca2d5d46407bf5d9ffb3 | 0f19aa6d0ba7b58e5ded3c63bb6846ab84d84c88 | /dependencies/irrlicht/examples/21.Quake3Explorer/main.cpp | 450247852d6aa2e7f175da17b03b6784f0408dab | [
"LicenseRef-scancode-other-permissive",
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | aep/slay | 200387b28b4dc1d21a9f5931967a85ff610d563a | daa808795fe352135e75a101520f208d4ba90433 | refs/heads/master | 2022-11-11T21:18:55.229691 | 2009-11-07T05:50:28 | 2009-11-07T05:50:28 | 275,114,718 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 59,274 | cpp | /** Example 021 Quake3 Explorer
This Tutorial shows how to load different Quake 3 maps.
Features:
- Load BSP Archives at Runtime from the menu
- Load a Map from the menu. Showing with Screenshot
- Set the VideoDriver at runtime from menu
- Adjust GammaLevel at runtime
- Create SceneNodes for the Shaders
- Load EntityList and create Entity SceneNodes
- Create Players with Weapons and with Collison Respsone
- Play music
You can download the Quake III Arena demo ( copyright id software )
at the following location:
ftp://ftp.idsoftware.com/idstuff/quake3/win32/q3ademo.exe
Copyright 2006-2009 Burningwater, Thomas Alten
*/
#include "q3factory.h"
#include "sound.h"
#include <iostream>
/*!
Game Data is used to hold Data which is needed to drive the game
*/
struct GameData
{
GameData ( const path &startupDir);
void setDefault ();
s32 save ( const path &filename );
s32 load ( const path &filename );
s32 debugState;
s32 gravityState;
s32 flyTroughState;
s32 wireFrame;
s32 guiActive;
s32 guiInputActive;
f32 GammaValue;
s32 retVal;
s32 sound;
path StartupDir;
stringw CurrentMapName;
array<path> CurrentArchiveList;
vector3df PlayerPosition;
vector3df PlayerRotation;
tQ3EntityList Variable;
Q3LevelLoadParameter loadParam;
SIrrlichtCreationParameters deviceParam;
funcptr_createDeviceEx createExDevice;
IrrlichtDevice *Device;
};
/*!
*/
GameData::GameData ( const path &startupDir)
{
retVal = 0;
createExDevice = 0;
Device = 0;
StartupDir = startupDir;
setDefault ();
}
/*!
set default settings
*/
void GameData::setDefault ()
{
debugState = EDS_OFF;
gravityState = 1;
flyTroughState = 0;
wireFrame = 0;
guiActive = 1;
guiInputActive = 0;
GammaValue = 1.f;
// default deviceParam;
#if defined ( _IRR_WINDOWS_ )
deviceParam.DriverType = EDT_DIRECT3D9;
#else
deviceParam.DriverType = EDT_OPENGL;
#endif
deviceParam.WindowSize.Width = 800;
deviceParam.WindowSize.Height = 600;
deviceParam.Fullscreen = false;
deviceParam.Bits = 32;
deviceParam.ZBufferBits = 32;
deviceParam.Vsync = false;
deviceParam.AntiAlias = false;
// default Quake3 loadParam
loadParam.defaultLightMapMaterial = EMT_LIGHTMAP;
loadParam.defaultModulate = EMFN_MODULATE_1X;
loadParam.defaultFilter = EMF_ANISOTROPIC_FILTER;
loadParam.verbose = 2;
loadParam.mergeShaderBuffer = 1; // merge meshbuffers with same material
loadParam.cleanUnResolvedMeshes = 1; // should unresolved meshes be cleaned. otherwise blue texture
loadParam.loadAllShaders = 1; // load all scripts in the script directory
loadParam.loadSkyShader = 0; // load sky Shader
loadParam.alpharef = 1;
sound = 0;
CurrentMapName = "";
CurrentArchiveList.clear ();
//! Explorer Media directory
CurrentArchiveList.push_back ( StartupDir + "../../media/" );
//! Add the original quake3 files before you load your custom map
//! Most mods are using the original shaders, models&items&weapons
CurrentArchiveList.push_back ( "/q/baseq3/" );
CurrentArchiveList.push_back ( StartupDir + "../../media/map-20kdm2.pk3" );
}
/*!
Load the current game State from a typical quake3 cfg file
*/
s32 GameData::load ( const path &filename )
{
if (!Device)
return 0;
//! the quake3 mesh loader can also handle *.shader and *.cfg file
IQ3LevelMesh* mesh = (IQ3LevelMesh*) Device->getSceneManager()->getMesh ( filename );
if (!mesh)
return 0;
tQ3EntityList &entityList = mesh->getEntityList ();
stringc s;
u32 pos;
for ( u32 e = 0; e != entityList.size (); ++e )
{
//dumpShader ( s, &entityList[e], false );
//printf ( s.c_str () );
for ( u32 g = 0; g != entityList[e].getGroupSize (); ++g )
{
const SVarGroup *group = entityList[e].getGroup ( g );
for ( u32 index = 0; index < group->Variable.size (); ++index )
{
const SVariable &v = group->Variable[index];
pos = 0;
if ( v.name == "playerposition" )
{
PlayerPosition = getAsVector3df ( v.content, pos );
}
else
if ( v.name == "playerrotation" )
{
PlayerRotation = getAsVector3df ( v.content, pos );
}
}
}
}
return 1;
}
/*!
Store the current game State in a quake3 configuration file
*/
s32 GameData::save ( const path &filename )
{
return 0;
if (!Device)
return 0;
c8 buf[128];
u32 i;
// Store current Archive for restart
CurrentArchiveList.clear();
IFileSystem *fs = Device->getFileSystem();
for ( i = 0; i != fs->getFileArchiveCount(); ++i )
{
CurrentArchiveList.push_back ( fs->getFileArchive(i)->getFileList()->getPath() );
}
// Store Player Position and Rotation
ICameraSceneNode * camera = Device->getSceneManager()->getActiveCamera ();
if ( camera )
{
PlayerPosition = camera->getPosition ();
PlayerRotation = camera->getRotation ();
}
IWriteFile *file = fs->createAndWriteFile ( filename );
if (!file)
return 0;
snprintf ( buf, 128, "playerposition %.f %.f %.f\nplayerrotation %.f %.f %.f\n",
PlayerPosition.X, PlayerPosition.Z, PlayerPosition.Y,
PlayerRotation.X, PlayerRotation.Z, PlayerRotation.Y);
file->write ( buf, (s32) strlen ( buf ) );
for ( i = 0; i != fs->getFileArchiveCount(); ++i )
{
snprintf ( buf, 128, "archive %s\n",stringc ( fs->getFileArchive(i)->getFileList()->getPath() ).c_str () );
file->write ( buf, (s32) strlen ( buf ) );
}
file->drop ();
return 1;
}
/*!
Representing a player
*/
struct Q3Player : public IAnimationEndCallBack
{
Q3Player ()
: Device(0), MapParent(0), Mesh(0), WeaponNode(0), StartPositionCurrent(0)
{
animation[0] = 0;
memset(Anim, 0, sizeof(TimeFire)*4);
}
virtual void OnAnimationEnd(IAnimatedMeshSceneNode* node);
void create ( IrrlichtDevice *device,
IQ3LevelMesh* mesh,
ISceneNode *mapNode,
IMetaTriangleSelector *meta
);
void shutdown ();
void setAnim ( const c8 *name );
void respawn ();
void setpos ( const vector3df &pos, const vector3df& rotation );
ISceneNodeAnimatorCollisionResponse * cam() { return camCollisionResponse ( Device ); }
IrrlichtDevice *Device;
ISceneNode* MapParent;
IQ3LevelMesh* Mesh;
IAnimatedMeshSceneNode* WeaponNode;
s32 StartPositionCurrent;
TimeFire Anim[4];
c8 animation[64];
c8 buf[64];
};
/*!
*/
void Q3Player::shutdown ()
{
setAnim ( 0 );
dropElement (WeaponNode);
if ( Device )
{
ICameraSceneNode* camera = Device->getSceneManager()->getActiveCamera();
dropElement ( camera );
Device = 0;
}
MapParent = 0;
Mesh = 0;
}
/*!
*/
void Q3Player::create ( IrrlichtDevice *device, IQ3LevelMesh* mesh, ISceneNode *mapNode, IMetaTriangleSelector *meta )
{
setTimeFire ( Anim + 0, 200, FIRED );
setTimeFire ( Anim + 1, 5000 );
// load FPS weapon to Camera
Device = device;
Mesh = mesh;
MapParent = mapNode;
ISceneManager *smgr = device->getSceneManager ();
IVideoDriver * driver = device->getVideoDriver();
ICameraSceneNode* camera = 0;
SKeyMap keyMap[10];
keyMap[0].Action = EKA_MOVE_FORWARD;
keyMap[0].KeyCode = KEY_UP;
keyMap[1].Action = EKA_MOVE_FORWARD;
keyMap[1].KeyCode = KEY_KEY_W;
keyMap[2].Action = EKA_MOVE_BACKWARD;
keyMap[2].KeyCode = KEY_DOWN;
keyMap[3].Action = EKA_MOVE_BACKWARD;
keyMap[3].KeyCode = KEY_KEY_S;
keyMap[4].Action = EKA_STRAFE_LEFT;
keyMap[4].KeyCode = KEY_LEFT;
keyMap[5].Action = EKA_STRAFE_LEFT;
keyMap[5].KeyCode = KEY_KEY_A;
keyMap[6].Action = EKA_STRAFE_RIGHT;
keyMap[6].KeyCode = KEY_RIGHT;
keyMap[7].Action = EKA_STRAFE_RIGHT;
keyMap[7].KeyCode = KEY_KEY_D;
keyMap[8].Action = EKA_JUMP_UP;
keyMap[8].KeyCode = KEY_KEY_J;
keyMap[9].Action = EKA_CROUCH;
keyMap[9].KeyCode = KEY_KEY_C;
camera = smgr->addCameraSceneNodeFPS(0, 100.0f, 0.6f, -1, keyMap, 10, false, 0.6f);
camera->setName ( "First Person Camera" );
//camera->setFOV ( 100.f * core::DEGTORAD );
camera->setFarValue( 20000.f );
IAnimatedMeshMD2* weaponMesh = (IAnimatedMeshMD2*) smgr->getMesh("gun.md2");
if ( 0 == weaponMesh )
return;
if ( weaponMesh->getMeshType() == EAMT_MD2 )
{
s32 count = weaponMesh->getAnimationCount();
for ( s32 i = 0; i != count; ++i )
{
snprintf ( buf, 64, "Animation: %s", weaponMesh->getAnimationName(i) );
device->getLogger()->log(buf, ELL_INFORMATION);
}
}
WeaponNode = smgr->addAnimatedMeshSceneNode(
weaponMesh,
smgr->getActiveCamera(),
10,
vector3df( 0, 0, 0),
vector3df(-90,-90,90)
);
WeaponNode->setMaterialFlag(EMF_LIGHTING, false);
WeaponNode->setMaterialTexture(0, driver->getTexture( "gun.jpg"));
WeaponNode->setLoopMode ( false );
WeaponNode->setName ( "tommi the gun man" );
//create a collision auto response animator
ISceneNodeAnimator* anim =
smgr->createCollisionResponseAnimator( meta, camera,
vector3df(30,45,30),
getGravity ( "earth" ),
vector3df(0,40,0),
0.0005f
);
camera->addAnimator( anim );
anim->drop();
if ( meta )
{
meta->drop ();
}
respawn ();
setAnim ( "idle" );
}
/*!
so we need a good starting Position in the level.
we can ask the Quake3 Loader for all entities with class_name "info_player_deathmatch"
*/
void Q3Player::respawn ()
{
ICameraSceneNode* camera = Device->getSceneManager()->getActiveCamera();
Device->getLogger()->log( "respawn" );
if ( StartPositionCurrent >= Q3StartPosition (
Mesh, camera,StartPositionCurrent++,
cam ()->getEllipsoidTranslation() )
)
{
StartPositionCurrent = 0;
}
}
/*
set Player position from saved coordinates
*/
void Q3Player::setpos ( const vector3df &pos, const vector3df &rotation )
{
Device->getLogger()->log( "setpos" );
ICameraSceneNode* camera = Device->getSceneManager()->getActiveCamera();
if ( camera )
{
camera->setPosition ( pos );
camera->setRotation ( rotation );
//! New. FPSCamera and animators catches reset on animate 0
camera->OnAnimate ( 0 );
}
}
/*!
*/
void Q3Player::setAnim ( const c8 *name )
{
if ( name )
{
snprintf ( animation, 64, "%s", name );
if ( WeaponNode )
{
WeaponNode->setAnimationEndCallback ( this );
WeaponNode->setMD2Animation ( animation );
}
}
else
{
animation[0] = 0;
if ( WeaponNode )
{
WeaponNode->setAnimationEndCallback ( 0 );
}
}
}
/*!
*/
void Q3Player::OnAnimationEnd(IAnimatedMeshSceneNode* node)
{
setAnim ( 0 );
}
//! GUIElements
struct GUI
{
GUI ()
{
memset ( this, 0, sizeof ( *this ) );
}
void drop()
{
dropElement ( Window );
dropElement ( Logo );
}
IGUIComboBox* VideoDriver;
IGUIComboBox* VideoMode;
IGUICheckBox* FullScreen;
IGUICheckBox* Bit32;
IGUIScrollBar* MultiSample;
IGUIButton* SetVideoMode;
IGUIScrollBar* Tesselation;
IGUIScrollBar* Gamma;
IGUICheckBox* Collision;
IGUICheckBox* Visible_Map;
IGUICheckBox* Visible_Shader;
IGUICheckBox* Visible_Fog;
IGUICheckBox* Visible_Unresolved;
IGUICheckBox* Visible_Skydome;
IGUIButton* Respawn;
IGUITable* ArchiveList;
IGUIButton* ArchiveAdd;
IGUIButton* ArchiveRemove;
IGUIFileOpenDialog* ArchiveFileOpen;
IGUIButton* ArchiveUp;
IGUIButton* ArchiveDown;
IGUIListBox* MapList;
IGUITreeView* SceneTree;
IGUIStaticText* StatusLine;
IGUIImage* Logo;
IGUIWindow* Window;
};
/*!
CQuake3EventHandler controls the game
*/
class CQuake3EventHandler : public IEventReceiver
{
public:
CQuake3EventHandler( GameData *gameData );
virtual ~CQuake3EventHandler ();
void Animate();
void Render();
void AddArchive ( const path& archiveName );
void LoadMap ( const stringw& mapName, s32 collision );
void CreatePlayers();
void AddSky( u32 dome, const c8 *texture );
Q3Player *GetPlayer ( u32 index ) { return &Player[index]; }
void CreateGUI();
void SetGUIActive( s32 command);
bool OnEvent(const SEvent& eve);
private:
GameData *Game;
IQ3LevelMesh* Mesh;
ISceneNode* MapParent;
ISceneNode* ShaderParent;
ISceneNode* ItemParent;
ISceneNode* UnresolvedParent;
ISceneNode* BulletParent;
ISceneNode* FogParent;
ISceneNode * SkyNode;
IMetaTriangleSelector *Meta;
c8 buf[256];
Q3Player Player[2];
struct SParticleImpact
{
u32 when;
vector3df pos;
vector3df outVector;
};
array<SParticleImpact> Impacts;
void useItem( Q3Player * player);
void createParticleImpacts( u32 now );
void createTextures ();
void addSceneTreeItem( ISceneNode * parent, IGUITreeViewNode* nodeParent);
GUI gui;
void dropMap ();
};
/*!
*/
CQuake3EventHandler::CQuake3EventHandler( GameData *game )
: Game(game), Mesh(0), MapParent(0), ShaderParent(0), ItemParent(0), UnresolvedParent(0),
BulletParent(0), FogParent(0), SkyNode(0), Meta(0)
{
buf[0]=0;
//! Also use 16 Bit Textures for 16 Bit RenderDevice
if ( Game->deviceParam.Bits == 16 )
{
game->Device->getVideoDriver()->setTextureCreationFlag(ETCF_ALWAYS_16_BIT, true);
}
// Quake3 Shader controls Z-Writing
game->Device->getSceneManager()->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
// create internal textures
createTextures ();
sound_init ( game->Device );
Game->Device->setEventReceiver ( this );
}
CQuake3EventHandler::~CQuake3EventHandler ()
{
Player[0].shutdown ();
sound_shutdown ();
Game->save( "explorer.cfg" );
Game->Device->drop();
}
//! create runtime textures smog, fog
void CQuake3EventHandler::createTextures ()
{
IVideoDriver * driver = Game->Device->getVideoDriver();
dimension2du dim ( 64, 64 );
video::ITexture* texture;
video::IImage* image;
u32 i;
u32 x;
u32 y;
u32 * data;
for ( i = 0; i != 8; ++i )
{
image = driver->createImage ( video::ECF_A8R8G8B8, dim);
data = (u32*) image->lock ();
for ( y = 0; y != dim.Height; ++y )
{
for ( x = 0; x != dim.Width; ++x )
{
data [x] = 0xFFFFFFFF;
}
data = (u32*) ( (u8*) data + image->getPitch() );
}
image->unlock();
snprintf ( buf, 64, "smoke_%02d", i );
texture = driver->addTexture( buf, image );
image->drop ();
}
// fog
for ( i = 0; i != 1; ++i )
{
image = driver->createImage ( video::ECF_A8R8G8B8, dim);
data = (u32*) image->lock ();
for ( y = 0; y != dim.Height; ++y )
{
for ( x = 0; x != dim.Width; ++x )
{
data [x] = 0xFFFFFFFF;
}
data = (u32*) ( (u8*) data + image->getPitch() );
}
image->unlock();
snprintf ( buf, 64, "fog_%02d", i );
texture = driver->addTexture( buf, image );
image->drop ();
}
}
/*!
create the GUI
*/
void CQuake3EventHandler::CreateGUI()
{
IGUIEnvironment *env = Game->Device->getGUIEnvironment();
IVideoDriver * driver = Game->Device->getVideoDriver();
gui.drop();
// set skin font
IGUIFont* font = env->getFont("fontlucida.png");
if (font)
env->getSkin()->setFont(font);
env->getSkin()->setColor ( EGDC_BUTTON_TEXT, video::SColor(240,0xAA,0xAA,0xAA) );
env->getSkin()->setColor ( EGDC_3D_HIGH_LIGHT, video::SColor(240,0x22,0x22,0x22) );
env->getSkin()->setColor ( EGDC_3D_FACE, video::SColor(240,0x44,0x44,0x44) );
env->getSkin()->setColor ( EGDC_WINDOW, video::SColor(240,0x66,0x66,0x66) );
// minimal gui size 800x600
dimension2d<u32> dim ( 800, 600 );
dimension2d<u32> vdim ( Game->Device->getVideoDriver()->getScreenSize() );
if ( vdim.Height >= dim.Height && vdim.Width >= dim.Width )
{
//dim = vdim;
}
else
{
}
gui.Window = env->addWindow ( rect<s32> ( 0, 0, dim.Width, dim.Height ), false, L"Quake3 Explorer" );
gui.Window->setToolTipText ( L"Quake3Explorer. Loads and show various BSP File Format and Shaders." );
gui.Window->getCloseButton()->setToolTipText ( L"Quit Quake3 Explorer" );
// add a status line help text
gui.StatusLine = env->addStaticText( 0, rect<s32>( 5,dim.Height - 30,dim.Width - 5,dim.Height - 10),
false, false, gui.Window, -1, true
);
env->addStaticText ( L"VideoDriver:", rect<s32>( dim.Width - 400, 24, dim.Width - 310, 40 ),false, false, gui.Window, -1, false );
gui.VideoDriver = env->addComboBox(rect<s32>( dim.Width - 300, 24, dim.Width - 10, 40 ),gui.Window);
gui.VideoDriver->addItem(L"Direct3D 9.0c", EDT_DIRECT3D9 );
gui.VideoDriver->addItem(L"Direct3D 8.1", EDT_DIRECT3D8 );
gui.VideoDriver->addItem(L"OpenGL 1.5", EDT_OPENGL);
gui.VideoDriver->addItem(L"Software Renderer", EDT_SOFTWARE);
gui.VideoDriver->addItem(L"Burning's Video (TM) Thomas Alten", EDT_BURNINGSVIDEO);
gui.VideoDriver->setSelected ( gui.VideoDriver->getIndexForItemData ( Game->deviceParam.DriverType ) );
gui.VideoDriver->setToolTipText ( L"Use a VideoDriver" );
env->addStaticText ( L"VideoMode:", rect<s32>( dim.Width - 400, 44, dim.Width - 310, 60 ),false, false, gui.Window, -1, false );
gui.VideoMode = env->addComboBox(rect<s32>( dim.Width - 300, 44, dim.Width - 10, 60 ),gui.Window);
gui.VideoMode->setToolTipText ( L"Supported Screenmodes" );
IVideoModeList *modeList = Game->Device->getVideoModeList();
if ( modeList )
{
s32 i;
for ( i = 0; i != modeList->getVideoModeCount (); ++i )
{
u16 d = modeList->getVideoModeDepth ( i );
if ( d < 16 )
continue;
u16 w = modeList->getVideoModeResolution ( i ).Width;
u16 h = modeList->getVideoModeResolution ( i ).Height;
u32 val = w << 16 | h;
if ( gui.VideoMode->getIndexForItemData ( val ) >= 0 )
continue;
f32 aspect = (f32) w / (f32) h;
const c8 *a = "";
if ( core::equals ( aspect, 1.3333333333f ) ) a = "4:3";
else if ( core::equals ( aspect, 1.6666666f ) ) a = "15:9 widescreen";
else if ( core::equals ( aspect, 1.7777777f ) ) a = "16:9 widescreen";
else if ( core::equals ( aspect, 1.6f ) ) a = "16:10 widescreen";
else if ( core::equals ( aspect, 2.133333f ) ) a = "20:9 widescreen";
snprintf ( buf, sizeof ( buf ), "%d x %d, %s",w, h, a );
gui.VideoMode->addItem ( stringw ( buf ).c_str(), val );
}
}
gui.VideoMode->setSelected ( gui.VideoMode->getIndexForItemData (
Game->deviceParam.WindowSize.Width << 16 |
Game->deviceParam.WindowSize.Height ) );
gui.FullScreen = env->addCheckBox ( Game->deviceParam.Fullscreen, rect<s32>( dim.Width - 400, 64, dim.Width - 300, 80 ), gui.Window,-1, L"Fullscreen" );
gui.FullScreen->setToolTipText ( L"Set Fullscreen or Window Mode" );
gui.Bit32 = env->addCheckBox ( Game->deviceParam.Bits == 32, rect<s32>( dim.Width - 300, 64, dim.Width - 240, 80 ), gui.Window,-1, L"32Bit" );
gui.Bit32->setToolTipText ( L"Use 16 or 32 Bit" );
env->addStaticText ( L"MultiSample:", rect<s32>( dim.Width - 235, 64, dim.Width - 150, 80 ),false, false, gui.Window, -1, false );
gui.MultiSample = env->addScrollBar( true, rect<s32>( dim.Width - 150, 64, dim.Width - 70, 80 ), gui.Window,-1 );
gui.MultiSample->setMin ( 0 );
gui.MultiSample->setMax ( 8 );
gui.MultiSample->setSmallStep ( 1 );
gui.MultiSample->setLargeStep ( 1 );
gui.MultiSample->setPos ( Game->deviceParam.AntiAlias );
gui.MultiSample->setToolTipText ( L"Set the MultiSample (disable, 1x, 2x, 4x, 8x )" );
gui.SetVideoMode = env->addButton (rect<s32>( dim.Width - 60, 64, dim.Width - 10, 80 ), gui.Window, -1,L"set" );
gui.SetVideoMode->setToolTipText ( L"Set Video Mode with current values" );
env->addStaticText ( L"Gamma:", rect<s32>( dim.Width - 400, 104, dim.Width - 310, 120 ),false, false, gui.Window, -1, false );
gui.Gamma = env->addScrollBar( true, rect<s32>( dim.Width - 300, 104, dim.Width - 10, 120 ), gui.Window,-1 );
gui.Gamma->setMin ( 50 );
gui.Gamma->setMax ( 350 );
gui.Gamma->setSmallStep ( 1 );
gui.Gamma->setLargeStep ( 10 );
gui.Gamma->setPos ( core::floor32 ( Game->GammaValue * 100.f ) );
gui.Gamma->setToolTipText ( L"Adjust Gamma Ramp ( 0.5 - 3.5)" );
Game->Device->setGammaRamp ( Game->GammaValue, Game->GammaValue, Game->GammaValue, 0.f, 0.f );
env->addStaticText ( L"Tesselation:", rect<s32>( dim.Width - 400, 124, dim.Width - 310, 140 ),false, false, gui.Window, -1, false );
gui.Tesselation = env->addScrollBar( true, rect<s32>( dim.Width - 300, 124, dim.Width - 10, 140 ), gui.Window,-1 );
gui.Tesselation->setMin ( 2 );
gui.Tesselation->setMax ( 12 );
gui.Tesselation->setSmallStep ( 1 );
gui.Tesselation->setLargeStep ( 1 );
gui.Tesselation->setPos ( Game->loadParam.patchTesselation );
gui.Tesselation->setToolTipText ( L"How smooth should curved surfaces be rendered" );
gui.Collision = env->addCheckBox ( true, rect<s32>( dim.Width - 400, 150, dim.Width - 300, 166 ), gui.Window,-1, L"Collision" );
gui.Collision->setToolTipText ( L"Set collision on or off ( flythrough ). \nPress F7 on your Keyboard" );
gui.Visible_Map = env->addCheckBox ( true, rect<s32>( dim.Width - 300, 150, dim.Width - 240, 166 ), gui.Window,-1, L"Map" );
gui.Visible_Map->setToolTipText ( L"Show or not show the static part the Level. \nPress F3 on your Keyboard" );
gui.Visible_Shader = env->addCheckBox ( true, rect<s32>( dim.Width - 240, 150, dim.Width - 170, 166 ), gui.Window,-1, L"Shader" );
gui.Visible_Shader->setToolTipText ( L"Show or not show the Shader Nodes. \nPress F4 on your Keyboard" );
gui.Visible_Fog = env->addCheckBox ( true, rect<s32>( dim.Width - 170, 150, dim.Width - 110, 166 ), gui.Window,-1, L"Fog" );
gui.Visible_Fog->setToolTipText ( L"Show or not show the Fog Nodes. \nPress F5 on your Keyboard" );
gui.Visible_Unresolved = env->addCheckBox ( true, rect<s32>( dim.Width - 110, 150, dim.Width - 10, 166 ), gui.Window,-1, L"Unresolved" );
gui.Visible_Unresolved->setToolTipText ( L"Show the or not show the Nodes the Engine can't handle. \nPress F6 on your Keyboard" );
gui.Visible_Skydome = env->addCheckBox ( true, rect<s32>( dim.Width - 110, 180, dim.Width - 10, 196 ), gui.Window,-1, L"Skydome" );
gui.Visible_Skydome->setToolTipText ( L"Show the or not show the Skydome." );
//Respawn = env->addButton ( rect<s32>( dim.Width - 260, 90, dim.Width - 10, 106 ), 0,-1, L"Respawn" );
env->addStaticText ( L"Archives:", rect<s32>( 5, dim.Height - 530, dim.Width - 600,dim.Height - 514 ),false, false, gui.Window, -1, false );
gui.ArchiveAdd = env->addButton ( rect<s32>( dim.Width - 725, dim.Height - 530, dim.Width - 665, dim.Height - 514 ), gui.Window,-1, L"add" );
gui.ArchiveAdd->setToolTipText ( L"Add an archive, usually packed zip-archives (*.pk3) to the Filesystem" );
gui.ArchiveRemove = env->addButton ( rect<s32>( dim.Width - 660, dim.Height - 530, dim.Width - 600, dim.Height - 514 ), gui.Window,-1, L"del" );
gui.ArchiveRemove->setToolTipText ( L"Remove the selected archive from the FileSystem." );
gui.ArchiveUp = env->addButton ( rect<s32>( dim.Width - 575, dim.Height - 530, dim.Width - 515, dim.Height - 514 ), gui.Window,-1, L"up" );
gui.ArchiveUp->setToolTipText ( L"Arrange Archive Look-up Hirachy. Move the selected Archive up" );
gui.ArchiveDown = env->addButton ( rect<s32>( dim.Width - 510, dim.Height - 530, dim.Width - 440, dim.Height - 514 ), gui.Window,-1, L"down" );
gui.ArchiveDown->setToolTipText ( L"Arrange Archive Look-up Hirachy. Move the selected Archive down" );
gui.ArchiveList = env->addTable ( rect<s32>( 5,dim.Height - 510, dim.Width - 450,dim.Height - 410 ), gui.Window );
gui.ArchiveList->addColumn ( L"Type", 0 );
gui.ArchiveList->addColumn ( L"Real File Path", 1 );
gui.ArchiveList->setColumnWidth ( 0, 60 );
gui.ArchiveList->setColumnWidth ( 1, 284 );
gui.ArchiveList->setToolTipText ( L"Show the attached Archives" );
env->addStaticText ( L"Maps:", rect<s32>( 5, dim.Height - 400, dim.Width - 450,dim.Height - 380 ),false, false, gui.Window, -1, false );
gui.MapList = env->addListBox ( rect<s32>( 5,dim.Height - 380, dim.Width - 450,dim.Height - 40 ), gui.Window, -1, true );
gui.MapList->setToolTipText ( L"Show the current Maps in all Archives.\n Double-Click the Map to start the level" );
// create a visible Scene Tree
env->addStaticText ( L"Scenegraph:", rect<s32>( dim.Width - 400, dim.Height - 400, dim.Width - 5,dim.Height - 380 ),false, false, gui.Window, -1, false );
gui.SceneTree = env->addTreeView( rect<s32>( dim.Width - 400, dim.Height - 380, dim.Width - 5, dim.Height - 40 ),
gui.Window, -1, true, true, false );
gui.SceneTree->setToolTipText ( L"Show the current Scenegraph" );
gui.SceneTree->getRoot()->clearChilds();
addSceneTreeItem ( Game->Device->getSceneManager()->getRootSceneNode(), gui.SceneTree->getRoot() );
IGUIImageList* imageList = env->createImageList( driver->getTexture ( "iconlist.png" ),
dimension2di( 32, 32 ), true );
if ( imageList )
{
gui.SceneTree->setImageList( imageList );
imageList->drop ();
}
// load the engine logo
gui.Logo = env->addImage( driver->getTexture("irrlichtlogo3.png"), position2d<s32>(5, 16 ), true, 0 );
gui.Logo->setToolTipText ( L"The great Irrlicht Engine" );
AddArchive ( "" );
}
/*!
Add an Archive to the FileSystems und updates the GUI
*/
void CQuake3EventHandler::AddArchive ( const path& archiveName )
{
IFileSystem *fs = Game->Device->getFileSystem();
u32 i;
if ( archiveName.size () )
{
bool exists = false;
for ( i = 0; i != fs->getFileArchiveCount(); ++i )
{
if ( fs->getFileArchive(i)->getFileList()->getPath() == archiveName )
{
exists = true;
break;
}
}
if (!exists)
{
fs->addFileArchive(archiveName, true, false);
}
}
// store the current archives in game data
// show the attached Archive in proper order
if ( gui.ArchiveList )
{
gui.ArchiveList->clearRows();
for ( i = 0; i != fs->getFileArchiveCount(); ++i )
{
IFileArchive * archive = fs->getFileArchive ( i );
u32 index = gui.ArchiveList->addRow(i);
core::stringw typeName;
switch(archive->getType())
{
case io::EFAT_ZIP:
typeName = "ZIP";
break;
case io::EFAT_GZIP:
typeName = "gzip";
break;
case io::EFAT_FOLDER:
typeName = "Mount";
break;
case io::EFAT_PAK:
typeName = "PAK";
break;
case io::EFAT_TAR:
typeName = "TAR";
break;
default:
typeName = "archive";
}
gui.ArchiveList->setCellText ( index, 0, typeName );
gui.ArchiveList->setCellText ( index, 1, archive->getFileList()->getPath() );
}
}
// browse the archives for maps
if ( gui.MapList )
{
gui.MapList->clear();
IGUISpriteBank *bank = Game->Device->getGUIEnvironment()->getSpriteBank("sprite_q3map");
if ( 0 == bank )
bank = Game->Device->getGUIEnvironment()->addEmptySpriteBank("sprite_q3map");
SGUISprite sprite;
SGUISpriteFrame frame;
core::rect<s32> r;
bank->getSprites().clear();
bank->getPositions().clear ();
gui.MapList->setSpriteBank ( bank );
u32 g = 0;
core::stringw s;
//! browse the attached file system
fs->setFileListSystem ( FILESYSTEM_VIRTUAL );
fs->changeWorkingDirectoryTo ( "/maps/" );
IFileList *fileList = fs->createFileList ();
fs->setFileListSystem ( FILESYSTEM_NATIVE );
for ( i=0; i< fileList->getFileCount(); ++i)
{
s = fileList->getFullFileName(i);
if ( s.find ( ".bsp" ) >= 0 )
{
// get level screenshot. reformat texture to 128x128
path c ( s );
deletePathFromFilename ( c );
cutFilenameExtension ( c, c );
c = path ( "levelshots/" ) + c;
dimension2du dim ( 128, 128 );
IVideoDriver * driver = Game->Device->getVideoDriver();
IImage* image = 0;
ITexture *tex = 0;
path filename;
filename = c + ".jpg";
if ( fs->existFile ( filename ) )
image = driver->createImageFromFile( filename );
if ( 0 == image )
{
filename = c + ".tga";
if ( fs->existFile ( filename ) )
image = driver->createImageFromFile( filename );
}
if ( image )
{
IImage* filter = driver->createImage ( video::ECF_R8G8B8, dim );
image->copyToScalingBoxFilter ( filter, 0 );
image->drop ();
image = filter;
}
if ( image )
{
tex = driver->addTexture ( filename, image );
image->drop ();
}
bank->setTexture ( g, tex );
r.LowerRightCorner.X = dim.Width;
r.LowerRightCorner.Y = dim.Height;
gui.MapList->setItemHeight ( r.LowerRightCorner.Y + 4 );
frame.rectNumber = bank->getPositions().size();
frame.textureNumber = g;
bank->getPositions().push_back(r);
sprite.Frames.set_used ( 0 );
sprite.Frames.push_back(frame);
sprite.frameTime = 0;
bank->getSprites().push_back(sprite);
gui.MapList->addItem ( s.c_str (), g );
g += 1;
}
}
fileList->drop ();
gui.MapList->setSelected ( -1 );
IGUIScrollBar * bar = (IGUIScrollBar*)gui.MapList->getElementFromId( 0 );
if ( bar )
bar->setPos ( 0 );
}
}
/*!
clears the Map in Memory
*/
void CQuake3EventHandler::dropMap ()
{
IVideoDriver * driver = Game->Device->getVideoDriver();
driver->removeAllHardwareBuffers ();
driver->removeAllTextures ();
Player[0].shutdown ();
dropElement ( ItemParent );
dropElement ( ShaderParent );
dropElement ( UnresolvedParent );
dropElement ( FogParent );
dropElement ( BulletParent );
Impacts.clear();
if ( Meta )
{
Meta = 0;
}
dropElement ( MapParent );
dropElement ( SkyNode );
// clean out meshes, because textures are invalid
// TODO: better texture handling;-)
IMeshCache *cache = Game->Device->getSceneManager ()->getMeshCache();
cache->clear ();
Mesh = 0;
}
/*!
*/
void CQuake3EventHandler::LoadMap ( const stringw &mapName, s32 collision )
{
if ( 0 == mapName.size() )
return;
dropMap ();
IFileSystem *fs = Game->Device->getFileSystem();
ISceneManager *smgr = Game->Device->getSceneManager ();
IReadFile* file = fs->createMemoryReadFile ( &Game->loadParam, sizeof ( Game->loadParam ),
L"levelparameter.cfg", false);
smgr->getMesh( file );
file->drop ();
Mesh = (IQ3LevelMesh*) smgr->getMesh(mapName);
if ( 0 == Mesh )
return;
/*
add the geometry mesh to the Scene ( polygon & patches )
The Geometry mesh is optimised for faster drawing
*/
IMesh *geometry = Mesh->getMesh(E_Q3_MESH_GEOMETRY);
if ( 0 == geometry || geometry->getMeshBufferCount() == 0)
return;
Game->CurrentMapName = mapName;
//create a collision list
Meta = 0;
ITriangleSelector * selector = 0;
if (collision)
Meta = smgr->createMetaTriangleSelector();
//IMeshBuffer *b0 = geometry->getMeshBuffer(0);
//s32 minimalNodes = b0 ? core::s32_max ( 2048, b0->getVertexCount() / 32 ) : 2048;
s32 minimalNodes = 2048;
MapParent = smgr->addMeshSceneNode( geometry );
//MapParent = smgr->addOctTreeSceneNode(geometry, 0, -1, minimalNodes);
MapParent->setName ( mapName );
if ( Meta )
{
selector = smgr->createOctTreeTriangleSelector( geometry,MapParent, minimalNodes);
//selector = smgr->createTriangleSelector ( geometry, MapParent );
Meta->addTriangleSelector( selector);
selector->drop ();
}
// logical parent for the items
ItemParent = smgr->addEmptySceneNode();
if ( ItemParent )
ItemParent->setName ( "Item Container" );
ShaderParent = smgr->addEmptySceneNode();
if ( ShaderParent )
ShaderParent->setName ( "Shader Container" );
UnresolvedParent = smgr->addEmptySceneNode();
if ( UnresolvedParent )
UnresolvedParent->setName ( "Unresolved Container" );
FogParent = smgr->addEmptySceneNode();
if ( FogParent )
FogParent->setName ( "Fog Container" );
// logical parent for the bullets
BulletParent = smgr->addEmptySceneNode();
if ( BulletParent )
BulletParent->setName ( "Bullet Container" );
/*
now construct SceneNodes for each Shader
The Objects are stored in the quake mesh E_Q3_MESH_ITEMS
and the Shader ID is stored in the MaterialParameters
mostly dark looking skulls and moving lava.. or green flashing tubes?
*/
Q3ShaderFactory ( Game->loadParam, Game->Device, Mesh, E_Q3_MESH_ITEMS,ShaderParent, Meta, false );
Q3ShaderFactory ( Game->loadParam, Game->Device, Mesh, E_Q3_MESH_FOG,FogParent, 0, false );
Q3ShaderFactory ( Game->loadParam, Game->Device, Mesh, E_Q3_MESH_UNRESOLVED,UnresolvedParent, Meta, true );
/*
Now construct Models from Entity List
*/
Q3ModelFactory ( Game->loadParam, Game->Device, Mesh, ItemParent, false );
}
/*
**/
/*!
Adds a SceneNode with an icon to the Scene Tree
*/
void CQuake3EventHandler::addSceneTreeItem( ISceneNode * parent, IGUITreeViewNode* nodeParent)
{
IGUITreeViewNode* node;
wchar_t msg[128];
s32 imageIndex;
list<ISceneNode*>::ConstIterator it = parent->getChildren().begin();
for (; it != parent->getChildren().end(); ++it)
{
switch ( (*it)->getType () )
{
case ESNT_Q3SHADER_SCENE_NODE: imageIndex = 0; break;
case ESNT_CAMERA: imageIndex = 1; break;
case ESNT_EMPTY: imageIndex = 2; break;
case ESNT_MESH: imageIndex = 3; break;
case ESNT_OCT_TREE: imageIndex = 3; break;
case ESNT_ANIMATED_MESH: imageIndex = 4; break;
case ESNT_SKY_BOX: imageIndex = 5; break;
case ESNT_BILLBOARD: imageIndex = 6; break;
case ESNT_PARTICLE_SYSTEM: imageIndex = 7; break;
case ESNT_TEXT: imageIndex = 8; break;
default:imageIndex = -1; break;
}
if ( imageIndex < 0 )
{
swprintf ( msg, 128, L"%hs,%hs",
Game->Device->getSceneManager ()->getSceneNodeTypeName ( (*it)->getType () ),
(*it)->getName()
);
}
else
{
swprintf ( msg, 128, L"%hs",(*it)->getName() );
}
node = nodeParent->addChildBack( msg, 0, imageIndex );
// Add all Animators
list<ISceneNodeAnimator*>::ConstIterator ait = (*it)->getAnimators().begin();
for (; ait != (*it)->getAnimators().end(); ++ait)
{
imageIndex = -1;
swprintf ( msg, 128, L"%hs",
Game->Device->getSceneManager ()->getAnimatorTypeName ( (*ait)->getType () )
);
switch ( (*ait)->getType () )
{
case ESNAT_FLY_CIRCLE:
case ESNAT_FLY_STRAIGHT:
case ESNAT_FOLLOW_SPLINE:
case ESNAT_ROTATION:
case ESNAT_TEXTURE:
case ESNAT_DELETION:
case ESNAT_COLLISION_RESPONSE:
case ESNAT_CAMERA_FPS:
case ESNAT_CAMERA_MAYA:
default:
break;
}
node->addChildBack( msg, 0, imageIndex );
}
addSceneTreeItem ( *it, node );
}
}
//! Adds life!
void CQuake3EventHandler::CreatePlayers()
{
Player[0].create ( Game->Device, Mesh, MapParent, Meta );
}
//! Adds a skydome to the scene
void CQuake3EventHandler::AddSky( u32 dome, const c8 *texture)
{
ISceneManager *smgr = Game->Device->getSceneManager ();
IVideoDriver * driver = Game->Device->getVideoDriver();
bool oldMipMapState = driver->getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS);
driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
if ( 0 == dome )
{
// irrlicht order
//static const c8*p[] = { "ft", "lf", "bk", "rt", "up", "dn" };
// quake3 order
static const c8*p[] = { "ft", "rt", "bk", "lf", "up", "dn" };
u32 i = 0;
snprintf ( buf, 64, "%s_%s.jpg", texture, p[i] );
SkyNode = smgr->addSkyBoxSceneNode( driver->getTexture ( buf ), 0, 0, 0, 0, 0 );
for ( i = 0; i < 6; ++i )
{
snprintf ( buf, 64, "%s_%s.jpg", texture, p[i] );
SkyNode->getMaterial(i).setTexture ( 0, driver->getTexture ( buf ) );
}
}
else
if ( 1 == dome )
{
snprintf ( buf, 64, "%s.jpg", texture );
SkyNode = smgr->addSkyDomeSceneNode(
driver->getTexture( buf ),
32,32,
1.f,
1.f,
1000.f,
0,
11
);
}
else
if ( 2 == dome )
{
snprintf ( buf, 64, "%s.jpg", texture );
SkyNode = smgr->addSkyDomeSceneNode(
driver->getTexture( buf ),
16,8,
0.95f,
2.f,
1000.f,
0,
11
);
}
SkyNode->setName ( "Skydome" );
//SkyNode->getMaterial(0).ZBuffer = video::EMDF_DEPTH_LESS_EQUAL;
driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, oldMipMapState);
}
/*!
*/
void CQuake3EventHandler::SetGUIActive( s32 command)
{
bool inputState = false;
ICameraSceneNode * camera = Game->Device->getSceneManager()->getActiveCamera ();
switch ( command )
{
case 0: Game->guiActive = 0; inputState = !Game->guiActive; break;
case 1: Game->guiActive = 1; inputState = !Game->guiActive;;break;
case 2: Game->guiActive ^= 1; inputState = !Game->guiActive;break;
case 3:
if ( camera )
inputState = !camera->isInputReceiverEnabled();
break;
}
if ( camera )
{
camera->setInputReceiverEnabled ( inputState );
Game->Device->getCursorControl()->setVisible( !inputState );
}
if ( gui.Window )
{
gui.Window->setVisible ( Game->guiActive != 0 );
}
if ( Game->guiActive &&
gui.SceneTree && Game->Device->getGUIEnvironment()->getFocus() != gui.SceneTree
)
{
gui.SceneTree->getRoot()->clearChilds();
addSceneTreeItem ( Game->Device->getSceneManager()->getRootSceneNode(), gui.SceneTree->getRoot() );
}
Game->Device->getGUIEnvironment()->setFocus ( Game->guiActive ? gui.Window: 0 );
}
/*!
Handle game input
*/
bool CQuake3EventHandler::OnEvent(const SEvent& eve)
{
if ( eve.EventType == EET_LOG_TEXT_EVENT )
{
return false;
}
if ( Game->guiActive && eve.EventType == EET_GUI_EVENT )
{
if ( eve.GUIEvent.Caller == gui.MapList && eve.GUIEvent.EventType == gui::EGET_LISTBOX_SELECTED_AGAIN )
{
s32 selected = gui.MapList->getSelected();
if ( selected >= 0 )
{
stringw loadMap = gui.MapList->getListItem ( selected );
if ( 0 == MapParent || loadMap != Game->CurrentMapName )
{
printf ( "Loading map %ls\n", loadMap.c_str() );
LoadMap ( loadMap , 1 );
if ( 0 == Game->loadParam.loadSkyShader )
{
AddSky ( 1, "skydome2" );
}
CreatePlayers ();
CreateGUI ();
SetGUIActive ( 0 );
return true;
}
}
}
else
if ( eve.GUIEvent.Caller == gui.ArchiveRemove && eve.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
{
Game->Device->getFileSystem()->removeFileArchive( gui.ArchiveList->getSelected() );
Game->CurrentMapName = "";
AddArchive ( "" );
}
else
if ( eve.GUIEvent.Caller == gui.ArchiveAdd && eve.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
{
if ( 0 == gui.ArchiveFileOpen )
{
Game->Device->getFileSystem()->setFileListSystem ( FILESYSTEM_NATIVE );
gui.ArchiveFileOpen = Game->Device->getGUIEnvironment()->addFileOpenDialog ( L"Add Game Archive" , false,gui.Window );
}
}
else
if ( eve.GUIEvent.Caller == gui.ArchiveFileOpen && eve.GUIEvent.EventType == gui::EGET_FILE_SELECTED )
{
AddArchive ( gui.ArchiveFileOpen->getFileName() );
gui.ArchiveFileOpen = 0;
}
else
if ( eve.GUIEvent.Caller == gui.ArchiveFileOpen && eve.GUIEvent.EventType == gui::EGET_DIRECTORY_SELECTED )
{
AddArchive ( gui.ArchiveFileOpen->getDirectoryName() );
}
else
if ( eve.GUIEvent.Caller == gui.ArchiveFileOpen && eve.GUIEvent.EventType == gui::EGET_FILE_CHOOSE_DIALOG_CANCELLED )
{
gui.ArchiveFileOpen = 0;
}
else
if ( ( eve.GUIEvent.Caller == gui.ArchiveUp || eve.GUIEvent.Caller == gui.ArchiveDown ) &&
eve.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
{
s32 rel = eve.GUIEvent.Caller == gui.ArchiveUp ? -1 : 1;
if ( Game->Device->getFileSystem()->moveFileArchive ( gui.ArchiveList->getSelected (), rel ) )
{
s32 newIndex = core::s32_clamp ( gui.ArchiveList->getSelected() + rel, 0, gui.ArchiveList->getRowCount() - 1 );
AddArchive ( "" );
gui.ArchiveList->setSelected ( newIndex );
Game->CurrentMapName = "";
}
}
else
if ( eve.GUIEvent.Caller == gui.VideoDriver && eve.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED )
{
Game->deviceParam.DriverType = (E_DRIVER_TYPE) gui.VideoDriver->getItemData ( gui.VideoDriver->getSelected() );
}
else
if ( eve.GUIEvent.Caller == gui.VideoMode && eve.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED )
{
u32 val = gui.VideoMode->getItemData ( gui.VideoMode->getSelected() );
Game->deviceParam.WindowSize.Width = val >> 16;
Game->deviceParam.WindowSize.Height = val & 0xFFFF;
}
else
if ( eve.GUIEvent.Caller == gui.FullScreen && eve.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED )
{
Game->deviceParam.Fullscreen = gui.FullScreen->isChecked();
}
else
if ( eve.GUIEvent.Caller == gui.Bit32 && eve.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED )
{
Game->deviceParam.Bits = gui.Bit32->isChecked() ? 32 : 16;
}
else
if ( eve.GUIEvent.Caller == gui.MultiSample && eve.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED )
{
Game->deviceParam.AntiAlias = gui.MultiSample->getPos();
}
else
if ( eve.GUIEvent.Caller == gui.Tesselation && eve.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED )
{
Game->loadParam.patchTesselation = gui.Tesselation->getPos ();
}
else
if ( eve.GUIEvent.Caller == gui.Gamma && eve.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED )
{
Game->GammaValue = gui.Gamma->getPos () * 0.01f;
Game->Device->setGammaRamp ( Game->GammaValue, Game->GammaValue, Game->GammaValue, 0.f, 0.f );
}
else
if ( eve.GUIEvent.Caller == gui.SetVideoMode && eve.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
{
Game->retVal = 2;
Game->Device->closeDevice();
}
else
if ( eve.GUIEvent.Caller == gui.Window && eve.GUIEvent.EventType == gui::EGET_ELEMENT_CLOSED )
{
Game->Device->closeDevice();
}
else
if ( eve.GUIEvent.Caller == gui.Collision && eve.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED )
{
// set fly through active
Game->flyTroughState ^= 1;
Player[0].cam()->setAnimateTarget ( Game->flyTroughState == 0 );
printf ( "collision %d\n", Game->flyTroughState == 0 );
}
else
if ( eve.GUIEvent.Caller == gui.Visible_Map && eve.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED )
{
bool v = gui.Visible_Map->isChecked();
if ( MapParent )
{
printf ( "static node set visible %d\n",v );
MapParent->setVisible ( v );
}
}
else
if ( eve.GUIEvent.Caller == gui.Visible_Shader && eve.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED )
{
bool v = gui.Visible_Shader->isChecked();
if ( ShaderParent )
{
printf ( "shader node set visible %d\n",v );
ShaderParent->setVisible ( v );
}
}
else
if ( eve.GUIEvent.Caller == gui.Visible_Skydome && eve.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED )
{
if ( SkyNode )
{
bool v = !SkyNode->isVisible();
printf ( "skynode set visible %d\n",v );
SkyNode->setVisible ( v );
}
}
else
if ( eve.GUIEvent.Caller == gui.Respawn && eve.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
{
Player[0].respawn ();
}
return false;
}
// fire
if ((eve.EventType == EET_KEY_INPUT_EVENT && eve.KeyInput.Key == KEY_SPACE &&
eve.KeyInput.PressedDown == false) ||
(eve.EventType == EET_MOUSE_INPUT_EVENT && eve.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
)
{
ICameraSceneNode * camera = Game->Device->getSceneManager()->getActiveCamera ();
if ( camera && camera->isInputReceiverEnabled () )
{
useItem( Player + 0 );
}
}
// gui active
if ((eve.EventType == EET_KEY_INPUT_EVENT && eve.KeyInput.Key == KEY_F1 &&
eve.KeyInput.PressedDown == false) ||
(eve.EventType == EET_MOUSE_INPUT_EVENT && eve.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
)
{
SetGUIActive ( 2 );
}
// check if user presses the key
if ( eve.EventType == EET_KEY_INPUT_EVENT && eve.KeyInput.PressedDown == false)
{
// Escape toggles camera Input
if ( eve.KeyInput.Key == irr::KEY_ESCAPE )
{
SetGUIActive ( 3 );
}
else
if (eve.KeyInput.Key == KEY_F11)
{
//! screenshot are taken without gamma!
IImage* image = Game->Device->getVideoDriver()->createScreenShot();
if (image)
{
core::vector3df pos;
core::vector3df rot;
ICameraSceneNode * cam = Game->Device->getSceneManager()->getActiveCamera ();
if ( cam )
{
pos = cam->getPosition ();
rot = cam->getRotation ();
}
static const c8 *dName[] = { "null", "software", "burning",
"d3d8", "d3d9", "opengl" };
snprintf(buf, 256, "%s_%ls_%.0f_%.0f_%.0f_%.0f_%.0f_%.0f.jpg",
dName[Game->Device->getVideoDriver()->getDriverType()],
Game->CurrentMapName.c_str(),
pos.X, pos.Y, pos.Z,
rot.X, rot.Y, rot.Z
);
path filename ( buf );
filename.replace ( '/', '_' );
printf ( "screenshot : %s\n", filename.c_str() );
Game->Device->getVideoDriver()->writeImageToFile(image, filename, 100 );
image->drop();
}
}
else
if (eve.KeyInput.Key == KEY_F9)
{
s32 value = EDS_OFF;
Game->debugState = ( Game->debugState + 1 ) & 3;
switch ( Game->debugState )
{
case 1: value = EDS_NORMALS | EDS_MESH_WIRE_OVERLAY | EDS_BBOX_ALL; break;
case 2: value = EDS_NORMALS | EDS_MESH_WIRE_OVERLAY | EDS_SKELETON; break;
}
/*
// set debug map data on/off
debugState = debugState == EDS_OFF ?
EDS_NORMALS | EDS_MESH_WIRE_OVERLAY | EDS_BBOX_ALL:
EDS_OFF;
*/
if ( ItemParent )
{
list<ISceneNode*>::ConstIterator it = ItemParent->getChildren().begin();
for (; it != ItemParent->getChildren().end(); ++it)
{
(*it)->setDebugDataVisible ( value );
}
}
if ( ShaderParent )
{
list<ISceneNode*>::ConstIterator it = ShaderParent->getChildren().begin();
for (; it != ShaderParent->getChildren().end(); ++it)
{
(*it)->setDebugDataVisible ( value );
}
}
if ( UnresolvedParent )
{
list<ISceneNode*>::ConstIterator it = UnresolvedParent->getChildren().begin();
for (; it != UnresolvedParent->getChildren().end(); ++it)
{
(*it)->setDebugDataVisible ( value );
}
}
if ( FogParent )
{
list<ISceneNode*>::ConstIterator it = FogParent->getChildren().begin();
for (; it != FogParent->getChildren().end(); ++it)
{
(*it)->setDebugDataVisible ( value );
}
}
if ( SkyNode )
{
SkyNode->setDebugDataVisible ( value );
}
}
else
if (eve.KeyInput.Key == KEY_F8)
{
// set gravity on/off
Game->gravityState ^= 1;
Player[0].cam()->setGravity ( getGravity ( Game->gravityState ? "earth" : "none" ) );
printf ( "gravity %s\n", Game->gravityState ? "earth" : "none" );
}
else
if (eve.KeyInput.Key == KEY_F7)
{
// set fly through active
Game->flyTroughState ^= 1;
Player[0].cam()->setAnimateTarget ( Game->flyTroughState == 0 );
if ( gui.Collision )
gui.Collision->setChecked ( Game->flyTroughState == 0 );
printf ( "collision %d\n", Game->flyTroughState == 0 );
}
else
if (eve.KeyInput.Key == KEY_F2)
{
Player[0].respawn ();
}
else
if (eve.KeyInput.Key == KEY_F3)
{
if ( MapParent )
{
bool v = !MapParent->isVisible ();
printf ( "static node set visible %d\n",v );
MapParent->setVisible ( v );
if ( gui.Visible_Map )
gui.Visible_Map->setChecked ( v );
}
}
else
if (eve.KeyInput.Key == KEY_F4)
{
if ( ShaderParent )
{
bool v = !ShaderParent->isVisible ();
printf ( "shader node set visible %d\n",v );
ShaderParent->setVisible ( v );
if ( gui.Visible_Shader )
gui.Visible_Shader->setChecked ( v );
}
}
else
if (eve.KeyInput.Key == KEY_F5)
{
if ( FogParent )
{
bool v = !FogParent->isVisible ();
printf ( "fog node set visible %d\n",v );
FogParent->setVisible ( v );
if ( gui.Visible_Fog )
gui.Visible_Fog->setChecked ( v );
}
}
else
if (eve.KeyInput.Key == KEY_F6)
{
if ( UnresolvedParent )
{
bool v = !UnresolvedParent->isVisible ();
printf ( "unresolved node set visible %d\n",v );
UnresolvedParent->setVisible ( v );
if ( gui.Visible_Unresolved )
gui.Visible_Unresolved->setChecked ( v );
}
}
}
// check if user presses the key C ( for crouch)
if ( eve.EventType == EET_KEY_INPUT_EVENT && eve.KeyInput.Key == KEY_KEY_C )
{
// crouch
ISceneNodeAnimatorCollisionResponse *anim = Player[0].cam ();
if ( anim && 0 == Game->flyTroughState )
{
if ( false == eve.KeyInput.PressedDown )
{
// stand up
anim->setEllipsoidRadius ( vector3df(30,45,30) );
anim->setEllipsoidTranslation ( vector3df(0,40,0));
}
else
{
// on your knees
anim->setEllipsoidRadius ( vector3df(30,20,30) );
anim->setEllipsoidTranslation ( vector3df(0,20,0));
}
return true;
}
}
return false;
}
/*
useItem
*/
void CQuake3EventHandler::useItem( Q3Player * player)
{
ISceneManager* smgr = Game->Device->getSceneManager();
ICameraSceneNode* camera = smgr->getActiveCamera();
if (!camera)
return;
SParticleImpact imp;
imp.when = 0;
// get line of camera
vector3df start = camera->getPosition();
if ( player->WeaponNode )
{
start.X += 0.f;
start.Y += 0.f;
start.Z += 0.f;
}
vector3df end = (camera->getTarget() - start);
end.normalize();
start += end*20.0f;
end = start + (end * camera->getFarValue());
triangle3df triangle;
line3d<f32> line(start, end);
// get intersection point with map
const scene::ISceneNode* hitNode;
if (smgr->getSceneCollisionManager()->getCollisionPoint(
line, Meta, end, triangle,hitNode))
{
// collides with wall
vector3df out = triangle.getNormal();
out.setLength(0.03f);
imp.when = 1;
imp.outVector = out;
imp.pos = end;
player->setAnim ( "pow" );
player->Anim[1].next += player->Anim[1].delta;
}
else
{
// doesnt collide with wall
vector3df start = camera->getPosition();
if ( player->WeaponNode )
{
//start.X += 10.f;
//start.Y += -5.f;
//start.Z += 1.f;
}
vector3df end = (camera->getTarget() - start);
end.normalize();
start += end*20.0f;
end = start + (end * camera->getFarValue());
}
// create fire ball
ISceneNode* node = 0;
node = smgr->addBillboardSceneNode( BulletParent,dimension2d<f32>(10,10), start);
node->setMaterialFlag(EMF_LIGHTING, false);
node->setMaterialTexture(0, Game->Device->getVideoDriver()->getTexture("fireball.bmp"));
node->setMaterialType(EMT_TRANSPARENT_ADD_COLOR);
f32 length = (f32)(end - start).getLength();
const f32 speed = 5.8f;
u32 time = (u32)(length / speed);
ISceneNodeAnimator* anim = 0;
// set flight line
anim = smgr->createFlyStraightAnimator(start, end, time);
node->addAnimator(anim);
anim->drop();
snprintf ( buf, 64, "bullet: %s on %.1f,%1.f,%1.f",
imp.when ? "hit" : "nohit", end.X, end.Y, end.Z );
node->setName ( buf );
anim = smgr->createDeleteAnimator(time);
node->addAnimator(anim);
anim->drop();
if (imp.when)
{
// create impact note
imp.when = Game->Device->getTimer()->getTime() +
(time + (s32) ( ( 1.f + Noiser::get() ) * 250.f ));
Impacts.push_back(imp);
}
// play sound
}
/*!
*/
void CQuake3EventHandler::createParticleImpacts( u32 now )
{
ISceneManager* sm = Game->Device->getSceneManager();
struct smokeLayer
{
const c8 * texture;
f32 scale;
f32 minparticleSize;
f32 maxparticleSize;
f32 boxSize;
u32 minParticle;
u32 maxParticle;
u32 fadeout;
u32 lifetime;
};
smokeLayer smoke[] =
{
{ "smoke2.jpg", 0.4f, 1.5f, 18.f, 20.f, 20, 50, 2000, 10000 },
{ "smoke3.jpg", 0.2f, 1.2f, 15.f, 20.f, 10, 30, 1000, 12000 }
};
u32 i;
u32 g;
s32 factor = 1;
for ( g = 0; g != 2; ++g )
{
smoke[g].minParticle *= factor;
smoke[g].maxParticle *= factor;
smoke[g].lifetime *= factor;
smoke[g].boxSize *= Noiser::get() * 0.5f;
}
for ( i=0; i < Impacts.size(); ++i)
{
if (now < Impacts[i].when)
continue;
// create smoke particle system
IParticleSystemSceneNode* pas = 0;
for ( g = 0; g != 2; ++g )
{
pas = sm->addParticleSystemSceneNode(false, BulletParent, -1, Impacts[i].pos);
snprintf ( buf, 64, "bullet impact smoke at %.1f,%.1f,%1.f",
Impacts[i].pos.X,Impacts[i].pos.Y,Impacts[i].pos.Z);
pas->setName ( buf );
// create a flat smoke
vector3df direction = Impacts[i].outVector;
direction *= smoke[g].scale;
IParticleEmitter* em = pas->createBoxEmitter(
aabbox3d<f32>(-4.f,0.f,-4.f,20.f,smoke[g].minparticleSize,20.f),
direction,smoke[g].minParticle, smoke[g].maxParticle,
video::SColor(0,0,0,0),video::SColor(0,128,128,128),
250,4000, 60);
em->setMinStartSize (dimension2d<f32>( smoke[g].minparticleSize, smoke[g].minparticleSize));
em->setMaxStartSize (dimension2d<f32>( smoke[g].maxparticleSize, smoke[g].maxparticleSize));
pas->setEmitter(em);
em->drop();
// particles get invisible
IParticleAffector* paf = pas->createFadeOutParticleAffector(
video::SColor ( 0, 0, 0, 0 ), smoke[g].fadeout);
pas->addAffector(paf);
paf->drop();
// particle system life time
ISceneNodeAnimator* anim = sm->createDeleteAnimator( smoke[g].lifetime);
pas->addAnimator(anim);
anim->drop();
pas->setMaterialFlag(video::EMF_LIGHTING, false);
pas->setMaterialType(video::EMT_TRANSPARENT_VERTEX_ALPHA );
pas->setMaterialTexture(0, Game->Device->getVideoDriver()->getTexture( smoke[g].texture ));
}
// play impact sound
#ifdef USE_IRRKLANG
/*
if (irrKlang)
{
audio::ISound* sound =
irrKlang->play3D(impactSound, Impacts[i].pos, false, false, true);
if (sound)
{
// adjust max value a bit to make to sound of an impact louder
sound->setMinDistance(400);
sound->drop();
}
}
*/
#endif
// delete entry
Impacts.erase(i);
i--;
}
}
/*
render
*/
void CQuake3EventHandler::Render()
{
IVideoDriver * driver = Game->Device->getVideoDriver();
if ( 0 == driver )
return;
driver->beginScene(true, true, SColor(0,0,0,0));
Game->Device->getSceneManager ()->drawAll();
Game->Device->getGUIEnvironment()->drawAll();
driver->endScene();
}
/*
update the generic scene node
*/
void CQuake3EventHandler::Animate()
{
u32 now = Game->Device->getTimer()->getTime();
Q3Player * player = Player + 0;
checkTimeFire ( player->Anim, 4, now );
// Query Scene Manager attributes
if ( player->Anim[0].flags & FIRED )
{
ISceneManager *smgr = Game->Device->getSceneManager ();
wchar_t msg[128];
IVideoDriver * driver = Game->Device->getVideoDriver();
IAttributes * attr = smgr->getParameters();
swprintf ( msg, 128,
L"Q3 %s [%s], FPS:%03d Tri:%.03fm Cull %d/%d nodes (%d,%d,%d)",
Game->CurrentMapName.c_str(),
driver->getName(),
driver->getFPS (),
(f32) driver->getPrimitiveCountDrawn( 0 ) * ( 1.f / 1000000.f ),
attr->getAttributeAsInt ( "culled" ),
attr->getAttributeAsInt ( "calls" ),
attr->getAttributeAsInt ( "drawn_solid" ),
attr->getAttributeAsInt ( "drawn_transparent" ),
attr->getAttributeAsInt ( "drawn_transparent_effect" )
);
Game->Device->setWindowCaption( msg );
swprintf ( msg, 128,
L"%03d fps, F1 GUI on/off, F2 respawn, F3-F6 toggle Nodes, F7 Collision on/off"
L", F8 Gravity on/off, Right Mouse Toggle GUI",
Game->Device->getVideoDriver()->getFPS ()
);
if ( gui.StatusLine )
gui.StatusLine->setText ( msg );
player->Anim[0].flags &= ~FIRED;
}
// idle..
if ( player->Anim[1].flags & FIRED )
{
if ( strcmp ( player->animation, "idle" ) )
player->setAnim ( "idle" );
player->Anim[1].flags &= ~FIRED;
}
createParticleImpacts ( now );
}
/*!
*/
void runGame ( GameData *game )
{
if ( game->retVal >= 3 )
return;
game->Device = (*game->createExDevice) ( game->deviceParam );
if ( 0 == game->Device)
{
// could not create selected driver.
game->retVal = 0;
return;
}
// create an event receiver based on current game data
CQuake3EventHandler *eventHandler = new CQuake3EventHandler( game );
//! load stored config
game->load ( "explorer.cfg" );
//! add our media directory and archive to the file system
for ( u32 i = 0; i < game->CurrentArchiveList.size(); ++i )
{
eventHandler->AddArchive ( game->CurrentArchiveList[i] );
}
// Load a Map or startup to the GUI
if ( game->CurrentMapName.size () )
{
eventHandler->LoadMap ( game->CurrentMapName, 1 );
if ( 0 == game->loadParam.loadSkyShader )
eventHandler->AddSky ( 1, "skydome2" );
eventHandler->CreatePlayers ();
eventHandler->CreateGUI ();
eventHandler->SetGUIActive ( 0 );
// set player to last position on restart
if ( game->retVal == 2 )
{
eventHandler->GetPlayer( 0 )->setpos ( game->PlayerPosition, game->PlayerRotation );
}
}
else
{
// start up empty
eventHandler->AddSky ( 1, "skydome2" );
eventHandler->CreatePlayers ();
eventHandler->CreateGUI ();
eventHandler->SetGUIActive ( 1 );
background_music ( "IrrlichtTheme.ogg" );
}
game->retVal = 3;
while( game->Device->run() )
{
eventHandler->Animate ();
eventHandler->Render ();
//if ( !game->Device->isWindowActive() )
game->Device->yield();
}
game->Device->setGammaRamp ( 1.f, 1.f, 1.f, 0.f, 0.f );
delete eventHandler;
}
#if defined (_IRR_WINDOWS_) && 0
#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
#endif
/*!
*/
int IRRCALLCONV main(int argc, char* argv[])
{
path prgname(argv[0]);
GameData game ( deletePathFromPath ( prgname, 1 ) );
// dynamically load irrlicht
const c8 * dllName = argc > 1 ? argv[1] : "irrlicht.dll";
game.createExDevice = load_createDeviceEx ( dllName );
if ( 0 == game.createExDevice )
{
game.retVal = 3;
printf ( "Could not load %s.\n", dllName );
return game.retVal; // could not load dll
}
// start without asking for driver
game.retVal = 1;
do
{
// if driver could not created, ask for another driver
if ( game.retVal == 0 )
{
game.setDefault ();
printf("Please select the driver you want for this example:\n"\
" (a) Direct3D 9.0c\n (b) Direct3D 8.1\n (c) OpenGL 1.5\n"\
" (d) Software Renderer\n (e) Burning's Video (TM) Thomas Alten\n"\
" (otherKey) exit\n\n");
char i = 'a';
std::cin >> i;
switch(i)
{
case 'a': game.deviceParam.DriverType = EDT_DIRECT3D9;break;
case 'b': game.deviceParam.DriverType = EDT_DIRECT3D8;break;
case 'c': game.deviceParam.DriverType = EDT_OPENGL; break;
case 'd': game.deviceParam.DriverType = EDT_SOFTWARE; break;
case 'e': game.deviceParam.DriverType = EDT_BURNINGSVIDEO;break;
default: game.retVal = 3; break;
}
}
runGame ( &game );
} while ( game.retVal < 3 );
return game.retVal;
}
/*
**/
| [
"[email protected]"
]
| [
[
[
1,
2133
]
]
]
|
d5cb8236243870dc74f1ffa7cb94fb65e64127d7 | 6baa03d2d25d4685cd94265bd0b5033ef185c2c9 | /TGL/src/objects/TGLobject_pipevscreen.cpp | 42f7258fc23383a5a9dc0abe327ee8035812cf0a | []
| no_license | neiderm/transball | 6ac83b8dd230569d45a40f1bd0085bebdc4a5b94 | 458dd1a903ea4fad582fb494c6fd773e3ab8dfd2 | refs/heads/master | 2021-01-10T07:01:43.565438 | 2011-12-12T23:53:54 | 2011-12-12T23:53:54 | 55,928,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,829 | cpp | #ifdef KITSCHY_DEBUG_MEMORY
#include "debug_memorymanager.h"
#endif
#ifdef _WIN32
#include <windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include "math.h"
#include "string.h"
#include "gl.h"
#include "glu.h"
#include "SDL.h"
#include "SDL_mixer.h"
#include "SDL_ttf.h"
#include "List.h"
#include "Symbol.h"
#include "2DCMC.h"
#include "auxiliar.h"
#include "GLTile.h"
#include "2DCMC.h"
#include "sound.h"
#include "keyboardstate.h"
#include "randomc.h"
#include "VirtualController.h"
#include "GLTManager.h"
#include "SFXManager.h"
#include "TGLobject.h"
#include "TGLobject_pipevscreen.h"
#include "TGLmap.h"
#include "debug.h"
TGLobject_pipevscreen::TGLobject_pipevscreen(float x,float y,int ao) : TGLobject(x,y,ao)
{
} /* TGLobject_pipevscreen::TGLobject_pipevscreen */
TGLobject_pipevscreen::~TGLobject_pipevscreen()
{
} /* TGLobject_pipevscreen::~TGLobject_pipevscreen */
void TGLobject_pipevscreen::draw(GLTManager *GLTM)
{
int local_cycle=((m_animation_offset+m_cycle)%120)/8;
if (local_cycle==0) m_last_tile=GLTM->get("objects/pipe-vertical-screen1");
if (local_cycle==1) m_last_tile=GLTM->get("objects/pipe-vertical-screen2");
if (local_cycle==2) m_last_tile=GLTM->get("objects/pipe-vertical-screen1");
if (local_cycle==3) m_last_tile=GLTM->get("objects/pipe-vertical-screen2");
if (local_cycle==4) m_last_tile=GLTM->get("objects/pipe-vertical-screen1");
if (local_cycle==5) m_last_tile=GLTM->get("objects/pipe-vertical-screen2");
if (local_cycle==6) m_last_tile=GLTM->get("objects/pipe-vertical-screen1");
if (local_cycle==7) m_last_tile=GLTM->get("objects/pipe-vertical-screen2");
if (local_cycle==8) m_last_tile=GLTM->get("objects/pipe-vertical-screen3");
if (local_cycle==9) m_last_tile=GLTM->get("objects/pipe-vertical-screen4");
if (local_cycle==10) m_last_tile=GLTM->get("objects/pipe-vertical-screen5");
if (local_cycle==11) m_last_tile=GLTM->get("objects/pipe-vertical-screen6");
if (local_cycle==12) m_last_tile=GLTM->get("objects/pipe-vertical-screen7");
if (local_cycle==13) m_last_tile=GLTM->get("objects/pipe-vertical-screen8");
if (local_cycle==14) m_last_tile=GLTM->get("objects/pipe-vertical-screen9");
if (m_last_tile!=0) m_last_tile->draw(m_x,m_y,0,0,1);
} /* TGLobject_pipevscreen::draw */
bool TGLobject_pipevscreen::is_a(Symbol *c)
{
if (c->cmp("TGLobject_pipevscreen")) return true;
return TGLobject::is_a(c);
} /* TGLobject_pipevscreen::is_a */
bool TGLobject_pipevscreen::is_a(char *c)
{
bool retval;
Symbol *s=new Symbol(c);
retval=is_a(s);
delete s;
return retval;
} /* TGLobject_pipevscreen::is_a */
const char *TGLobject_pipevscreen::get_class(void)
{
return "TGLobject_pipevscreen";
} /* TGLobject_pipevscreen:get_class */
| [
"santi.ontanon@535450eb-5f2b-0410-a0e9-a13dc2d1f197"
]
| [
[
[
1,
98
]
]
]
|
b0e021520085685f0027b2de4b9987253d41821a | b24d5382e0575ad5f7c6e5a77ed065d04b77d9fa | /RadiantLaserCross/RLC_GameStateNames.cpp | acb1446128cccb12d32fa341368d626573e40397 | []
| 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 | 147 | cpp | #include "RLC_GameStateNames.h"
namespace rlc
{
namespace names
{
const std::string GAMESTATE_GAME_SESSION = "game_session";
}
} | [
"[email protected]"
]
| [
[
[
1,
11
]
]
]
|
9179d36078cb387a8e60cab9435d0eeccb23b81d | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/util/Compilers/OS400SetDefs.cpp | b709c7b500a0492d0c671d56147ebbf9410e0376 | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,042 | cpp | /*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: OS400SetDefs.cpp 191054 2005-06-17 02:56:35Z jberry $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <sys/types.h>
#include <ctype.h>
int
strcasecmp (const char *string1,const char * string2)
{
char *s1, *s2;
int result;
s1 = (char *)string1;
s2 = (char *)string2;
while ((result = tolower (*s1) - tolower (*s2)) == 0)
{
if (*s1++ == '\0')
return 0;
s2++;
}
return (result);
}
int
strncasecmp (const char *string1,const char *string2,size_t count)
{
register char *s1, *s2;
register int r;
register unsigned int rcount;
rcount = (unsigned int) count;
if (rcount > 0)
{
s1 = (char *)string1;
s2 = (char *)string2;
do
{
if ((r = tolower (*s1) - tolower (*s2)) != 0)
return r;
if (*s1++ == '\0')
break;
s2++;
}
while (--rcount != 0);
}
return (0);
}
/* des not appear as though the following is needed */
#ifndef __OS400__
int stricmp(const char* str1, const char* str2)
{
return strcasecmp(str1, str2);
}
int strnicmp(const char* str1, const char* str2, const unsigned int count)
{
if (count == 0)
return 0;
return strncasecmp( str1, str2, (size_t)count);
}
#endif
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
81
]
]
]
|
b45c89aba00b51744faa7ab17151579cb38c7096 | 64094c7f00c68816d1e2abea13526d2c88b3a682 | /main.cpp | 07555a08c901fc618dbfdbbc358348f7db9dd7de | []
| no_license | cwxfly/fibonacci-heap | 8c585ebbf2338e46ce6117116d4caa7f8ce61008 | ddada1f4b7f73684015538445e09f53d29a7ef54 | refs/heads/master | 2021-01-10T12:41:24.680894 | 2009-01-04T17:55:20 | 2009-01-04T17:55:20 | 53,788,370 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,712 | cpp | #include <stdio.h>
#include <stdlib.h>
#include "Fibo.h"
void test1()
{
printf("[Test1] \n");
FiboHeap fiboHeap;
stHeapInfo heapInfo;
heapInfo.nKey = 1;
fiboHeap.Insert(heapInfo);
heapInfo.nKey = 3;
fiboHeap.Insert(heapInfo);
heapInfo.nKey = 2;
fiboHeap.Insert(heapInfo);
heapInfo.nKey = 5;
fiboHeap.Insert(heapInfo);
heapInfo.nKey = 9;
fiboHeap.Insert(heapInfo);
fiboHeap.DumpHeap();
// It should be 1
fiboHeap.ExtractMin(&heapInfo);
printf("Extrace min = %d\n", heapInfo.nKey);
fiboHeap.DumpHeap();
// It should be 2
fiboHeap.ExtractMin(&heapInfo);
printf("Extrace min = %d\n", heapInfo.nKey);
fiboHeap.DumpHeap();
// It should be 3
fiboHeap.ExtractMin(&heapInfo);
printf("Extrace min = %d\n", heapInfo.nKey);
fiboHeap.DumpHeap();
// It should be 5
fiboHeap.ExtractMin(&heapInfo);
printf("Extrace min = %d\n", heapInfo.nKey);
fiboHeap.DumpHeap();
// It should be 9
fiboHeap.ExtractMin(&heapInfo);
printf("Extrace min = %d\n", heapInfo.nKey);
fiboHeap.DumpHeap();
// Error handling
fiboHeap.ExtractMin(&heapInfo);
fiboHeap.DumpHeap();
printf("[Test1] Complete!\n");
}
void test2()
{
printf("[Test2] \n");
FiboHeap fiboHeap;
stHeapInfo heapInfo;
int maxTest = 100;
srand(0);
for (int i = 0; i < maxTest; i++)
{
int nR = rand() % 100000;
heapInfo.nKey = nR;
fiboHeap.Insert(heapInfo);
}
fiboHeap.DumpHeap();
for (i = 0; i < maxTest; i++)
{
fiboHeap.ExtractMin(&heapInfo);
printf("Extrace min = %d\n", heapInfo.nKey);
fiboHeap.DumpHeap();
}
printf("[Test2] Complete!\n");
}
int main()
{
test1();
test2();
return 0;
} | [
"demoncris@a7b313c2-da83-11dd-918e-25ffe7a15323"
]
| [
[
[
1,
90
]
]
]
|
977cef4d9e8c4f14de8a954c9135517673941030 | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /maxsdk2008/include/actiontable.h | eef98985c6cbee7524bf23cfcf1c667d49bc2e21 | []
| no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 49,615 | h | //**************************************************************************/
// Copyright (c) 1998-2006 Autodesk, Inc.
// All rights reserved.
//
// These coded instructions, statements, and computer programs contain
// unpublished proprietary information written by Autodesk, Inc., and are
// protected by Federal copyright law. They may not be disclosed to third
// parties or copied or duplicated in any form, in whole or in part, without
// the prior written consent of Autodesk, Inc.
//**************************************************************************/
// FILE: ActionTable.h
// DESCRIPTION: Action Table definitions
// AUTHOR: Scott Morrison
// HISTORY: Created 8 February, 2000, Based on KbdAction.h.
//**************************************************************************/
// The ActionTable class is used by plug-ins (and core) to export
// tables of items that can be used by the UI to attach to keyboard
// shorcuts, assign to toolbar buttons, and add to menus.
#ifndef _ACTIONTABLE_H_
#define _ACTIONTABLE_H_
#include "maxheap.h"
#include "stack.h"
#include "iFnPub.h"
#include "strbasic.h" // MCHAR
class MaxIcon;
class MacroEntry;
typedef DWORD ActionTableId;
typedef DWORD ActionContextId;
// ActionTableIds used by the system
const ActionTableId kActionMainUI = 0;
const ActionTableId kActionTrackView = 1;
const ActionTableId kActionMaterialEditor = 2;
const ActionTableId kActionVideoPost = 3;
const ActionTableId kActionSchematicView = 5;
const ActionTableId kActionCommonIReshade = 6;
const ActionTableId kActionScanlineIReshade = 7;
class ActionTable;
class IMenu;
// Context IDs used by the system. Several tables may share the same context id.
const ActionContextId kActionMainUIContext = 0;
const ActionContextId kActionTrackViewContext = 1;
const ActionContextId kActionMaterialEditorContext = 2;
const ActionContextId kActionVideoPostContext = 3;
const ActionContextId kActionSchematicViewContext = 5;
const ActionContextId kActionIReshadeContext = 6;
// Description of a command for building action tables from static data
/*! \sa Class ActionTable, Class ActionItem, Class ActionCallback.
\par Description:
This structure is available in release 4.0 and later only. \n\n
This is a helper structure used for building ActionTables. A static array
of these descriptors is passed to the ActionTable constructor.
*/
struct ActionDescription {
/*! A unique identifier for the command (must be unique per table).
When an action is executed this is the command ID passed to ActionCallback::ExecuteAction().
*/
int mCmdID;
/*! A string resource id that describes the command. */
int mDescriptionResourceID;
/*! A string resource ID for a short name for the action. This name
appears in the list of Actions in the Customize User Interface dialog. */
int mShortNameResourceID;
/*! A string resource ID for the category of an operation. This name appears in
the Category drop down list in the Customize User Interface dialog. */
int mCategoryResourceID;
};
#define AO_DEFAULT 0x0001 //default option command to execute
#define AO_CLOSEDIALOG 0x0002 //Execute closeDialog option
#define ACTION_OPTION_INTERFACE Interface_ID(0x3c0276f5, 0x190964f5)
#define ACTION_OPTION_INTERFACE_OPT2 Interface_ID(0x0011dcdc, 0x0012dcdc)
// Implement if the an action item supports an alternate options command,
// overwrite ActionItem::GetInterface(ACTION_OPTION_INTERFACE), to return an instance of this class
class IActionOptions : public BaseInterface
{
public:
virtual BOOL ExecuteOptions(DWORD options = AO_DEFAULT) = 0;
};
// Describes an single operation that can be attached to a UI elements
/*! \sa Class ActionTable, Class ActionCallback, Structure ActionDescription, Class ActionContext, Class IActionManager, Class DynamicMenu, Class DynamicMenuCallback, Class MAXIcon, Class Interface.\n\n
\par Description:
This class is available in release 4.0 and later only.\n\n
The class ActionItem is used to represent the operation that live in
ActionTables. ActionItem is an abstract class with operations to support
various UI operations. The system provides a default implementation of this
class that works when the table is build with the
<b>ActionTable::BuildActionTable()</b> method. However, developers may want to
specialize this class for more special-purpose applications. For example,
MAXScipt does this to export macroScripts to an ActionTable. Methods that are
marked as internal should not be used.\n\n
\par Data Members:
protected:\n\n
<b>ActionTable* mpTable;</b>\n\n
Points to the table that owns the action. */
class ActionItem : public InterfaceServer {
public:
/*! \remarks This method retrieves the unique identifier for the action.
This action must be unique in the table, but not does not have to be unique
between tables. */
virtual int GetId() = 0;
// return true if action executed, and FALSE otherwise
/*! \remarks Calling ExecuteAction causes the item to be run. This returns
a BOOL that indicates if the action was actually executed. If the item is
disabled, or if the table that owns it is not activated, then it won't
execute, and returns FALSE.
\return TRUE if the action is executed; otherwise FALSE. */
virtual BOOL ExecuteAction() = 0;
// override this if you wish to customize macroRecorder output for this action
CoreExport virtual void EmitMacro();
// internal Execute(), handles macroRecording, etc. and call ExecuteAction() - jbw 9.9.00
CoreExport BOOL Execute();
// Get the text to put on a button
/*! \remarks This method retrieves the text that will be used when the
ActionItem is on a text button. The text is stored into the buttonText
parameter.
\par Parameters:
<b>MSTR\& buttonText</b>\n\n
Storage for the retrieved text. */
virtual void GetButtonText(MSTR& buttonText) = 0;
// Get the text to use in a menu
/*! \remarks This method retrieves the text to use when the item is on a
menu (either Quad menu or main menu bar). This can be different from the
button text. This method is called just before the menu is displayed, so it
can update the text at that time. For example, the "Undo" menu item in 3ds
Max's main menu adds the name of the command that will be undone.
\par Parameters:
<b>MSTR\& menuText</b>\n\n
Storage for the retrieved text. */
virtual void GetMenuText(MSTR& menuText) = 0;
// Get the long description text for tool tips etc.
/*! \remarks This method gets the text that will be used for tool tips and
menu help. This is also the string that is displayed for the operation in
all the lists in the customization dialogs.
\par Parameters:
<b>MSTR\& descText</b>\n\n
Storage for the retrieved text. */
virtual void GetDescriptionText(MSTR& descText) = 0;
// Get the string describing the category of the item
/*! \remarks This method retrieves the text for the category of the
operation. This is used in the customization dialog to fill the "category"
drop-down list.
\par Parameters:
<b>MSTR\& catText</b>\n\n
Storage for the retrieved text. */
virtual void GetCategoryText(MSTR& catText) = 0;
// check to see if menu items should be checked, or button pressed
/*! \remarks This method determines if the action is in a "Checked" state.
For menus, this means that a check mark will appear next to the item, if
this returns TRUE. If the item is on a button, this is used to determine of
the button is in the "Pressed" state. Note that button states are
automatically updated on selection change and command mode changes. If your
plug-in performs an operation that requires the CUI buttons to be redrawn,
you need to call the method <b>CUIFrameMgr::SetMacroButtonStates(TRUE)</b>.
*/
virtual BOOL IsChecked() = 0;
// Check to see if menu item should show up in context menu
/*! \remarks This method determines if an item is visible on a menu. If it
returns FALSE, then the item is not included in the menu. This can be used
to create items that a context sensitive. For example, you may want an item
to appear on a menu only when the selected object is of a particular type.
To do this, you have this method check the class id of the current
selection. */
virtual BOOL IsItemVisible() = 0;
// Check to see if menu item should be enabled in a menu
/*! \remarks This method determines if the operation is currently
available. If it is on a menu, or button, the item is grayed out if this
method returns FALSE. If it assigned to a keyboard shortcut, then it will
not execute the operation if invoked. . If your plug-in performs an
operation that requires the CUI buttons to be redrawn, you need to call the
method <b>CUIFrameMgr::SetMacroButtonStates(TRUE)</b>.\n\n
\return TRUE for enabled; FALSE for disabled. */
virtual BOOL IsEnabled() = 0;
/*! \remarks If you've provided an icon for this operation, you return it
with this method. If no icon is available, this returns NULL. The icon is
used on CUI buttons, and in the list of operations in the customization
dialogs. */
virtual MaxIcon* GetIcon() = 0;
/*! \remarks Called to delete the ActionItem. This normally happens when
the table that owns it is deleted. */
virtual void DeleteThis() = 0;
/*! \remarks This returns a pointer to the table that owns the ActionItem.
An item can only be owned by a single table.
\par Default Implementation:
<b>{ return mpTable; }</b> */
CoreExport ActionTable* GetTable() { return mpTable; }
/*! \remarks Sets the table that owns the item. Used internally. May be
used if you implement a custom sub-class of ActionItem.
\par Parameters:
<b>ActionTable* pTable</b>\n\n
Points to the table to set.
\par Default Implementation:
<b>{ mpTable = pTable; }</b> */
CoreExport void SetTable(ActionTable* pTable) { mpTable = pTable; }
/*! \remarks Returns the string that describes all the keyboard shortcuts
associated with the item. This will look something like "Alt+A" or "C,
Shift+Alt+Q". This returns NULL if no keyboard shortcut is associated with
the item. */
CoreExport MCHAR* GetShortcutString();
/*! \remarks Returns the representation of the macroScript for the item,
if it's implemented by a macroScript, it returns NULL otherwise.
\par Default Implementation:
<b>{ return NULL; }</b> */
virtual MacroEntry* GetMacroScript() { return NULL; }
// If this method returns true, then the ActionItem creates
// a menu instead of performing an action
/*! \remarks Determines if a menu is created or if an action takes place.
If this method returns TRUE, then the ActionItem creates a menu. If it
returns FALSE then an action is performed.
\par Default Implementation:
<b>{ return FALSE; }</b> */
CoreExport virtual BOOL IsDynamicMenu() { return FALSE; }
// This can be called after an action item is created to tell the
// system that is is a dynamic menu action.
/*! \remarks This method may be called after an action item is created to
tell the system that it is a dynamic menu action. Note: Dynamic menus may
be added to the quad menus programmatically (via the IMenuManager API) or
'manually'. */
CoreExport virtual void SetIsDynamicMenu() {}
// If the ActionItem does produce a menu, this method is called To
// get the menu. See the DynamicMenu class below for an easy way
// to produce these menus. If the menu is requested by a
// right-click quad menu, then hwnd is the window where the click
// occurred, and m is the point in the window where the user
// clicked. If the item is used from a menu bar, hwnd will be NULL.
/*! \remarks If the ActionItem does produce a menu, this method is called
to return a pointer to the menu. See
Class DynamicMenu for an easy way to
produce these menus.
\par Parameters:
<b>HWND hwnd</b>\n\n
If the menu is requested by a right-click quad menu, then this hwnd is the
handle of the window where the click occurred. If the item is used from a
menu bar, this hwnd will be NULL.\n\n
<b>IPoint2\& m</b>\n\n
If the menu is requested by a right-click quad menu, then this parameter is
the point in the window where the user clicked.
\return A pointer to the menu.
\par Default Implementation:
<b>{ return NULL; }</b> */
CoreExport virtual IMenu* GetDynamicMenu(HWND hwnd, IPoint2& m) { return NULL; }
// ActionItems that are deleted after they execute should return TRUE.
CoreExport virtual BOOL IsDynamicAction() { return FALSE; }
protected:
ActionTable* mpTable; // The table that owns the action
};
#define ACTIONITEM_STANDIN_INTERFACE Interface_ID(0x108e1314, 0x5aff3138)
class IActionItemStandin : public BaseInterface
{
public:
virtual void SetPersistentActionId(MSTR idString) = 0;
virtual MSTR &GetPersistentActionId() = 0;
virtual void SetActionTableId( ActionTableId id ) = 0;
virtual ActionTableId GetActionTableId() = 0;
virtual MSTR &GetPrefixString() = 0;
};
inline IActionItemStandin* GetIActionItemStandin(ActionItem* a) { return (IActionItemStandin*)a->GetInterface(ACTIONITEM_STANDIN_INTERFACE); }
class ActionItemStandin: public ActionItem, public IActionItemStandin {
public:
CoreExport ActionItemStandin(int cmdId );
CoreExport virtual ~ActionItemStandin() {};
CoreExport virtual int GetId() { return mCmdId; }
CoreExport virtual void SetId(int id) { mCmdId = id; }
CoreExport virtual MCHAR* GetDescription() { return mName.data();}
CoreExport virtual void SetDescription(MCHAR* pDesc) { mName = pDesc; }
CoreExport virtual MCHAR* GetShortName() { return mName.data();}
CoreExport virtual void SetShortName(MCHAR* pShortName) { mName = pShortName; }
CoreExport virtual MCHAR* GetCategory() { return mName.data();}
CoreExport virtual void SetCategory(MCHAR* pCategory) { mName = pCategory; }
CoreExport virtual MaxIcon* GetIcon() { return NULL; };
// return true if action executed, and FALSE otherwise
CoreExport virtual BOOL ExecuteAction() { return FALSE; };
// Get the text to put on a button
CoreExport virtual void GetButtonText(MSTR& buttonText) { buttonText = mName; };
// Get the text to use in a menu
CoreExport virtual void GetMenuText(MSTR& menuText) { menuText = mName; };
// Get the long description text for tool tips etc.
CoreExport virtual void GetDescriptionText(MSTR& descText) { descText = mName; };
// Get the string describing the category of the item
CoreExport virtual void GetCategoryText(MSTR& catText) { catText = mName; };
// check to see if menu items should be checked, or button pressed
CoreExport virtual BOOL IsChecked() { return FALSE; };
// Check to see if menu item should show up in context menu
CoreExport virtual BOOL IsItemVisible() { return TRUE; };
// Check to see if menu item should be enabled in a menu
CoreExport virtual BOOL IsEnabled() { return FALSE; };
CoreExport virtual BOOL IsDynamicMenu() { return FALSE; }
CoreExport virtual void SetIsDynamicMenu() { };
CoreExport virtual IMenu* GetDynamicMenu(HWND hwnd, IPoint2& m) { return NULL; };
CoreExport void DeleteThis();
CoreExport virtual BaseInterface* GetInterface(Interface_ID id);
// IActionItemStandin
CoreExport virtual void SetPersistentActionId(MSTR idString);
CoreExport virtual MSTR &GetPersistentActionId() { return mPersistentActionId; };
CoreExport virtual void SetActionTableId( ActionTableId id ) { mId = id; };
CoreExport virtual ActionTableId GetActionTableId() { return mId; };
CoreExport virtual MSTR &GetPrefixString() { return mPrefix; };
protected:
int mCmdId;
MSTR mName;
MSTR mPersistentActionId;
MSTR mPrefix;
ActionTableId mId;
};
class ActionCallback;
// A table of actions that can be tied to UI elements (buttons, menus, RC menu,
// keyboard shortcuts)
/*! \sa Class BaseInterfaceServer, Class ClassDesc, Structure ActionDescription, Class ActionItem, Class ActionCallback, Class ActionContext, Class IActionManager, Class DynamicMenu, Class DynamicMenuCallback, Class Interface.\n\n
\par Description:
This class is available in release 4.0 and later only.\n\n
This is the class used to create Action Tables. An ActionTable holds a set of
ActionItems, which are operations that can be tied to various UI elements, such
as keyboard shortcuts, CUI buttons, the main menu and the Quad menu. 3ds Max's
core code exports several ActionTables for built-in operations in 3ds Max.
Plug-ins can also export their own action tables via methods available in
ClassDesc.\n\n
All methods of this class are implemented by the system. Note however that many
methods are virtual and may be customized by the plug-in developer as this
class may be sub-classed if required. See the Advanced Topics section
<a href="ms-its:3dsMaxSDK.chm::/ui_customization_root.html">UI
Customization</a> for details on sub-classing this class and ActionItem. For
details on implementing an ActionTable please refer to
<b>/MAXSDK/SAMPLES/MODIFIERS/FFD</b> */
class ActionTable : public BaseInterfaceServer {
public:
/*! \remarks Constructor. This constructor builds the action table using
an array of descriptors. It takes the ID of the table, the context id, a
name for the table, a windows accelerator table that gives default keyboard
assignments for the operations, the number of items, the table of operation
descriptions, and the instance of the module where the string resources in
the table are stored.\n\n
At the same time the action table is built developers need to register the
action context ID with the system. This is done using the
<b>IActionManager::RegisterActionContext()</b> method.
\par Parameters:
<b>ActionTableId id</b>\n\n
The unique ID for the ActionTable. Every ActionTable has a unique 32-bit
integer ID. For new tables exported by plug-ins, the developer should
choose a random 32-bit integer. You can use the Class_ID program to
generate this identifier: See Class
Class_ID for more details. Simply use one of the two DWORDs that
comprise the Class_ID for the ActionTableId.\n\n
<b>ActionContextId contextId</b>\n\n
The ActionContextID associated with this table. Several tables may share
the same ActionContextID.\n\n
<b>MSTR\& name</b>\n\n
The name for the ActionTable.\n\n
<b>HACCEL hDefaults</b>\n\n
The handle of the a windows accelerator table that gives default keyboard
assignments for the operations.\n\n
<b>int numIds</b>\n\n
The number of items in the description array below.\n\n
<b>ActionDescription* pOps</b>\n\n
Points to the array of the operator descriptors.\n\n
<b>HINSTANCE hInst</b>\n\n
The handle to the instance of the module where the string resources in the
array of operator descriptors are stored. */
CoreExport ActionTable(ActionTableId id,
ActionContextId contextId,
MSTR& name,
HACCEL hDefaults,
int numIds,
ActionDescription* pOps,
HINSTANCE hInst);
/*! \remarks Constructor. This constructor build a new empty action table
with the given ID, context ID and name. You then need to add ActionItems to
the table separately using the <b>AppendOperation()</b> method described
below.
\par Parameters:
<b>ActionTableId id</b>\n\n
The unique ID for the ActionTable.\n\n
<b>ActionContextId contextId</b>\n\n
The ActionContextID associated with this table. Several tables may share
the same ActionContextID.\n\n
<b>MSTR\& name</b>\n\n
The name for the ActionTable. */
CoreExport ActionTable(ActionTableId id,
ActionContextId contextId,
MSTR& name);
/*! \remarks Destructor. Deletes all the operations maintained by the
table and deletes the keyboard accelerator table if in use. */
CoreExport virtual ~ActionTable();
// Get/Set the current keyboard accelerators for the table
/*! \remarks Returns the handle of the current keyboard accelerator for
the table. */
CoreExport HACCEL GetHAccel() { return mhAccel; }
/*! \remarks Sets the current keyboard accelerator for the table. */
CoreExport void SetHAccel(HACCEL hAccel) { mhAccel = hAccel; }
// Get the default keyboard accelerator table. This is used when
// the user has not assigned any accelerators.
/*! \remarks Get the default keyboard accelerator table. This is used when
the user has not assigned any accelerators. */
CoreExport HACCEL GetDefaultHAccel() { return mhDefaultAccel; }
CoreExport void SetDefaultHAccel(HACCEL accel) { mhDefaultAccel = accel; }
CoreExport MSTR& GetName() { return mName; }
CoreExport ActionTableId GetId() { return mId; }
/*! \remarks Returns the ActionContextId for this ActionTable. */
CoreExport ActionContextId GetContextId() { return mContextId; }
// Get the current callback assocuated with this table.
// returns NULL if the table is not active.
/*! \remarks Get the current callback associated with this table. Returns
NULL if the table is not active. */
CoreExport ActionCallback* GetCallback() { return mpCallback; }
/*! \remarks Sets the callback object used by this ActionTable.
\par Parameters:
<b>ActionCallback* pCallback</b>\n\n
Points to the callback to set. */
CoreExport void SetCallback(ActionCallback* pCallback) { mpCallback = pCallback; }
// Methods to iterate over the actions in the table
/*! \remarks Returns the number of ActionItems in the table. */
CoreExport int Count() { return mOps.Count(); }
/*! \remarks This operator returns a pointer to the 'i-th' ActionItem.
\par Parameters:
<b>int i</b>\n\n
The zero based index in the list of ActionItems. */
CoreExport ActionItem* operator[](int i) { return mOps[i]; }
// Get an action by its command id.
/*! \remarks Returns a pointer to the ActionItem associated with the
command ID passed.
\par Parameters:
<b>int cmdId</b>\n\n
The command ID. */
CoreExport ActionItem* GetAction(int cmdId);
// Add an operation to the table
/*! \remarks This method adds an operation to the table.
\par Parameters:
<b>ActionItem* pAction</b>\n\n
Points to the ActionItem to append. */
CoreExport void AppendOperation(ActionItem* pAction);
// Remove an operation from the table
/*! \remarks Remove an operation from the table
\par Parameters:
<b>ActionItem* pAction</b>\n\n
Points to the ActionItem to delete.
\return TRUE if the operation was deleted; FALSE if it could not be found
and wasn't. */
CoreExport BOOL DeleteOperation(ActionItem* pAction);
/*! \remarks Deletes this ActionItem.
\par Default Implementation:
<b>{ delete this; }</b> */
CoreExport virtual void DeleteThis();
// Get the text to put on a button
/*! \remarks This method retrieves the text that will be used when the
ActionItem is on a text button.
\par Parameters:
<b>int cmdId</b>\n\n
The unique ID of the command whose button text is retrieved.\n\n
<b>MSTR\& buttonText</b>\n\n
Storage for the text.
\return TRUE if the command is in the table; otherwise FALSE. */
CoreExport virtual BOOL GetButtonText(int cmdId, MSTR& buttonText);
// Get the text to use in a menu
/*! \remarks This method retrieves the text to use when the item is on a
menu (either Quad menu or main menu bar). This can be different from the
button text.
\par Parameters:
<b>int cmdId</b>\n\n
The unique ID of the command whose menu text is retrieved.\n\n
<b>MSTR\& menuText</b>\n\n
Storage for the text.
\return TRUE if the command is in the table; otherwise FALSE.
\par Default Implementation:
<b>{ return GetButtonText(cmdId, menuText); }</b> */
CoreExport virtual BOOL GetMenuText(int cmdId, MSTR& menuText)
{ return GetButtonText(cmdId, menuText); }
// Get the long description text for tool tips etc.
/*! \remarks This method gets the text that will be used for tool tips and
menu help. This is also the string that is displayed for the operation in
all the lists in the customization dialogs.
\par Parameters:
<b>int cmdId</b>\n\n
The unique ID of the command whose description text is retrieved.\n\n
<b>MSTR\& descText</b>\n\n
Storage for the text.
\return TRUE if the command is in the table; otherwise FALSE. */
CoreExport virtual BOOL GetDescriptionText(int cmdId, MSTR& descText);
// check to see if menu items should be checked, or button pressed
/*! \remarks Returns TRUE if the menu item should be checked or a CUI
button should be in the pressed state.
\par Parameters:
<b>int cmdId</b>\n\n
The unique ID of the command.
\par Default Implementation:
<b>{ return FALSE; }</b> */
CoreExport virtual BOOL IsChecked(int cmdId) { return FALSE; }
// Check to see if menu item should show up in context menu
/*! \remarks This method determines if an item is to be visible on a menu.
Returns TRUE if visible; FALSE if not.
\par Parameters:
<b>int cmdId</b>\n\n
The unique ID of the command.
\par Default Implementation:
<b>{ return TRUE; }</b> */
CoreExport virtual BOOL IsItemVisible(int cmdId) { return TRUE; }
// Check to see if menu item should be enabled in a menu
/*! \remarks This method determines if the operation is currently enabled
and available. Returns TRUE if enabled; FALSE if disabled.
\par Parameters:
<b>int cmdId</b>\n\n
The unique ID of the command.
\par Default Implementation:
<b>{ return TRUE; }</b> */
CoreExport virtual BOOL IsEnabled(int cmdId) { return TRUE; }
// Write an action identifier to a CUI file or KBD file
// Default implementation is to write the integer ID.
// This is over-riden when command IDs are not persistent
/*! \remarks This method will write an action identifier to a *.CUI file
or *.KBD file. It's default implementation is to write the integer ID but
will be over-riden when command IDs are not persistent.
\par Parameters:
<b>int cmdId</b>\n\n
The unique ID of the command.\n\n
<b>MSTR\& idString</b>\n\n
The action ID placed in the string. */
CoreExport virtual void WritePersistentActionId(int cmdId, MSTR& idString);
// Read an action identifier from a CUI file or KBD file
// Default implementation is to read the integer ID.
// This is over-riden when command IDs are not persistent
// Returns -1 if the command is not found in the table
/*! \remarks This method will read an action identifier from a *.CUI file
or *.KBD file. It's default implementation is to read the integer ID but
will be over-riden when command IDs are not persistent.
\par Parameters:
<b>MSTR\& idString</b>\n\n
The action ID string.
\return This method returns -1 if the command was not found in the table.
*/
CoreExport virtual int ReadPersistentActionId(MSTR& idString);
// return an optional icon for the command
/*! \remarks Returns an optional icon for the command, or NULL if there is
none.
\par Parameters:
<b>int cmdID</b>\n\n
The unique ID of the command. */
CoreExport virtual MaxIcon* GetIcon(int cmdId) { return NULL; };
// Fill the action table with the given action descriptions
/*! \remarks This method will fill the action table with the given action
descriptions.
\par Parameters:
<b>HACCEL hDefaults</b>\n\n
The handle of the a windows accelerator table that provides keyboard
assignments for the operations.\n\n
<b>int numIds</b>\n\n
The number of ID's to add to the action table.\n\n
<b>ActionDescription* pOps</b>\n\n
The array of action descriptions to build the table from.\n\n
<b>HINSTANCE hInst</b>\n\n
The handle to the instance of the module. */
CoreExport void BuildActionTable(HACCEL hDefaults,
int numIds,
ActionDescription* pOps,
HINSTANCE hInst);
// Get the action assigned to the given accelerator, if any
/*! \remarks Get the action assigned to the given accelerator, if any.
\par Parameters:
<b>ACCEL accel</b>\n\n
The accelerator key you wish to check the assignment for. */
CoreExport ActionItem* GetCurrentAssignment(ACCEL accel);
// Assign the command to th given accelerator. Also removes any
// previous assignment to that accelerator
/*! \remarks Assign the command to the given accelerator. Also removes any
previous assignment to that accelerator.
\par Parameters:
<b>int cmdId</b>\n\n
The command ID.\n\n
<b>ACCEL accel</b>\n\n
The accelerator key you wish to assign. */
CoreExport void AssignKey(int cmdId, ACCEL accel);
// removes the given assignment from the shortcut table
/*! \remarks removes the given assignment from the shortcut table
\par Parameters:
<b>ACCEL accel</b>\n\n
The accelerator key you wish to remove from the shortcut table. */
void RemoveShortcutFromTable(ACCEL accel);
private:
// These values are set by the plug-in to describe a action table
// Unique identifier of table (like a class id)
ActionTableId mId;
// An identifier to group tables use the same context. Tables with the
// same context cannot have overlapping keyboard shortcuts.
ActionContextId mContextId;
// Name to use in preference dlg drop-down
MSTR mName;
// Descriptors of all operations that can have Actions
Tab<ActionItem*> mOps;
// The windows accelerator table in use when no keyboard shortcuts saved
HACCEL mhDefaultAccel;
// The windows accelerator table in use
HACCEL mhAccel;
// The currently active callback
ActionCallback* mpCallback;
};
/*! \sa Class BaseInterfaceServer, Class ActionTable, Class ActionItem, Class ActionContext, Class IActionManager, Class DynamicMenu, Class DynamicMenuCallback, Class Interface.\n\n
\par Description:
This class is available in release 4.0 and later only.\n\n
An important part of implementing an ActionTable is creating a sub-class of
this class. This is an abstract class with a virtual method called
ExecuteAction(int id). Developers need to sub-class this class and pass an
instance of it to the system when they activate an ActionTable. Then when the
system wants to execute an action the ExecuteAction() method is called.\n\n
All methods of this class are virtual.\n\n
\par Data Members:
private:\n\n
<b>ActionTable *mpTable;</b>\n\n
Points to the table that uses this ActionCallback. */
class ActionCallback : public BaseInterfaceServer {
public:
CoreExport virtual ~ActionCallback(){};
/*! \remarks This method is called to actually execute the action.
\par Parameters:
<b>int id</b>\n\n
The ID of the item to execute.
\return This returns a BOOL that indicates if the action was actually
executed. If the item is disabled, or if the table that owns it is not
activated, then it won't execute, and returns FALSE. If it does execute
then TRUE is returned.
\par Default Implementation:
<b>{ return FALSE; }</b> */
CoreExport virtual BOOL ExecuteAction(int id) { return FALSE; }
// called when an action item says it is a dynamic menu
/*! \remarks This method is called when an action item says it is a
dynamic menu. This returns a pointer to the menu itself.
\par Parameters:
<b>int id</b>\n\n
The item ID which is passed to the
<b>DynamicMenuCallback::MenuItemSelected()</b>\n\n
<b>HWND hwnd</b>\n\n
If the menu is requested by a right-click quad menu, then hwnd is the
window where the click occurred. If the item is used from a menu bar, then
hwnd will be NULL.\n\n
<b>IPoint2\& m</b>\n\n
If the menu is requested by a right-click quad menu, then this will be the
point in the window where the user clicked.
\par Default Implementation:
<b>{ return NULL; }</b> */
CoreExport virtual IMenu* GetDynamicMenu(int id, HWND hwnd, IPoint2& m) { return NULL; }
// Access to the table the callback uses
/*! \remarks Returns a pointer to the ActionTable the callback uses.
\par Default Implementation:
<b>{ return mpTable; }</b> */
ActionTable* GetTable() { return mpTable; }
/*! \remarks Sets the ActionTable the callback uses.
\par Parameters:
<b>ActionTable* pTable</b>\n\n
Points to the ActionTable the callback uses.
\par Default Implementation:
<b>{ mpTable = pTable; }</b> */
void SetTable(ActionTable* pTable) { mpTable = pTable; }
private:
ActionTable *mpTable;
};
// An ActionContext is an identifer of a group of keyboard shortcuts.
// Examples are Main UI, Tack View, and Editable Mesh. They are
// registered using Interface::RegisterActionContext().
//
/*! \sa Class ActionTable, Class ActionItem, Class ActionCallback, Class IActionManager, Class DynamicMenu, Class DynamicMenuCallback, Class Interface.\n\n
\par Description:
This class is available in release 4.0 and later only.\n\n
Every ActionTable also has an ActionContextId associated with it. This
ActionContextId can be shared with other tables.\n\n
When assigning keyboard shortcuts to items in an ActionTable, tables that share
a unique context id are forced to have unique shortcuts. Tables with different
context ids can have overlapping keyboard shortcut assignments.\n\n
An ActionContext is an identifer of a group of keyboard shortcuts. Examples are
the Main 3ds Max UI, Track %View, and the Editable Mesh. They are registered
using <b>IActionManager::RegisterActionContext()</b>.\n\n
Note: <b>typedef DWORD ActionContextId;</b> */
class ActionContext: public MaxHeapOperators {
public:
/*! \remarks Constructor. The context ID and the name are initialized from
the data passed.
\par Parameters:
<b>ActionContextId contextId</b>\n\n
The ID for the ActionContext.\n\n
<b>MCHAR *pName</b>\n\n
The name for the ActionContext. */
ActionContext(ActionContextId contextId, MCHAR *pName)
{ mContextId = contextId; mName = pName; mActive = true; }
/*! \remarks Returns the name of this ActionContext. */
MCHAR* GetName() { return mName.data(); }
/*! \remarks Returns the ID of this ActionContext. */
ActionContextId GetContextId() { return mContextId; }
/*! \remarks Returns true if this ActionContext is active; otherwise
false. An active ActionContext means that it uses its keyboard
accelerators. This corresponds to the "Active" checkbox in the keyboard
customization UI. */
bool IsActive() { return mActive; }
/*! \remarks Sets the active state of this ActionContext.
\par Parameters:
<b>bool active</b>\n\n
Pass true for active; false for inactive. */
void SetActive(bool active) { mActive = active; }
private:
ActionContextId mContextId;
MSTR mName;
bool mActive;
};
// The ActionManager manages a set of ActionTables, callbacks and ActionContexts.
// The manager handles the keyboard accelerator tables for each ActionTable
// as well. You get a pointer to this class using Interface::GetActionManager().
#define ACTION_MGR_INTERFACE Interface_ID(0x4bb71a79, 0x4e531e4f)
/*! \sa Class ActionTable, Class ClassDesc, Class ActionItem, Class ActionCallback, Class ActionContext, Class DynamicMenu, Class DynamicMenuCallback, Class Interface.\n\n
\par Description:
This class is available in release 4.0 and later only.\n\n
The ActionManager manages a set of ActionTables, callbacks and ActionContexts.
The manager handles the keyboard accelerator tables for each ActionTable as
well. You get a pointer to this class using
<b>Interface::GetActionManager()</b>. */
class IActionManager : public FPStaticInterface {
public:
// Register an action table with the manager.
// Note that most plug-ins will not need this method. Instead,
// plug-ins export action table with the methods in ClassDesc.
/*! \remarks Register an action table with the manager. Note that most
plug-ins will not need this method. Instead, plug-ins export action table
with the methods in ClassDesc. See
<a href="class_class_desc.html#A_GM_cldesc_actiontable">ClassDesc Action
Table Methods</a>.
\par Parameters:
<b>ActionTable* pTable</b>\n\n
Points to the Action Table to register. */
virtual void RegisterActionTable(ActionTable* pTable) = 0;
// Methods to iterate over the action table
/*! \remarks Returns the number of ActionTables. */
virtual int NumActionTables() = 0;
/*! \remarks Returns a pointer to the 'i-th' ActionTable.
\par Parameters:
<b>int i</b>\n\n
The zero based index of the table. */
virtual ActionTable* GetTable(int i) = 0;
// These methods are used to turn a table on and off.
/*! \remarks This method is called to activate the action table. Some
plug-ins (for instance Modifiers or Geometric Objects) may only want to
activate the table when they are being edited in the command panel (between
BeginEditParams() and EndEditParams()). Others, for instance Global Utility
Plug-ins, may wish to do so when they are initially loaded so the actions
are always available.\n\n
Note that if this method is called multiple times, only the callback from
the last call will be used.
\par Parameters:
<b>ActionCallback* pCallback</b>\n\n
Points to the callback object which is responsible for executing the
action.\n\n
<b>ActionTableId id</b>\n\n
This is the ID of the table to activate.
\return TRUE if the action table was activated. FALSE if the table is
already active or doesn't exist. */
virtual int ActivateActionTable(ActionCallback* pCallback, ActionTableId id) = 0;
/*! \remarks This method is called to deactivate the action table. After
the table is deactivated (for example in EndEditParams()) the callback
object can be deleted. Tables are initially active, please do not call this
method without a preceding call to <b>ActivateActionTable()</b>.
\par Parameters:
<b>ActionCallback* pCallback</b>\n\n
Points to the callback object responsible for executing the action. Pass
the same callback that was originally passed to
<b>ActivateActionTable()</b> and do not set this to NULL.\n\n
<b>ActionTableId id</b>\n\n
The ID of the table to deactivate.
\return TRUE if the action table was deactivated. FALSE if the table was
already deactivated or doesn't exist. */
virtual int DeactivateActionTable(ActionCallback* pCallback, ActionTableId id) = 0;
// Find a table based on its id.
/*! \remarks This method returns a pointer to the action table as
specified by it's ID.
\par Parameters:
<b>ActionTableId id</b>\n\n
The ID of the table to find. */
virtual ActionTable* FindTable(ActionTableId id) = 0;
// Get the string that describes the keyboard shortcut for the operation
/*! \remarks Retrieves the string that describes the keyboard shortcut for
the operation.
\par Parameters:
<b>ActionTableId tableId</b>\n\n
The ID of the action table.\n\n
<b>int commandId</b>\n\n
The ID of the command for the action.\n\n
<b>MCHAR* buf</b>\n\n
Points to storage for the string.
\return TRUE if found; FALSE if not found. */
virtual BOOL GetShortcutString(ActionTableId tableId, int commandId, MCHAR* buf) = 0;
// Get A string the descibes an operation
/*! \remarks Retrieves a string that descibes the specified operation from
the action table whose ID is passed.
\par Parameters:
<b>ActionTableId tableId</b>\n\n
The ID of the action table.\n\n
<b>int commandId</b>\n\n
The ID of the command.\n\n
<b>MCHAR* buf</b>\n\n
Points to storage for the description string.
\return TRUE if the string was returned; FALSE if not. */
virtual BOOL GetActionDescription(ActionTableId tableId, int commandId, MCHAR* buf) = 0;
// Register an action context. This is called when you create the
// action table that uses this context.
/*! \remarks Register the specified action context with the system. This
is called when you create the action table that uses this context.
\par Parameters:
<b>ActionContextId contextId</b>\n\n
The context ID.\n\n
<b>MCHAR* pName</b>\n\n
The name for the action context.
\return If the specified action context is already registered FALSE is
returned; otherwise TRUE is returned. */
virtual BOOL RegisterActionContext(ActionContextId contextId, MCHAR* pName) = 0;
// Methods to iterate over the action contexts
/*! \remarks Returns the number of ActionContexts. */
virtual int NumActionContexts() = 0;
/*! \remarks Returns a pointer to the 'i-th' ActionContext.
\par Parameters:
<b>int i</b>\n\n
The zero based index of the ActionContext. */
virtual ActionContext* GetActionContext(int i) = 0;
// Find a context based on it's ID.
/*! \remarks Returns a pointer to the ActionContext based on it's ID. If
not found NULL is returned.
\par Parameters:
<b>ActionContextId contextId</b>\n\n
The ID whose context is found. */
virtual ActionContext* FindContext(ActionContextId contextId) = 0;
// Query whether a context is active.
/*! \remarks Returns TRUE if the specified context is active; otherwise
FALSE.
\par Parameters:
<b>ActionContextId contextId</b>\n\n
Specifies the context to check. */
virtual BOOL IsContextActive(ActionContextId contextId) = 0;
// Internal methods used by the keyboard shotcut UI
virtual MCHAR* GetShortcutFile() = 0;
virtual MCHAR* GetShortcutDir() = 0;
virtual int IdToIndex(ActionTableId id) = 0;
virtual void SaveAllContextsToINI() = 0;
virtual int MakeActionSetCurrent(MCHAR* pDir, MCHAR* pFile) = 0;
virtual int LoadAccelConfig(LPACCEL *accel, int *cts, ActionTableId tableId = -1,
BOOL forceDefault = FALSE) = 0;
virtual int SaveAccelConfig(LPACCEL *accel, int *cts) = 0;
virtual int GetCurrentActionSet(MCHAR *buf) = 0;
virtual BOOL SaveKeyboardFile(MCHAR* pFileName) = 0;
virtual BOOL LoadKeyboardFile(MCHAR* pFileName) = 0;
virtual MCHAR* GetKeyboardFile() = 0;
// Function IDs
enum {
executeAction,
#ifndef NO_CUI // russom - 02/12/02
saveKeyboardFile,
loadKeyboardFile,
getKeyboardFile,
#endif // NO_CUI
};
};
//!Class IActionManager
/*!
A mixin-interface extension to IActionManager which allows a client to dispatch a Message back to the application
if it is not handled by the focused control.
Can be accessed by calling
\code
Interface10* ip = GetCOREInterface10();
IActionManager* actionMgr = ip-> GetActionManager();
IActionManagerExt* ext =
static_cast<IActionManagerExt*>(actionMgr->GetInterface(IActionManagerExt::kActionMgr10InterfaceID));
\endcode
\remarks This interface is NOT intended for extension by 3rd-party developers.
\see IActionManager
*/
class IActionManager10 : public BaseInterface, public MaxSDK::Util::Noncopyable {
public:
//! \brief The ID for this interface. See class description for usage.
CoreExport static const Interface_ID kActionMgr10InterfaceID;
//! \brief Dispatches a windows Message structure to the application
/*! Takes a MSG structure and dispatches it to the main application proc directly.
This function can be used to dispatch WM_KEYDOWN events to the application for processing.
If a control or dialog is capturing input messages, then this function is useful to delegate
message handling to the main application window proc in the case where the message is not handled
by the focused control hierarchy or the activated (modeless) dialog.
\param[in, out] message The message to dispatch to the application.
\return true if the message is handled by the application
*/
virtual bool DispatchMessageToApplication(MSG* message) = 0;
//! \brief Returns the interface ID
CoreExport virtual Interface_ID GetID();
protected:
//! \brief The constructor / destructor are defined in Core.dll, but bear in mind that this interface is NOT
//! intended for extension.
CoreExport IActionManager10();
//! \brief The constructor / destructor are defined in Core.dll, but bear in mind that this interface is NOT
//! intended for extension.
CoreExport virtual ~IActionManager10();
};
// The DynamicMenu class provides a way for plugins to produce
// the menu needed in the ActionItem::GetDynamicMenu() method.
/*! \sa Class DynamicMenu, Class IMenu, Class ActionTable, Class ActionItem, Class ActionCallback, Class ActionContext, Class IActionManager, Class Interface.\n\n
\par Description:
This class is available in release 4.0 and later only.\n\n
This is the callback object for a dynamic menu. When a user makes a selection
from a dynamic menu the <b>MenuItemSelected()</b> method of this class is
called to process that selection. */
class DynamicMenuCallback: public MaxHeapOperators {
public:
/*! \remarks This method is called to process the user's menu selection.
\par Parameters:
<b>int itemId</b>\n\n
The ID of the item selected. */
virtual void MenuItemSelected(int itemId) = 0;
};
/*! \sa Class DynamicMenuCallback, Class IMenu, Class ActionTable, Class ActionItem, Class ActionCallback, Class ActionContext, Class IActionManager, Class Interface.\n\n
\par Description:
This class is available in release 4.0 and later only.\n\n
This class provides a simple way for plug-ins to produce the menu needed in the
<b>ActionItem::GetDynamicMenu()</b> method. The constructor of this class is
used to create the menu and the GetMenu() method returns the appropriate IMenu
pointer. */
class DynamicMenu: public MaxHeapOperators {
public:
/*! \remarks Constructor.
\par Parameters:
<b>DynamicMenuCallback* pCallback</b>\n\n
Points to the instance of the DynamicMenuCallback class that handles the
menu selection. */
CoreExport DynamicMenu(DynamicMenuCallback* pCallback);
// Called after menu creation to get the IMenu created.
// This is the value returned from ActionItem::GetDynamicMenu()
/*! \remarks Returns a pointer to the IMenu. This method may be called
after menu creation to get a pointer to the IMenu created. This is the
required value to return from <b>ActionItem::GetDynamicMenu()</b>. */
CoreExport IMenu* GetMenu();
enum DynamicMenuFlags {
kDisabled = 1 << 0,
kChecked = 1 << 1,
kSeparator = 1 << 2,
};
// Add an item to the dynamic menu.
/*! \remarks This method adds an item to the dynamic menu.
\par Parameters:
<b>DWORD flags</b>\n\n
One or more of the following values:\n\n
<b>kDisabled</b>\n\n
Item is disabled (can't be selected)\n\n
<b>kChecked</b>\n\n
Item has a check mark beside it.\n\n
<b>kSeparator</b>\n\n
Item is a seperator between the previous menu item and the next one.\n\n
<b>UINT itemId</b>\n\n
The ID for the menu item.\n\n
<b>MCHAR* pItemTitle</b>\n\n
The name to appear for the menu item. */
CoreExport void AddItem(DWORD flags, UINT itemId, MCHAR* pItemTitle);
/*! \remarks This begins a new sub menu. Items added after this call will
appear as sub choices of this one until <b>EndSubMenu()</b> is called.
\par Parameters:
<b>MCHAR* pTitle</b>\n\n
The name to appear for the sub menu item. */
CoreExport void BeginSubMenu(MCHAR* pTitle);
/*! \remarks This ends a sub menu. Items added after this call will appear
as they did prior to calling <b>BeginSubMenu()</b>. */
CoreExport void EndSubMenu();
private:
Stack<IMenu*> mMenuStack;
DynamicMenuCallback *mpCallback;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
1074
]
]
]
|
20cc41c03990b2c8d237ddb6ae5302c73ba625a5 | 02c2e62bcb9a54738bfbd95693978b8709e88fdb | /opencv/cvhough.cpp | 55f16bfc34f8775383cbb35052dfe373827c00a9 | []
| no_license | ThadeuFerreira/sift-coprojeto | 7ab823926e135f0ac388ae267c40e7069e39553a | bba43ef6fa37561621eb5f2126e5aa7d1c3f7024 | refs/heads/master | 2021-01-10T15:15:21.698124 | 2009-05-08T17:38:51 | 2009-05-08T17:38:51 | 45,042,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,428 | cpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include "_cv.h"
#include "_cvlist.h"
#define halfPi ((float)(CV_PI*0.5))
#define Pi ((float)CV_PI)
#define a0 0 /*-4.172325e-7f*/ /*(-(float)0x7)/((float)0x1000000); */
#define a1 1.000025f /*((float)0x1922253)/((float)0x1000000)*2/Pi; */
#define a2 -2.652905e-4f /*(-(float)0x2ae6)/((float)0x1000000)*4/(Pi*Pi); */
#define a3 -0.165624f /*(-(float)0xa45511)/((float)0x1000000)*8/(Pi*Pi*Pi); */
#define a4 -1.964532e-3f /*(-(float)0x30fd3)/((float)0x1000000)*16/(Pi*Pi*Pi*Pi); */
#define a5 1.02575e-2f /*((float)0x191cac)/((float)0x1000000)*32/(Pi*Pi*Pi*Pi*Pi); */
#define a6 -9.580378e-4f /*(-(float)0x3af27)/((float)0x1000000)*64/(Pi*Pi*Pi*Pi*Pi*Pi); */
#define _sin(x) ((((((a6*(x) + a5)*(x) + a4)*(x) + a3)*(x) + a2)*(x) + a1)*(x) + a0)
#define _cos(x) _sin(halfPi - (x))
/****************************************************************************************\
* Classical Hough Transform *
\****************************************************************************************/
typedef struct CvLinePolar
{
float rho;
float angle;
}
CvLinePolar;
/*=====================================================================================*/
#define hough_cmp_gt(l1,l2) (aux[l1] > aux[l2])
static CV_IMPLEMENT_QSORT_EX( icvHoughSortDescent32s, int, hough_cmp_gt, const int* );
/*
Here image is an input raster;
step is it's step; size characterizes it's ROI;
rho and theta are discretization steps (in pixels and radians correspondingly).
threshold is the minimum number of pixels in the feature for it
to be a candidate for line. lines is the output
array of (rho, theta) pairs. linesMax is the buffer size (number of pairs).
Functions return the actual number of found lines.
*/
static CvStatus
icvHoughLines_8uC1R( uchar* image, int step, CvSize size,
float rho, float theta, int threshold,
CvSeq *lines, int linesMax )
{
int width, height;
int numangle, numrho;
int *accum = 0;
int *sort_buf=0;
int total = 0;
float *tabSin = 0;
float *tabCos = 0;
float ang;
int r, n;
int i, j;
float irho = 1 / rho;
double scale;
width = size.width;
height = size.height;
if( image == NULL )
return CV_NULLPTR_ERR;
if( width < 0 || height < 0 )
return CV_BADSIZE_ERR;
numangle = (int) (Pi / theta);
numrho = (int) (((width + height) * 2 + 1) / rho);
accum = (int*)cvAlloc( sizeof(accum[0]) * (numangle+2) * (numrho+2) );
sort_buf = (int*)cvAlloc( sizeof(accum[0]) * numangle * numrho );
tabSin = (float*)cvAlloc( sizeof(tabSin[0]) * numangle );
tabCos = (float*)cvAlloc( sizeof(tabCos[0]) * numangle );
memset( accum, 0, sizeof(accum[0]) * (numangle+2) * (numrho+2) );
if( tabSin == 0 || tabCos == 0 || accum == 0 )
goto func_exit;
for( ang = 0, n = 0; n < numangle; ang += theta, n++ )
{
tabSin[n] = (float)(sin(ang) * irho);
tabCos[n] = (float)(cos(ang) * irho);
}
// stage 1. fill accumulator
for( j = 0; j < height; j++ )
for( i = 0; i < width; i++ )
{
if( image[j * step + i] != 0 )
for( n = 0; n < numangle; n++ )
{
r = cvRound( i * tabCos[n] + j * tabSin[n] );
r += (numrho - 1) / 2;
accum[(n+1) * (numrho+2) + r+1]++;
}
}
// stage 2. find local maximums
for( r = 0; r < numrho; r++ )
for( n = 0; n < numangle; n++ )
{
int base = (n+1) * (numrho+2) + r+1;
if( accum[base] > threshold &&
accum[base] > accum[base - 1] && accum[base] >= accum[base + 1] &&
accum[base] > accum[base - numrho - 2] && accum[base] >= accum[base + numrho + 2] )
sort_buf[total++] = base;
}
// stage 3. sort the detected lines by accumulator value
icvHoughSortDescent32s( sort_buf, total, accum );
// stage 4. store the first min(total,linesMax) lines to the output buffer
linesMax = MIN(linesMax, total);
scale = 1./(numrho+2);
for( i = 0; i < linesMax; i++ )
{
CvLinePolar line;
int idx = sort_buf[i];
int n = cvFloor(idx*scale) - 1;
int r = idx - (n+1)*(numrho+2) - 1;
line.rho = (r - (numrho - 1)*0.5f) * rho;
line.angle = n * theta;
cvSeqPush( lines, &line );
}
func_exit:
cvFree( (void**)&tabSin );
cvFree( (void**)&tabCos );
cvFree( (void**)&accum );
return CV_OK;
}
/****************************************************************************************\
* Multi-Scale variant of Classical Hough Transform *
\****************************************************************************************/
#if defined _MSC_VER && _MSC_VER >= 1200
#pragma warning( disable: 4714 )
#endif
//DECLARE_AND_IMPLEMENT_LIST( _index, h_ );
IMPLEMENT_LIST( _index, h_ )
static CvStatus icvHoughLinesSDiv_8uC1R( uchar * image_src, int step, CvSize size,
float rho, float theta, int threshold,
int srn, int stn,
CvSeq* lines, int linesMax )
{
#define _POINT(row, column)\
(image_src[(row)*step+(column)])
int rn, tn; /* number of rho and theta discrete values */
uchar *mcaccum = 0;
uchar *caccum = 0;
uchar *buffer = 0;
float *sinTable = 0;
int *x = 0;
int *y = 0;
int index, i;
int ri, ti, ti1, ti0;
int row, col;
float r, t; /* Current rho and theta */
float rv; /* Some temporary rho value */
float irho;
float itheta;
float srho, stheta;
float isrho, istheta;
int w = size.width;
int h = size.height;
int fn = 0;
float xc, yc;
const float d2r = (float)(Pi / 180);
int sfn = srn * stn;
int fi;
int count;
int cmax = 0;
_CVLIST *list;
CVPOS pos;
_index *pindex;
_index vi;
if( image_src == NULL )
return CV_NULLPTR_ERR;
if( size.width < 0 || size.height < 0 )
return CV_BADSIZE_ERR;
if( linesMax == 0 || rho <= 0 || theta <= 0 )
return CV_BADFACTOR_ERR;
irho = 1 / rho;
itheta = 1 / theta;
srho = rho / srn;
stheta = theta / stn;
isrho = 1 / srho;
istheta = 1 / stheta;
rn = cvFloor( sqrt( (double)w * w + (double)h * h ) * irho );
tn = cvFloor( 2 * Pi * itheta );
list = h_create_list__index( linesMax < 1000 ? linesMax : 1000 );
vi.value = threshold;
vi.rho = -1;
h_add_head__index( list, &vi );
/* Precalculating sin */
sinTable = (float*)cvAlloc( 5 * tn * stn * sizeof( float ));
for( index = 0; index < 5 * tn * stn; index++ )
{
sinTable[index] = (float)cos( stheta * index * 0.2f );
}
/* Allocating memory for the accumulator ad initializing it */
if( threshold > 255 )
goto func_exit;
caccum = (uchar*)cvAlloc( rn * tn * sizeof( caccum[0] ));
memset( caccum, 0, rn * tn * sizeof( caccum[0] ));
/* Counting all feature pixels */
for( row = 0; row < h; row++ )
for( col = 0; col < w; col++ )
fn += _POINT( row, col ) != 0;
x = (int*)cvAlloc( fn * sizeof(x[0]));
y = (int*)cvAlloc( fn * sizeof(y[0]));
/* Full Hough Transform (it's accumulator update part) */
fi = 0;
if( threshold < 256 )
{
for( row = 0; row < h; row++ )
{
for( col = 0; col < w; col++ )
{
if( _POINT( row, col ))
{
int halftn;
float r0;
float scale_factor;
int iprev = -1;
float phi, phi1;
float theta_it; /* Value of theta for iterating */
/* Remember the feature point */
x[fi] = col;
y[fi] = row;
fi++;
yc = (float) row + 0.5f;
xc = (float) col + 0.5f;
/* Update the accumulator */
t = (float) fabs( cvFastArctan( yc, xc ) * d2r );
r = (float) sqrt( (double)xc * xc + (double)yc * yc );
r0 = r * irho;
ti0 = cvFloor( (t + Pi / 2) * itheta );
caccum[ti0]++;
theta_it = rho / r;
theta_it = theta_it < theta ? theta_it : theta;
scale_factor = theta_it * itheta;
halftn = cvFloor( Pi / theta_it );
for( ti1 = 1, phi = theta_it - halfPi, phi1 = (theta_it + t) * itheta;
ti1 < halftn; ti1++, phi += theta_it, phi1 += scale_factor )
{
rv = r0 * _cos( phi );
i = cvFloor( rv ) * tn;
i += cvFloor( phi1 );
assert( i >= 0 );
assert( i < rn * tn );
caccum[i] = (unsigned char) (caccum[i] + ((i ^ iprev) != 0));
iprev = i;
if( cmax < caccum[i] )
cmax = caccum[i];
}
}
}
}
}
else
{
cvClearSeq( lines );
goto func_exit;
}
/* Starting additional analysis */
count = 0;
for( ri = 0; ri < rn; ri++ )
{
for( ti = 0; ti < tn; ti++ )
{
if( caccum[ri * tn + ti > threshold] )
{
count++;
}
}
}
if( count * 100 > rn * tn )
{
icvHoughLines_8uC1R( image_src, step, size, rho, theta,
threshold, lines, linesMax );
goto func_exit;
}
buffer = (uchar *) cvAlloc( (srn * stn + 2) * sizeof( uchar ));
mcaccum = buffer + 1;
count = 0;
for( ri = 0; ri < rn; ri++ )
{
for( ti = 0; ti < tn; ti++ )
{
if( caccum[ri * tn + ti] > threshold )
{
count++;
memset( mcaccum, 0, sfn * sizeof( uchar ));
for( index = 0; index < fn; index++ )
{
int ti2;
float r0;
yc = (float) y[index] + 0.5f;
xc = (float) x[index] + 0.5f;
/* Update the accumulator */
t = (float) fabs( cvFastArctan( yc, xc ) * d2r );
r = (float) sqrt( (double)xc * xc + (double)yc * yc ) * isrho;
ti0 = cvFloor( (t + Pi * 0.5f) * istheta );
ti2 = (ti * stn - ti0) * 5;
r0 = (float) ri *srn;
for( ti1 = 0 /*, phi = ti*theta - Pi/2 - t */ ; ti1 < stn; ti1++, ti2 += 5
/*phi += stheta */ )
{
/*rv = r*_cos(phi) - r0; */
rv = r * sinTable[(int) (abs( ti2 ))] - r0;
i = cvFloor( rv ) * stn + ti1;
i = CV_IMAX( i, -1 );
i = CV_IMIN( i, sfn );
mcaccum[i]++;
assert( i >= -1 );
assert( i <= sfn );
}
}
/* Find peaks in maccum... */
for( index = 0; index < sfn; index++ )
{
i = 0;
pos = h_get_tail_pos__index( list );
if( h_get_prev__index( &pos )->value < mcaccum[index] )
{
vi.value = mcaccum[index];
vi.rho = index / stn * srho + ri * rho;
vi.theta = index % stn * stheta + ti * theta - halfPi;
while( h_is_pos__index( pos ))
{
if( h_get__index( pos )->value > mcaccum[index] )
{
h_insert_after__index( list, pos, &vi );
if( h_get_count__index( list ) > linesMax )
{
h_remove_tail__index( list );
}
break;
}
h_get_prev__index( &pos );
}
if( !h_is_pos__index( pos ))
{
h_add_head__index( list, &vi );
if( h_get_count__index( list ) > linesMax )
{
h_remove_tail__index( list );
}
}
}
}
}
}
}
pos = h_get_head_pos__index( list );
if( h_get_count__index( list ) == 1 )
{
if( h_get__index( pos )->rho < 0 )
{
h_clear_list__index( list );
}
}
else
{
while( h_is_pos__index( pos ))
{
CvLinePolar line;
pindex = h_get__index( pos );
if( pindex->rho < 0 )
{
/* This should be the last element... */
h_get_next__index( &pos );
assert( !h_is_pos__index( pos ));
break;
}
line.rho = pindex->rho;
line.angle = pindex->theta;
cvSeqPush( lines, &line );
if( lines->total >= linesMax )
goto func_exit;
h_get_next__index( &pos );
}
}
func_exit:
h_destroy_list__index( list );
cvFree( (void**)&sinTable );
cvFree( (void**)&x );
cvFree( (void**)&y );
cvFree( (void**)&caccum );
cvFree( (void**)&buffer );
return CV_OK;
}
/****************************************************************************************\
* Probabilistic Hough Transform *
\****************************************************************************************/
#define _PHOUGH_SIN_TABLE
static CvStatus icvHoughLinesP_8uC1R( uchar * image_src, int step, CvSize size,
float rho, float theta, int threshold,
int lineLength, int lineGap,
CvSeq *lines, int linesMax )
{
#define _POINT(row, column)\
(image_src[(row)*step+(column)])
int *map = 0;
int rn, tn; /* number of rho and theta discrete values */
#define ROUNDR(x) cvFloor(x)
#define ROUNDT(x) cvFloor(x)
#ifdef _PHOUGH_SIN_TABLE
#define SIN(a) sinTable[a]
#else
#define SIN(a) sin((a)*theta)
#endif
int *iaccum = 0;
uchar *caccum = 0;
int imaccum;
uchar cmaccum;
int *x = 0;
int *y = 0;
int index, i;
int ri, ri1, ti, ti1, ti0;
int halftn;
int row, col;
float r, t; /* Current rho and theta */
float rv; /* Some temporary rho value */
float irho;
float itheta;
int w = size.width;
int h = size.height;
int fn = 0;
float xc, yc;
const float d2r = (float)(Pi / 180);
int fpn = 0;
float *sinTable = 0;
CvRNG state = CvRNG(0xffffffff);
if( linesMax <= 0 )
return CV_BADSIZE_ERR;
if( rho <= 0 || theta <= 0 )
return CV_BADARG_ERR;
irho = 1 / rho;
itheta = 1 / theta;
rn = cvFloor( sqrt( (double)w * w + (double)h * h ) * irho );
tn = cvFloor( 2 * Pi * itheta );
halftn = cvFloor( Pi * itheta );
/* Allocating memory for the accumulator ad initializing it */
if( threshold > 255 )
{
iaccum = (int *) cvAlloc( rn * tn * sizeof( int ));
memset( iaccum, 0, rn * tn * sizeof( int ));
}
else
{
caccum = (uchar *) cvAlloc( rn * tn * sizeof( uchar ));
memset( caccum, 0, rn * tn * sizeof( uchar ));
}
/* Counting all feature pixels */
for( row = 0; row < h; row++ )
{
for( col = 0; col < w; col++ )
{
fn += !!_POINT( row, col );
}
}
x = (int *) cvAlloc( fn * sizeof( int ));
y = (int *) cvAlloc( fn * sizeof( int ));
map = (int *) cvAlloc( w * h * sizeof( int ));
memset( map, -1, w * h * sizeof( int ));
#ifdef _PHOUGH_SIN_TABLE
sinTable = (float *) cvAlloc( tn * sizeof( float ));
for( ti = 0; ti < tn; ti++ )
{
sinTable[ti] = (float)sin( (double)(ti * theta) );
}
#endif
index = 0;
for( row = 0; row < h; row++ )
{
for( col = 0; col < w; col++ )
{
if( _POINT( row, col ))
{
x[index] = col;
y[index] = row;
map[row * w + col] = index;
index++;
}
}
}
/* Starting Hough Transform */
while( fn != 0 )
{
int temp;
int index0;
int cl; /* Counter of length of lines of feature pixels */
int cg; /* Counter of gaps length in lines of feature pixels */
float dx = 1.0f, dy = 0.0f, ax, ay;
float msx = 0, msy = 0, mex = 0, mey = 0, mdx = 1.0f, mdy = 0.0f;
int ml;
/* The x, y and length of a line (remember the maximum length) */
float curx = 0, cury = 0;
int ox, oy; /* Rounded ax and ay */
int ex, ey;
#define _EXCHANGE(x1, x2) temp = x1;x1 = x2;x2 = temp
/* Select a pixel randomly */
index0 = cvRandInt(&state) % fn;
/* Remove the pixel from the feature points set */
if( index0 != fn - 1 )
{
/* Exchange the point with the last one */
_EXCHANGE( x[index0], x[fn - 1] );
_EXCHANGE( y[index0], y[fn - 1] );
_EXCHANGE( map[y[index0] * w + x[index0]], map[y[fn - 1] * w + x[fn - 1]] );
}
fn--;
fpn++;
yc = (float) y[fn] + 0.5f;
xc = (float) x[fn] + 0.5f;
/* Update the accumulator */
t = (float) fabs( cvFastArctan( yc, xc ) * d2r );
r = (float) sqrt( (double)xc * xc + (double)yc * yc );
ti0 = ROUNDT( t * itheta );
/* ti1 = 0 */
if( threshold > 255 )
{
rv = 0.0f;
ri1 = 0;
i = ti0;
iaccum[i]++;
imaccum = iaccum[i];
ri = ri1;
ti = ti0;
for( ti1 = 1; ti1 < halftn; ti1++ )
{
rv = r * SIN( ti1 );
ri1 = ROUNDR( rv * irho );
i = ri1 * tn + ti1 + ti0;
iaccum[i]++;
if( imaccum < iaccum[i] )
{
imaccum = iaccum[i];
ri = ri1;
ti = ti1 + ti0;
}
}
r = ri * rho + rho / 2;
t = ti * theta + theta / 2;
if( iaccum[ri * tn + ti] < threshold )
{
continue;
}
/* Unvote all the pixels from the detected line */
iaccum[ri * tn + ti] = 0;
}
else
{
rv = 0.0f;
ri1 = 0;
i = ti0;
caccum[i]++;
cmaccum = caccum[i];
ri = ri1;
ti = ti0;
for( ti1 = 1; ti1 < halftn; ti1++ )
{
rv = r * SIN( ti1 );
ri1 = ROUNDR( rv * irho );
i = ri1 * tn + ti1 + ti0;
caccum[i]++;
if( cmaccum < caccum[i] )
{
cmaccum = caccum[i];
ri = ri1;
ti = ti1 + ti0;
}
}
r = ri * rho + rho / 2;
t = ti * theta + theta / 2;
if( caccum[ri * tn + ti] < threshold )
{
continue;
}
/* Unvote all the pixels from the detected line */
caccum[ri * tn + ti] = 0;
}
/* Find a longest segment representing the line */
/* Use an algorithm like Bresenheim one */
ml = 0;
for( i = 0; i < 7; i++ )
{
switch (i)
{
case 0:
break;
case 1:
r = ri * rho;
t = ti * theta - halfPi + 0.1f * theta;
break;
case 2:
r = ri * rho;
t = (ti + 1) * theta - halfPi - 0.1f * theta;
break;
case 3:
r = (ri + 1) * rho - 0.1f * rho;
t = ti * theta - halfPi + 0.1f * theta;
break;
case 4:
r = (ri + 1) * rho - 0.1f * rho;
t = (ti + 1) * theta - halfPi - 0.1f * theta;
break;
case 5:
r = ri * rho + 0.1f * rho;
t = ti * theta - halfPi + 0.5f * theta;
break;
case 6:
r = (ri + 1) * rho - 0.1f * rho;
t = ti * theta - halfPi + 0.5f * theta;
break;
}
if( t > Pi )
{
t = t - 2 * Pi;
}
if( t >= 0 )
{
if( t <= Pi / 2 )
{
dx = -(float) sin( t );
dy = (float) cos( t );
if( r < (w - 1) * fabs( dy ))
{
ax = (float) cvFloor( r / dy ) + 0.5f;
ay = 0.5f;
}
else
{
ax = (float) w - 0.5f;
ay = (float) cvFloor( (r - (w - 1) * dy) / (float) fabs( dx )) + 0.5f;
}
}
else
{
/* Pi/2 < t < Pi */
dx = (float) sin( t );
dy = -(float) cos( t );
ax = 0.5f;
ay = (float) cvFloor( r / dx ) + 0.5f;
}
}
else
{
/* -Pi/2 < t < 0 */
dx = -(float) sin( t );
dy = (float) cos( t );
ax = (float) cvFloor( r / dy ) + 0.5f;
ay = 0.5f;
}
cl = 0;
cg = 0;
ox = cvFloor( ax );
oy = cvFloor( ay );
while( ox >= 0 && ox < w && oy >= 0 && oy < h )
{
if( _POINT( oy, ox ))
{
if( cl == 0 )
{
/* A line has started */
curx = ax;
cury = ay;
}
cl++;
cg = 0; /* No gaps so far */
}
else if( cl )
{
if( ++cg > lineGap )
{
/* This is not a gap, the line has finished */
/* Let us remember it's parameters */
if( ml < cl )
{
msx = curx;
msy = cury;
mex = ax;
mey = ay;
mdx = dx;
mdy = dy;
ml = cl;
}
cl = 0;
cg = 0;
}
}
ax += dx;
ay += dy;
ox = cvFloor( ax );
oy = cvFloor( ay );
}
/* The last line if there was any... */
if( ml < cl )
{
msx = curx;
msy = cury;
mex = ax;
mey = ay;
mdx = dx;
mdy = dy;
ml = cl;
}
}
if( ml == 0 )
{
// no line...
continue;
}
/* Now let's remove all the pixels in the segment from the input image */
cl = 0;
cg = 0;
ax = msx;
ay = msy;
ox = cvFloor( msx );
oy = cvFloor( msy );
ex = cvFloor( mex );
ey = cvFloor( mey );
while( (ox != ex || oy != ey) && fn > 0 )
{
if( (unsigned)ox >= (unsigned)w || (unsigned)oy >= (unsigned)h )
break;
{
image_src[oy * step + ox] = 0;
index0 = map[oy * w + ox];
if( index0 != -1 )
{
if( index0 != fn - 1 )
{
/* Exchange the point with the last one */
_EXCHANGE( x[index0], x[fn - 1] );
_EXCHANGE( y[index0], y[fn - 1] );
_EXCHANGE( map[y[index0] * w + x[index0]],
map[y[fn - 1] * w + x[fn - 1]] );
}
fn--;
}
}
ax += mdx;
ay += mdy;
ox = cvFloor( ax );
oy = cvFloor( ay );
}
if( ml >= lineLength )
{
CvRect line;
line.x = cvFloor( msx );
line.y = cvFloor( msy );
line.width = cvFloor( mex );
line.height = cvFloor( mey );
cvSeqPush( lines, &line );
if( lines->total >= linesMax || fn == 0 )
goto func_exit;
}
}
func_exit:
cvFree( (void**)&x );
cvFree( (void**)&y );
cvFree( (void**)&map );
cvFree( (void**)&sinTable );
cvFree( (void**)&iaccum );
cvFree( (void**)&caccum );
return CV_OK;
}
/* Wrapper function for standard hough transform */
CV_IMPL CvSeq*
cvHoughLines2( CvArr* src_image, void* lineStorage, int method,
double rho, double theta, int threshold,
double param1, double param2 )
{
CvSeq* result = 0;
CV_FUNCNAME( "cvHoughLines" );
__BEGIN__;
CvMat stub, *img = (CvMat*)src_image;
CvMat* mat = 0;
CvSeq* lines = 0;
CvSeq lines_header;
CvSeqBlock lines_block;
int lineType, elemSize;
int linesMax = INT_MAX;
CvSize size;
int iparam1, iparam2;
CV_CALL( img = cvGetMat( img, &stub ));
if( !CV_IS_MASK_ARR(img))
CV_ERROR( CV_StsBadArg, "The source image must be 8-bit, single-channel" );
if( !lineStorage )
CV_ERROR( CV_StsNullPtr, "NULL destination" );
if( rho <= 0 || theta <= 0 || threshold <= 0 )
CV_ERROR( CV_StsOutOfRange, "rho, theta and threshold must be positive" );
if( method != CV_HOUGH_PROBABILISTIC )
{
lineType = CV_32FC2;
elemSize = sizeof(float)*2;
}
else
{
lineType = CV_32SC4;
elemSize = sizeof(int)*4;
}
if( CV_IS_STORAGE( lineStorage ))
{
CV_CALL( lines = cvCreateSeq( lineType, sizeof(CvSeq), elemSize, (CvMemStorage*)lineStorage ));
}
else if( CV_IS_MAT( lineStorage ))
{
mat = (CvMat*)lineStorage;
if( !CV_IS_MAT_CONT( mat->type ) || mat->rows != 1 && mat->cols != 1 )
CV_ERROR( CV_StsBadArg,
"The destination matrix should be continuous and have a single row or a single column" );
if( CV_MAT_TYPE( mat->type ) != lineType )
CV_ERROR( CV_StsBadArg,
"The destination matrix data type is inappropriate, see the manual" );
CV_CALL( lines = cvMakeSeqHeaderForArray( lineType, sizeof(CvSeq), elemSize, mat->data.ptr,
mat->rows + mat->cols - 1, &lines_header, &lines_block ));
linesMax = lines->total;
CV_CALL( cvClearSeq( lines ));
}
else
{
CV_ERROR( CV_StsBadArg, "Destination is not CvMemStorage* nor CvMat*" );
}
size = cvGetMatSize(img);
iparam1 = cvRound(param1);
iparam2 = cvRound(param2);
switch( method )
{
case CV_HOUGH_STANDARD:
IPPI_CALL( icvHoughLines_8uC1R( img->data.ptr, img->step, size, (float)rho,
(float)theta, threshold, lines, linesMax ));
break;
case CV_HOUGH_MULTI_SCALE:
IPPI_CALL( icvHoughLinesSDiv_8uC1R( img->data.ptr, img->step, size, (float)rho,
(float)theta, threshold, iparam1,
iparam2, lines, linesMax ));
break;
case CV_HOUGH_PROBABILISTIC:
IPPI_CALL( icvHoughLinesP_8uC1R( img->data.ptr, img->step, size, (float)rho,
(float)theta, threshold, iparam1,
iparam2, lines, linesMax ));
break;
default:
CV_ERROR( CV_StsBadArg, "Unrecognized method id" );
}
if( mat )
{
if( mat->cols > mat->rows )
mat->cols = lines->total;
else
mat->rows = lines->total;
}
else
{
result = lines;
}
__END__;
return result;
}
/****************************************************************************************\
* Circle Detection *
\****************************************************************************************/
static void
icvHoughCirclesGradient( CvMat* img, float dp, float min_dist,
int canny_threshold, int acc_threshold,
CvSeq* circles, int circles_max )
{
const int SHIFT = 10, ONE = 1 << SHIFT, R_THRESH = 30;
CvMat *dx = 0, *dy = 0;
CvMat *edges = 0;
CvMat *accum = 0;
int* sort_buf = 0;
CvMat* dist_buf = 0;
CvMemStorage* storage = 0;
CV_FUNCNAME( "icvHoughCirclesGradient" );
__BEGIN__;
int x, y, i, j, center_count, nz_count;
int rows, cols, arows, acols;
int astep, *adata;
float* ddata;
CvSize asize;
CvSeq *nz, *centers;
float idp, dr;
CvSeqReader reader;
CV_CALL( edges = cvCreateMat( img->rows, img->cols, CV_8UC1 ));
CV_CALL( cvCanny( img, edges, MAX(canny_threshold/2,1), canny_threshold, 3 ));
CV_CALL( dx = cvCreateMat( img->rows, img->cols, CV_16SC1 ));
CV_CALL( dy = cvCreateMat( img->rows, img->cols, CV_16SC1 ));
CV_CALL( cvSobel( img, dx, 1, 0, 3 ));
CV_CALL( cvSobel( img, dy, 0, 1, 3 ));
if( dp < 1.f )
dp = 1.f;
idp = 1.f/dp;
CV_CALL( accum = cvCreateMat( cvCeil(img->rows*idp)+2, cvCeil(img->cols*idp)+2, CV_32SC1 ));
CV_CALL( cvZero(accum));
asize = cvGetMatSize(accum);
CV_CALL( storage = cvCreateMemStorage() );
CV_CALL( nz = cvCreateSeq( CV_32SC2, sizeof(CvSeq), sizeof(CvPoint), storage ));
CV_CALL( centers = cvCreateSeq( CV_32SC1, sizeof(CvSeq), sizeof(int), storage ));
rows = img->rows;
cols = img->cols;
arows = accum->rows - 2;
acols = accum->cols - 2;
adata = accum->data.i;
astep = accum->step/sizeof(adata[0]);
for( y = 0; y < rows; y++ )
{
const uchar* edges_row = edges->data.ptr + y*edges->step;
const short* dx_row = (const short*)(dx->data.ptr + y*dx->step);
const short* dy_row = (const short*)(dy->data.ptr + y*dy->step);
for( x = 0; x < cols; x++ )
{
float vx, vy;
int sx, sy, x0, y0, x1, y1;
CvPoint pt;
vx = dx_row[x];
vy = dy_row[x];
if( !edges_row[x] || vx == 0 && vy == 0 )
continue;
if( fabs(vx) < fabs(vy) )
{
sx = cvRound(vx*ONE/fabs(vy));
sy = vy < 0 ? -ONE : ONE;
}
else
{
assert( vx != 0 );
sy = cvRound(vy*ONE/fabs(vx));
sx = vx < 0 ? -ONE : ONE;
}
x0 = cvRound((x*idp)*ONE) + ONE + (ONE/2);
y0 = cvRound((y*idp)*ONE) + ONE + (ONE/2);
for( x1 = x0, y1 = y0;; x1 += sx, y1 += sy )
{
int x2 = x1 >> SHIFT, y2 = y1 >> SHIFT;
if( (unsigned)x2 >= (unsigned)acols ||
(unsigned)y2 >= (unsigned)arows )
break;
adata[y2*astep + x2]++;
}
sx = -sx; sy = -sy;
for( x1 = x0 + sx, y1 = y0 + sy;; x1 += sx, y1 += sy )
{
int x2 = x1 >> SHIFT, y2 = y1 >> SHIFT;
if( (unsigned)x2 >= (unsigned)acols ||
(unsigned)y2 >= (unsigned)arows )
break;
adata[y2*astep + x2]++;
}
pt.x = x; pt.y = y;
cvSeqPush( nz, &pt );
}
}
nz_count = nz->total;
if( !nz_count )
EXIT;
for( y = 1; y < arows - 1; y++ )
{
for( x = 1; x < acols - 1; x++ )
{
int base = y*(acols+2) + x;
if( adata[base] > acc_threshold &&
adata[base] > adata[base-1] && adata[base] > adata[base+1] &&
adata[base] > adata[base-acols-2] && adata[base] > adata[base+acols+2] )
cvSeqPush(centers, &base);
}
}
center_count = centers->total;
if( !center_count )
EXIT;
CV_CALL( sort_buf = (int*)cvAlloc( MAX(center_count,nz_count)*sizeof(sort_buf[0]) ));
cvCvtSeqToArray( centers, sort_buf );
icvHoughSortDescent32s( sort_buf, center_count, adata );
cvClearSeq( centers );
cvSeqPushMulti( centers, sort_buf, center_count );
CV_CALL( dist_buf = cvCreateMat( 1, nz_count, CV_32FC1 ));
ddata = dist_buf->data.fl;
dr = dp;
min_dist = MAX( min_dist, dp );
min_dist *= min_dist;
for( i = 0; i < centers->total; i++ )
{
int ofs = *(int*)cvGetSeqElem( centers, i );
y = ofs/(acols+2) - 1;
x = ofs - (y+1)*(acols+2) - 1;
float cx = (float)(x*dp), cy = (float)(y*dp);
int start_idx = nz_count - 1;
float start_dist, prev_dist, dist_sum;
float r_best = 0, c[3];
int max_count = R_THRESH;
for( j = 0; j < circles->total; j++ )
{
float* c = (float*)cvGetSeqElem( circles, j );
if( (c[0] - cx)*(c[0] - cx) + (c[1] - cy)*(c[1] - cy) < min_dist )
break;
}
if( j < circles->total )
continue;
cvStartReadSeq( nz, &reader );
for( j = 0; j < nz_count; j++ )
{
CvPoint pt;
float _dx, _dy;
CV_READ_SEQ_ELEM( pt, reader );
_dx = cx - pt.x; _dy = cy - pt.y;
ddata[j] = _dx*_dx + _dy*_dy;
sort_buf[j] = j;
}
cvPow( dist_buf, dist_buf, 0.5 );
icvHoughSortDescent32s( sort_buf, nz_count, (int*)ddata );
dist_sum = prev_dist = start_dist = ddata[sort_buf[nz_count-1]];
for( j = nz_count - 2; j >= 0; j-- )
{
float d = ddata[sort_buf[j]];
if( d - start_dist > dr )
{
if( start_idx - j >= max_count )
{
r_best = ddata[sort_buf[(j + start_idx)/2]];
max_count = start_idx - j;
}
start_dist = d;
start_idx = j;
dist_sum = 0;
}
dist_sum += d;
prev_dist = d;
}
if( max_count > R_THRESH )
{
c[0] = cx;
c[1] = cy;
c[2] = (float)r_best;
cvSeqPush( circles, c );
if( circles->total > circles_max )
EXIT;
}
}
__END__;
cvReleaseMat( &dist_buf );
cvFree( (void**)&sort_buf );
cvReleaseMemStorage( &storage );
cvReleaseMat( &edges );
cvReleaseMat( &dx );
cvReleaseMat( &dy );
cvReleaseMat( &accum );
}
CV_IMPL CvSeq*
cvHoughCircles( CvArr* src_image, void* circle_storage,
int method, double dp, double min_dist,
double param1, double param2 )
{
CvSeq* result = 0;
CV_FUNCNAME( "cvHoughCircles" );
__BEGIN__;
CvMat stub, *img = (CvMat*)src_image;
CvMat* mat = 0;
CvSeq* circles = 0;
CvSeq circles_header;
CvSeqBlock circles_block;
int circles_max = INT_MAX;
int canny_threshold = cvRound(param1);
int acc_threshold = cvRound(param2);
CvSize size;
CV_CALL( img = cvGetMat( img, &stub ));
if( !CV_IS_MASK_ARR(img))
CV_ERROR( CV_StsBadArg, "The source image must be 8-bit, single-channel" );
if( !circle_storage )
CV_ERROR( CV_StsNullPtr, "NULL destination" );
if( dp <= 0 || min_dist <= 0 || canny_threshold <= 0 || acc_threshold <= 0 )
CV_ERROR( CV_StsOutOfRange, "dp, min_dist, canny_threshold and acc_threshold must be all positive numbers" );
if( CV_IS_STORAGE( circle_storage ))
{
CV_CALL( circles = cvCreateSeq( CV_32FC3, sizeof(CvSeq),
sizeof(float)*3, (CvMemStorage*)circle_storage ));
}
else if( CV_IS_MAT( circle_storage ))
{
mat = (CvMat*)circle_storage;
if( !CV_IS_MAT_CONT( mat->type ) || mat->rows != 1 && mat->cols != 1 ||
CV_MAT_TYPE(mat->type) != CV_32FC3 )
CV_ERROR( CV_StsBadArg,
"The destination matrix should be continuous and have a single row or a single column" );
CV_CALL( circles = cvMakeSeqHeaderForArray( CV_32FC3, sizeof(CvSeq), sizeof(float)*3,
mat->data.ptr, mat->rows + mat->cols - 1, &circles_header, &circles_block ));
circles_max = circles->total;
CV_CALL( cvClearSeq( circles ));
}
else
{
CV_ERROR( CV_StsBadArg, "Destination is not CvMemStorage* nor CvMat*" );
}
size = cvGetMatSize(img);
switch( method )
{
case CV_HOUGH_GRADIENT:
CV_CALL( icvHoughCirclesGradient( img, (float)dp, (float)min_dist,
canny_threshold, acc_threshold, circles, circles_max ));
break;
default:
CV_ERROR( CV_StsBadArg, "Unrecognized method id" );
}
if( mat )
{
if( mat->cols > mat->rows )
mat->cols = circles->total;
else
mat->rows = circles->total;
}
else
result = circles;
__END__;
return result;
}
/* End of file. */
| [
"[email protected]"
]
| [
[
[
1,
1351
]
]
]
|
c2ed110ea367fecc3eb5545673c0ca4f645c7539 | 740ed7e8d98fc0af56ee8e0832e3bd28f08cf362 | /src/game/megaman_demo/ScreenUI.cpp | 1295524759c7f53b83fe3205d24a6c9067c14769 | []
| no_license | fgervais/armconsoledemogame | 420c53f926728b30fe1723733de2f32961a6a6d9 | 9158c0e684db16c4327b51aec45d1e4eed96b2d4 | refs/heads/master | 2021-01-10T11:27:43.912609 | 2010-07-29T18:53:06 | 2010-07-29T18:53:06 | 44,270,121 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,391 | cpp | /*
* Megaman.cpp
*
* Created on: Mar 8, 2010
* Author: fgervais
*/
#include "ScreenUI.h"
#include "Environment.h"
#include "ScreenUIState.h"
#include "VisibleArea.h"
#include <iostream>
using namespace std;
//#include "LPC2478.h"
ScreenUI::ScreenUI(ScreenUIState* initialState, Environment* environment) : Sprite(initialState, environment) {
// Keep a pointer to the initial state in case we need to re-spawn the sprite
//this->initialState = initialState;
this->currentState = initialState;
// Unsafe?
this->currentState->initialize(this);
}
ScreenUI::~ScreenUI() {
}
void ScreenUI::setState(ScreenUIState* state) {
this->currentState = state;
// Do state entry initialization on the sprite
state->initialize(this);
// Send state to the superclass
Sprite::setState(state);
}
void ScreenUI::update() {
VisibleArea* visibleArea = environment->getVisibleArea();
environment->move(this, visibleArea->x+getOffsetX(), visibleArea->y+getOffsetY());
cout << this->getPositionX() << " " << this->getPositionY() << endl;
// Update the currently displayed frame
// And possibly some state specific things
currentState->update(this);
}
void ScreenUI::linkTo(Sprite* sprite) {
linkedSprite = sprite;
}
void ScreenUI::show() {
this->isHidden = 0;
}
void ScreenUI::hide() {
this->isHidden = 1;
}
| [
"fournierseb2@051cbfc0-75b8-dce1-6088-688cefeb9347"
]
| [
[
[
1,
62
]
]
]
|
326b7c438b25ef03689d6692f3964f120240f320 | 7476d2c710c9a48373ce77f8e0113cb6fcc4c93b | /RakNet/CCRakNetUDT.h | ac2a2740b392a9d4e8152ceeace14fcedb76f76b | []
| no_license | CmaThomas/Vault-Tec-Multiplayer-Mod | af23777ef39237df28545ee82aa852d687c75bc9 | 5c1294dad16edd00f796635edaf5348227c33933 | refs/heads/master | 2021-01-16T21:13:29.029937 | 2011-10-30T21:58:41 | 2011-10-30T22:00:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,005 | h | #include "RakNetDefines.h"
#if USE_SLIDING_WINDOW_CONGESTION_CONTROL!=1
#ifndef __CONGESTION_CONTROL_UDT_H
#define __CONGESTION_CONTROL_UDT_H
#include "NativeTypes.h"
#include "RakNetTime.h"
#include "RakNetTypes.h"
#include "DS_Queue.h"
/// Set to 4 if you are using the iPod Touch TG. See http://www.jenkinssoftware.com/forum/index.php?topic=2717.0
#define CC_TIME_TYPE_BYTES 8
namespace RakNet
{
typedef uint64_t CCTimeType;
typedef uint24_t DatagramSequenceNumberType;
typedef double BytesPerMicrosecond;
typedef double BytesPerSecond;
typedef double MicrosecondsPerByte;
/// CC_RAKNET_UDT_PACKET_HISTORY_LENGTH should be a power of 2 for the writeIndex variables to wrap properly
#define CC_RAKNET_UDT_PACKET_HISTORY_LENGTH 64
#define RTT_HISTORY_LENGTH 64
/// Sizeof an UDP header in byte
#define UDP_HEADER_SIZE 28
#define CC_DEBUG_PRINTF_1(x)
#define CC_DEBUG_PRINTF_2(x,y)
#define CC_DEBUG_PRINTF_3(x,y,z)
#define CC_DEBUG_PRINTF_4(x,y,z,a)
#define CC_DEBUG_PRINTF_5(x,y,z,a,b)
//#define CC_DEBUG_PRINTF_1(x) printf(x)
//#define CC_DEBUG_PRINTF_2(x,y) printf(x,y)
//#define CC_DEBUG_PRINTF_3(x,y,z) printf(x,y,z)
//#define CC_DEBUG_PRINTF_4(x,y,z,a) printf(x,y,z,a)
//#define CC_DEBUG_PRINTF_5(x,y,z,a,b) printf(x,y,z,a,b)
/// \brief Encapsulates UDT congestion control, as used by RakNet
/// Requirements:
/// <OL>
/// <LI>Each datagram is no more than MAXIMUM_MTU_SIZE, after accounting for the UDP header
/// <LI>Each datagram containing a user message has a sequence number which is set after calling OnSendBytes(). Set it by calling GetAndIncrementNextDatagramSequenceNumber()
/// <LI>System is designed to be used from a single thread.
/// <LI>Each packet should have a timeout time based on GetSenderRTOForACK(). If this time elapses, add the packet to the head of the send list for retransmission.
/// </OL>
///
/// Recommended:
/// <OL>
/// <LI>Call sendto in its own thread. This takes a significant amount of time in high speed networks.
/// </OL>
///
/// Algorithm:
/// <OL>
/// <LI>On a new connection, call Init()
/// <LI>On a periodic interval (SYN time is the best) call Update(). Also call ShouldSendACKs(), and send buffered ACKS if it returns true.
/// <LI>Call OnSendAck() when sending acks.
/// <LI>When you want to send or resend data, call GetNumberOfBytesToSend(). It will return you enough bytes to keep you busy for \a estimatedTimeToNextTick. You can send more than this to fill out a datagram, or to send packet pairs
/// <LI>Call OnSendBytes() when sending datagrams.
/// <LI>When data arrives, record the sequence number and buffer an ACK for it, to be sent from Update() if ShouldSendACKs() returns true
/// <LI>Every 16 packets that you send, send two of them back to back (a packet pair) as long as both packets are the same size. If you don't have two packets the same size, it is fine to defer this until you do.
/// <LI>When you get a packet, call OnGotPacket(). If the packet is also either of a packet pair, call OnGotPacketPair()
/// <LI>If you get a packet, and the sequence number is not 1 + the last sequence number, send a NAK. On the remote system, call OnNAK() and resend that message.
/// <LI>If you get an ACK, remove that message from retransmission. Call OnNonDuplicateAck().
/// <LI>If a message is not ACKed for GetRTOForRetransmission(), resend it.
/// </OL>
class CCRakNetUDT
{
public:
CCRakNetUDT();
~CCRakNetUDT();
/// Reset all variables to their initial states, for a new connection
void Init(CCTimeType curTime, uint32_t maxDatagramPayload);
/// Update over time
void Update(CCTimeType curTime, bool hasDataToSendOrResend);
int GetRetransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend);
int GetTransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend);
/// Acks do not have to be sent immediately. Instead, they can be buffered up such that groups of acks are sent at a time
/// This reduces overall bandwidth usage
/// How long they can be buffered depends on the retransmit time of the sender
/// Should call once per update tick, and send if needed
bool ShouldSendACKs(CCTimeType curTime, CCTimeType estimatedTimeToNextTick);
/// Every data packet sent must contain a sequence number
/// Call this function to get it. The sequence number is passed into OnGotPacketPair()
DatagramSequenceNumberType GetAndIncrementNextDatagramSequenceNumber(void);
DatagramSequenceNumberType GetNextDatagramSequenceNumber(void);
/// Call this when you send packets
/// Every 15th and 16th packets should be sent as a packet pair if possible
/// When packets marked as a packet pair arrive, pass to OnGotPacketPair()
/// When any packets arrive, (additionally) pass to OnGotPacket
/// Packets should contain our system time, so we can pass rtt to OnNonDuplicateAck()
void OnSendBytes(CCTimeType curTime, uint32_t numBytes);
/// Call this when you get a packet pair
void OnGotPacketPair(DatagramSequenceNumberType datagramSequenceNumber, uint32_t sizeInBytes, CCTimeType curTime);
/// Call this when you get a packet (including packet pairs)
/// If the DatagramSequenceNumberType is out of order, skippedMessageCount will be non-zero
/// In that case, send a NAK for every sequence number up to that count
bool OnGotPacket(DatagramSequenceNumberType datagramSequenceNumber, bool isContinuousSend, CCTimeType curTime, uint32_t sizeInBytes, uint32_t *skippedMessageCount);
/// Call when you get a NAK, with the sequence number of the lost message
/// Affects the congestion control
void OnResend(CCTimeType curTime);
void OnNAK(CCTimeType curTime, DatagramSequenceNumberType nakSequenceNumber);
/// Call this when an ACK arrives.
/// hasBAndAS are possibly written with the ack, see OnSendAck()
/// B and AS are used in the calculations in UpdateWindowSizeAndAckOnAckPerSyn
/// B and AS are updated at most once per SYN
void OnAck(CCTimeType curTime, CCTimeType rtt, bool hasBAndAS, BytesPerMicrosecond _B, BytesPerMicrosecond _AS, double totalUserDataBytesAcked, bool isContinuousSend, DatagramSequenceNumberType sequenceNumber );
void OnDuplicateAck( CCTimeType curTime, DatagramSequenceNumberType sequenceNumber ) {}
/// Call when you send an ack, to see if the ack should have the B and AS parameters transmitted
/// Call before calling OnSendAck()
void OnSendAckGetBAndAS(CCTimeType curTime, bool *hasBAndAS, BytesPerMicrosecond *_B, BytesPerMicrosecond *_AS);
/// Call when we send an ack, to write B and AS if needed
/// B and AS are only written once per SYN, to prevent slow calculations
/// Also updates SND, the period between sends, since data is written out
/// Be sure to call OnSendAckGetBAndAS() before calling OnSendAck(), since whether you write it or not affects \a numBytes
void OnSendAck(CCTimeType curTime, uint32_t numBytes);
/// Call when we send a NACK
/// Also updates SND, the period between sends, since data is written out
void OnSendNACK(CCTimeType curTime, uint32_t numBytes);
/// Retransmission time out for the sender
/// If the time difference between when a message was last transmitted, and the current time is greater than RTO then packet is eligible for retransmission, pending congestion control
/// RTO = (RTT + 4 * RTTVar) + SYN
/// If we have been continuously sending for the last RTO, and no ACK or NAK at all, SND*=2;
/// This is per message, which is different from UDT, but RakNet supports packetloss with continuing data where UDT is only RELIABLE_ORDERED
/// Minimum value is 100 milliseconds
CCTimeType GetRTOForRetransmission(void) const;
/// Set the maximum amount of data that can be sent in one datagram
/// Default to MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE
void SetMTU(uint32_t bytes);
/// Return what was set by SetMTU()
uint32_t GetMTU(void) const;
/// Query for statistics
BytesPerMicrosecond GetLocalSendRate(void) const {return 1.0 / SND;}
BytesPerMicrosecond GetLocalReceiveRate(CCTimeType currentTime) const;
BytesPerMicrosecond GetRemoveReceiveRate(void) const {return AS;}
//BytesPerMicrosecond GetEstimatedBandwidth(void) const {return B;}
BytesPerMicrosecond GetEstimatedBandwidth(void) const {return GetLinkCapacityBytesPerSecond()*1000000.0;}
double GetLinkCapacityBytesPerSecond(void) const {return estimatedLinkCapacityBytesPerSecond;};
/// Query for statistics
double GetRTT(void) const;
bool GetIsInSlowStart(void) const {return isInSlowStart;}
uint32_t GetCWNDLimit(void) const {return (uint32_t) (CWND*MAXIMUM_MTU_INCLUDING_UDP_HEADER);}
/// Is a > b, accounting for variable overflow?
static bool GreaterThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b);
/// Is a < b, accounting for variable overflow?
static bool LessThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b);
// void SetTimeBetweenSendsLimit(unsigned int bitsPerSecond);
uint64_t GetBytesPerSecondLimitByCongestionControl(void) const;
void OnExternalPing(double pingMS) {(void) ping;}
protected:
// --------------------------- PROTECTED VARIABLES ---------------------------
/// time interval between bytes, in microseconds.
/// Only used when slowStart==false
/// Increased over time as we continually get messages
/// Decreased on NAK and timeout
/// Starts at 0 (invalid)
MicrosecondsPerByte SND;
/// Supportive window mechanism, controlling the maximum number of in-flight packets
/// Used both during and after slow-start, but primarily during slow-start
/// Starts at 2, which is also the low threshhold
/// Max is the socket receive buffer / MTU
/// CWND = AS * (RTT + SYN) + 16
double CWND;
/// When we do an update process on the SYN interval, nextSYNUpdate is set to the next time we should update
/// Normally this is nextSYNUpdate+=SYN, in order to update on a consistent schedule
/// However, if this would result in an immediate update yet again, it is set to SYN microseconds past the current time (in case the thread did not update for a long time)
CCTimeType nextSYNUpdate;
/// Index into packetPairRecieptHistory where we will next write
/// The history is always full (starting with default values) so no read index is needed
int packetPairRecieptHistoryWriteIndex;
/// Sent to the sender by the receiver from packetPairRecieptHistory whenever a back to back packet arrives on the receiver
/// Updated by B = B * .875 + incomingB * .125
//BytesPerMicrosecond B;
/// Running round trip time (ping*2)
/// Only sender needs to know this
/// Initialized to UNSET
/// Set to rtt on first calculation
/// Updated gradually by RTT = RTT * 0.875 + rtt * 0.125
double RTT;
/// Round trip time variance
/// Only sender needs to know this
/// Initialized to UNSET
/// Set to rtt on first calculation
// double RTTVar;
/// Update: Use min/max, RTTVar follows current variance too closely resulting in packetloss
double minRTT, maxRTT;
/// Used to calculate packet arrival rate (in UDT) but data arrival rate (in RakNet, where not all datagrams are the same size)
/// Filter is used to cull lowest half of values for bytesPerMicrosecond, to discount spikes and inactivity
/// Referred to in the documentation as AS, data arrival rate
/// AS is sent to the sender and calculated every 10th ack
/// Each node represents (curTime-lastPacketArrivalTime)/bytes
/// Used with ReceiverCalculateDataArrivalRate();
BytesPerMicrosecond packetArrivalHistory[CC_RAKNET_UDT_PACKET_HISTORY_LENGTH];
BytesPerMicrosecond packetArrivalHistoryContinuousGaps[CC_RAKNET_UDT_PACKET_HISTORY_LENGTH];
unsigned char packetArrivalHistoryContinuousGapsIndex;
uint64_t continuousBytesReceived;
CCTimeType continuousBytesReceivedStartTime;
unsigned int packetArrivalHistoryWriteCount;
/// Index into packetArrivalHistory where we will next write
/// The history is always full (starting with default values) so no read index is needed
int packetArrivalHistoryWriteIndex;
/// Tracks the time the last packet that arrived, so BytesPerMicrosecond can be calculated for packetArrivalHistory when a new packet arrives
CCTimeType lastPacketArrivalTime;
/// Data arrival rate from the sender to the receiver, as told to us by the receiver
/// Used to calculate initial sending rate when slow start stops
BytesPerMicrosecond AS;
/// When the receiver last calculated and send B and AS, from packetArrivalHistory and packetPairRecieptHistory
/// Used to prevent it from being calculated and send too frequently, as they are slow operations
CCTimeType lastTransmitOfBAndAS;
/// New connections start in slow start
/// During slow start, SND is not used, only CWND
/// Slow start ends when we get a NAK, or the maximum size of CWND is reached
/// SND is initialized to the inverse of the receiver's packet arrival rate when slow start ends
bool isInSlowStart;
/// How many NAKs arrived this congestion period
/// Initialized to 1 when the congestion period starts
uint32_t NAKCount;
/// How many NAKs do you get on average during a congestion period?
/// Starts at 1
/// Used to generate a random number, DecRandom, between 1 and AvgNAKNum
uint32_t AvgNAKNum;
/// How many times we have decremented SND this congestion period. Used to limit the number of decrements to 5
uint32_t DecCount;
/// Every DecInterval NAKs per congestion period, we decrease the send rate
uint32_t DecInterval;
/// Every outgoing datagram is assigned a sequence number, which increments by 1 every assignment
DatagramSequenceNumberType nextDatagramSequenceNumber;
/// If a packet is marked as a packet pair, lastPacketPairPacketArrivalTime is set to the time it arrives
/// This is used so when the 2nd packet of the pair arrives, we can calculate the time interval between the two
CCTimeType lastPacketPairPacketArrivalTime;
/// If a packet is marked as a packet pair, lastPacketPairSequenceNumber is checked to see if the last packet we got
/// was the packet immediately before the one that arrived
/// If so, we can use lastPacketPairPacketArrivalTime to get the time between the two packets, and thus estimate the link capacity
/// Initialized to -1, so the first packet of a packet pair won't be treated as the second
DatagramSequenceNumberType lastPacketPairSequenceNumber;
/// Used to cap UpdateWindowSizeAndAckOnAckPerSyn() to once speed increase per SYN
/// This is to prevent speeding up faster than congestion control can compensate for
CCTimeType lastUpdateWindowSizeAndAck;
/// Every time SND is halved due to timeout, the RTO is increased
/// This is to prevent massive retransmissions to an unresponsive system
/// Reset on any data arriving
double ExpCount;
/// Total number of user data bytes sent
/// Used to adjust the window size, on ACK, during slow start
uint64_t totalUserDataBytesSent;
/// When we get an ack, if oldestUnsentAck==0, set it to the current time
/// When we send out acks, set oldestUnsentAck to 0
CCTimeType oldestUnsentAck;
// Maximum amount of bytes that the user can send, e.g. the size of one full datagram
uint32_t MAXIMUM_MTU_INCLUDING_UDP_HEADER;
// Max window size
double CWND_MAX_THRESHOLD;
/// Track which datagram sequence numbers have arrived.
/// If a sequence number is skipped, send a NAK for all skipped messages
DatagramSequenceNumberType expectedNextSequenceNumber;
// How many times have we sent B and AS? Used to force it to send at least CC_RAKNET_UDT_PACKET_HISTORY_LENGTH times
// Otherwise, the default values in the array generate inaccuracy
uint32_t sendBAndASCount;
/// Most recent values read into the corresponding lists
/// Used during the beginning of a connection, when the median filter is still inaccurate
BytesPerMicrosecond mostRecentPacketArrivalHistory;
bool hasWrittenToPacketPairReceiptHistory;
// uint32_t rttHistory[RTT_HISTORY_LENGTH];
// uint32_t rttHistoryIndex;
// uint32_t rttHistoryWriteCount;
// uint32_t rttSum, rttLow;
// CCTimeType lastSndUpdateTime;
double estimatedLinkCapacityBytesPerSecond;
// --------------------------- PROTECTED METHODS ---------------------------
/// Update nextSYNUpdate by SYN, or the same amount past the current time if no updates have occurred for a long time
void SetNextSYNUpdate(CCTimeType currentTime);
/// Returns the rate of data arrival, based on packets arriving on the sender.
BytesPerMicrosecond ReceiverCalculateDataArrivalRate(CCTimeType curTime) const;
/// Returns the median of the data arrival rate
BytesPerMicrosecond ReceiverCalculateDataArrivalRateMedian(void) const;
/// Calculates the median an array of BytesPerMicrosecond
static BytesPerMicrosecond CalculateListMedianRecursive(const BytesPerMicrosecond inputList[CC_RAKNET_UDT_PACKET_HISTORY_LENGTH], int inputListLength, int lessThanSum, int greaterThanSum);
// static uint32_t CalculateListMedianRecursive(const uint32_t inputList[RTT_HISTORY_LENGTH], int inputListLength, int lessThanSum, int greaterThanSum);
/// Same as GetRTOForRetransmission, but does not factor in ExpCount
/// This is because the receiver does not know ExpCount for the sender, and even if it did, acks shouldn't be delayed for this reason
CCTimeType GetSenderRTOForACK(void) const;
/// Stop slow start, and enter normal transfer rate
void EndSlowStart(void);
/// Does the named conversion
inline double BytesPerMicrosecondToPacketsPerMillisecond(BytesPerMicrosecond in);
/// Update the round trip time, from ACK or ACK2
//void UpdateRTT(CCTimeType rtt);
/// Update the corresponding variables pre-slow start
void UpdateWindowSizeAndAckOnAckPreSlowStart(double totalUserDataBytesAcked);
/// Update the corresponding variables post-slow start
void UpdateWindowSizeAndAckOnAckPerSyn(CCTimeType curTime, CCTimeType rtt, bool isContinuousSend, DatagramSequenceNumberType sequenceNumber);
/// Sets halveSNDOnNoDataTime to the future, and also resets ExpCount, which is used to multiple the RTO on no data arriving at all
void ResetOnDataArrivalHalveSNDOnNoDataTime(CCTimeType curTime);
// Init array
void InitPacketArrivalHistory(void);
// Printf
void PrintLowBandwidthWarning(void);
// Bug: SND can sometimes get super high - have seen 11693
void CapMinSnd(const char *file, int line);
void DecreaseTimeBetweenSends(void);
void IncreaseTimeBetweenSends(void);
int bytesCanSendThisTick;
CCTimeType lastRttOnIncreaseSendRate;
CCTimeType lastRtt;
DatagramSequenceNumberType nextCongestionControlBlock;
bool hadPacketlossThisBlock;
DataStructures::Queue<CCTimeType> pingsLastInterval;
};
}
#endif
#endif
| [
"[email protected]"
]
| [
[
[
1,
396
]
]
]
|
0998171ec28aaec4efee93b6782cbbc87850050e | b2155efef00dbb04ae7a23e749955f5ec47afb5a | /source/OECore/OERender/OESkeletonRender_Impl.h | 89ede0e7d0672f772b235715e5ddff0a8fc807b5 | []
| no_license | zjhlogo/originengine | 00c0bd3c38a634b4c96394e3f8eece86f2fe8351 | a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f | refs/heads/master | 2021-01-20T13:48:48.015940 | 2011-04-21T04:10:54 | 2011-04-21T04:10:54 | 32,371,356 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 871 | h | /*!
* \file OESkeletonRender_Impl.h
* \date 1-3-2010 19:23:34
*
*
* \author zjhlogo ([email protected])
*/
#ifndef __OESKELETONRENDER_IMPL_H__
#define __OESKELETONRENDER_IMPL_H__
#include <OECore/OEBaseTypeEx.h>
#include <OECore/IOERender.h>
#include <OECore/IOEShader.h>
class COESkeletonRender_Impl : public IOERender
{
public:
RTTI_DEF(COESkeletonRender_Impl, IOERender);
COESkeletonRender_Impl();
virtual ~COESkeletonRender_Impl();
virtual bool Render(IOERenderData* pRenderData);
private:
bool Init();
void Destroy();
bool BuildBoneVerts(TV_VERTEX_LINE& vVertsOut, TV_VERTEX_INDEX& vIndisOut, IOESkeleton* pSkeleton, const CMatrix4x4* pSkinMatrixs, int nBoneID, int nParentBoneID);
private:
TV_VERTEX_LINE m_vVerts;
TV_VERTEX_INDEX m_vIndis;
IOEShader* m_pShader;
};
#endif // __OESKELETONRENDER_IMPL_H__
| [
"zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571"
]
| [
[
[
1,
37
]
]
]
|
a6fd09be12bce37b1f794d278f3f5fe3317974fc | 30e4267e1a7fe172118bf26252aa2eb92b97a460 | /code/pkg_Example/Modules/ChangeObserverExample/DocEventObserver.h | 1e272477a20d217587da9b4e8e8390e307af142c | [
"Apache-2.0"
]
| permissive | thinkhy/x3c_extension | f299103002715365160c274314f02171ca9d9d97 | 8a31deb466df5d487561db0fbacb753a0873a19c | refs/heads/master | 2020-04-22T22:02:44.934037 | 2011-01-07T06:20:28 | 2011-01-07T06:20:28 | 1,234,211 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,700 | h | //! \file DocEventObserver.h
//! \brief 定义文档事件观察者类 DocEventObserver
#ifndef EXAMPLE_DOCEVENT_OBSERVER_H_
#define EXAMPLE_DOCEVENT_OBSERVER_H_
#pragma once
#include <ChangeNotifyData.h>
//! 文档事件类型
enum kDocEventType
{
kDocEvent_BeforeOpen, //!< 文档打开之前
kDocEvent_AfterOpen, //!< 文档打开之后
kDocEvent_OpenFail, //!< 文档打开失败
};
//! 作为例子的文档事件观察者类
/*! 本例子用于让派生类都能响应多个事件通知
\note 建议派生类从本类私有继承
\ingroup _GROUP_CHANGE_OBSERVER_
*/
class DocEventObserver : public ChangeObserver
{
public:
//! DocEventObserver 观察者的通知数据类
class Data : public ChangeNotifyData
{
public:
Data(kDocEventType _event)
: ChangeNotifyData(typeid(DocEventObserver).name()), event(_event)
{
}
kDocEventType event;
};
protected:
DocEventObserver() : ChangeObserver(typeid(DocEventObserver).name())
{
}
//! 响应文档打开之前的通知
virtual void OnDocEventBeforeOpen() {}
//! 响应文档打开之后的通知
virtual void OnDocEventAfterOpen() {}
//! 响应文档打开失败的通知
virtual void OnDocEventOpenFail() {}
private:
void DoUpdate(ChangeNotifyData* data)
{
Data* mydata = dynamic_cast<Data*>(data);
ASSERT(mydata);
switch (mydata->event)
{
case kDocEvent_BeforeOpen:
OnDocEventBeforeOpen();
break;
case kDocEvent_AfterOpen:
OnDocEventAfterOpen();
break;
case kDocEvent_OpenFail:
OnDocEventOpenFail();
break;
default:
ASSERT(FALSE);
}
}
};
#endif // EXAMPLE_DOCEVENT_OBSERVER_H_
| [
"rhcad1@71899303-b18e-48b3-b26e-8aaddbe541a3"
]
| [
[
[
1,
78
]
]
]
|
3e8254d45107c98814059ca3da984407eae62962 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/python/src/converter/builtin_converters.cpp | 3223a250c2c26e2dfa04afb3f880e0be19a5544b | [
"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 | 13,377 | cpp | // Copyright David Abrahams 2002.
// 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)
#include <boost/python/handle.hpp>
#include <boost/python/type_id.hpp>
#include <boost/python/errors.hpp>
#include <boost/python/refcount.hpp>
#include <boost/python/detail/config.hpp>
#include <boost/python/detail/wrap_python.hpp>
#include <boost/python/converter/builtin_converters.hpp>
#include <boost/python/converter/rvalue_from_python_data.hpp>
#include <boost/python/converter/registry.hpp>
#include <boost/python/converter/registrations.hpp>
#include <boost/python/converter/shared_ptr_deleter.hpp>
#include <boost/cast.hpp>
#include <string>
#include <complex>
namespace boost { namespace python { namespace converter {
shared_ptr_deleter::shared_ptr_deleter(handle<> owner)
: owner(owner)
{}
shared_ptr_deleter::~shared_ptr_deleter() {}
void shared_ptr_deleter::operator()(void const*)
{
owner.reset();
}
namespace
{
// An lvalue conversion function which extracts a char const* from a
// Python String.
void* convert_to_cstring(PyObject* obj)
{
return PyString_Check(obj) ? PyString_AsString(obj) : 0;
}
// Given a target type and a SlotPolicy describing how to perform a
// given conversion, registers from_python converters which use the
// SlotPolicy to extract the type.
template <class T, class SlotPolicy>
struct slot_rvalue_from_python
{
public:
slot_rvalue_from_python()
{
registry::insert(
&slot_rvalue_from_python<T,SlotPolicy>::convertible
, &slot_rvalue_from_python<T,SlotPolicy>::construct
, type_id<T>()
);
}
private:
static void* convertible(PyObject* obj)
{
unaryfunc* slot = SlotPolicy::get_slot(obj);
return slot && *slot ? slot : 0;
}
static void construct(PyObject* obj, rvalue_from_python_stage1_data* data)
{
// Get the (intermediate) source object
unaryfunc creator = *static_cast<unaryfunc*>(data->convertible);
handle<> intermediate(creator(obj));
// Get the location in which to construct
void* storage = ((rvalue_from_python_storage<T>*)data)->storage.bytes;
# ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4244)
# endif
new (storage) T( SlotPolicy::extract(intermediate.get()) );
# ifdef _MSC_VER
# pragma warning(pop)
# endif
// record successful construction
data->convertible = storage;
}
};
// A SlotPolicy for extracting signed integer types from Python objects
struct signed_int_rvalue_from_python_base
{
static unaryfunc* get_slot(PyObject* obj)
{
PyNumberMethods* number_methods = obj->ob_type->tp_as_number;
if (number_methods == 0)
return 0;
return (PyInt_Check(obj) || PyLong_Check(obj))
? &number_methods->nb_int : 0;
}
};
template <class T>
struct signed_int_rvalue_from_python : signed_int_rvalue_from_python_base
{
static T extract(PyObject* intermediate)
{
long x = PyInt_AsLong(intermediate);
if (PyErr_Occurred())
throw_error_already_set();
return numeric_cast<T>(x);
}
};
// identity_unaryfunc/py_object_identity -- manufacture a unaryfunc
// "slot" which just returns its argument.
extern "C" PyObject* identity_unaryfunc(PyObject* x)
{
Py_INCREF(x);
return x;
}
unaryfunc py_object_identity = identity_unaryfunc;
// A SlotPolicy for extracting unsigned integer types from Python objects
struct unsigned_int_rvalue_from_python_base
{
static unaryfunc* get_slot(PyObject* obj)
{
PyNumberMethods* number_methods = obj->ob_type->tp_as_number;
if (number_methods == 0)
return 0;
return (PyInt_Check(obj) || PyLong_Check(obj))
? &py_object_identity : 0;
}
};
template <class T>
struct unsigned_int_rvalue_from_python : unsigned_int_rvalue_from_python_base
{
static T extract(PyObject* intermediate)
{
return numeric_cast<T>(
PyLong_Check(intermediate)
? PyLong_AsUnsignedLong(intermediate)
: PyInt_AS_LONG(intermediate));
}
};
// Checking Python's macro instead of Boost's - we don't seem to get
// the config right all the time. Furthermore, Python's is defined
// when long long is absent but __int64 is present.
#ifdef HAVE_LONG_LONG
// A SlotPolicy for extracting long long types from Python objects
struct long_long_rvalue_from_python_base
{
static unaryfunc* get_slot(PyObject* obj)
{
PyNumberMethods* number_methods = obj->ob_type->tp_as_number;
if (number_methods == 0)
return 0;
// Return the identity conversion slot to avoid creating a
// new object. We'll handle that in the extract function
if (PyInt_Check(obj))
return &number_methods->nb_int;
else if (PyLong_Check(obj))
return &number_methods->nb_long;
else
return 0;
}
};
struct long_long_rvalue_from_python : long_long_rvalue_from_python_base
{
static BOOST_PYTHON_LONG_LONG extract(PyObject* intermediate)
{
if (PyInt_Check(intermediate))
{
return PyInt_AS_LONG(intermediate);
}
else
{
BOOST_PYTHON_LONG_LONG result = PyLong_AsLongLong(intermediate);
if (PyErr_Occurred())
throw_error_already_set();
return result;
}
}
};
struct unsigned_long_long_rvalue_from_python : long_long_rvalue_from_python_base
{
static unsigned BOOST_PYTHON_LONG_LONG extract(PyObject* intermediate)
{
if (PyInt_Check(intermediate))
{
return numeric_cast<unsigned BOOST_PYTHON_LONG_LONG>(PyInt_AS_LONG(intermediate));
}
else
{
unsigned BOOST_PYTHON_LONG_LONG result = PyLong_AsUnsignedLongLong(intermediate);
if (PyErr_Occurred())
throw_error_already_set();
return result;
}
}
};
#endif
// A SlotPolicy for extracting bool from a Python object
struct bool_rvalue_from_python
{
static unaryfunc* get_slot(PyObject* obj)
{
return obj == Py_None || PyInt_Check(obj) ? &py_object_identity : 0;
}
static bool extract(PyObject* intermediate)
{
return PyObject_IsTrue(intermediate);
}
};
// A SlotPolicy for extracting floating types from Python objects.
struct float_rvalue_from_python
{
static unaryfunc* get_slot(PyObject* obj)
{
PyNumberMethods* number_methods = obj->ob_type->tp_as_number;
if (number_methods == 0)
return 0;
// For integer types, return the tp_int conversion slot to avoid
// creating a new object. We'll handle that below
if (PyInt_Check(obj))
return &number_methods->nb_int;
return (PyLong_Check(obj) || PyFloat_Check(obj))
? &number_methods->nb_float : 0;
}
static double extract(PyObject* intermediate)
{
if (PyInt_Check(intermediate))
{
return PyInt_AS_LONG(intermediate);
}
else
{
return PyFloat_AS_DOUBLE(intermediate);
}
}
};
// A SlotPolicy for extracting C++ strings from Python objects.
struct string_rvalue_from_python
{
// If the underlying object is "string-able" this will succeed
static unaryfunc* get_slot(PyObject* obj)
{
return (PyString_Check(obj))
? &obj->ob_type->tp_str : 0;
};
// Remember that this will be used to construct the result object
static std::string extract(PyObject* intermediate)
{
return std::string(PyString_AsString(intermediate),PyString_Size(intermediate));
}
};
#if defined(Py_USING_UNICODE) && !defined(BOOST_NO_STD_WSTRING)
// encode_string_unaryfunc/py_encode_string -- manufacture a unaryfunc
// "slot" which encodes a Python string using the default encoding
extern "C" PyObject* encode_string_unaryfunc(PyObject* x)
{
return PyUnicode_FromEncodedObject( x, 0, 0 );
}
unaryfunc py_encode_string = encode_string_unaryfunc;
// A SlotPolicy for extracting C++ strings from Python objects.
struct wstring_rvalue_from_python
{
// If the underlying object is "string-able" this will succeed
static unaryfunc* get_slot(PyObject* obj)
{
return PyUnicode_Check(obj)
? &py_object_identity
: PyString_Check(obj)
? &py_encode_string
: 0;
};
// Remember that this will be used to construct the result object
static std::wstring extract(PyObject* intermediate)
{
std::wstring result(::PyObject_Length(intermediate), L' ');
if (!result.empty())
{
int err = PyUnicode_AsWideChar(
(PyUnicodeObject *)intermediate
, &result[0]
, result.size());
if (err == -1)
throw_error_already_set();
}
return result;
}
};
#endif
struct complex_rvalue_from_python
{
static unaryfunc* get_slot(PyObject* obj)
{
if (PyComplex_Check(obj))
return &py_object_identity;
else
return float_rvalue_from_python::get_slot(obj);
}
static std::complex<double> extract(PyObject* intermediate)
{
if (PyComplex_Check(intermediate))
{
return std::complex<double>(
PyComplex_RealAsDouble(intermediate)
, PyComplex_ImagAsDouble(intermediate));
}
else if (PyInt_Check(intermediate))
{
return PyInt_AS_LONG(intermediate);
}
else
{
return PyFloat_AS_DOUBLE(intermediate);
}
}
};
}
BOOST_PYTHON_DECL PyObject* do_return_to_python(char x)
{
return PyString_FromStringAndSize(&x, 1);
}
BOOST_PYTHON_DECL PyObject* do_return_to_python(char const* x)
{
return x ? PyString_FromString(x) : boost::python::detail::none();
}
BOOST_PYTHON_DECL PyObject* do_return_to_python(PyObject* x)
{
return x ? x : boost::python::detail::none();
}
BOOST_PYTHON_DECL PyObject* do_arg_to_python(PyObject* x)
{
if (x == 0)
return boost::python::detail::none();
Py_INCREF(x);
return x;
}
#define REGISTER_INT_CONVERTERS(signedness, U) \
slot_rvalue_from_python< \
signedness U \
,signedness##_int_rvalue_from_python<signedness U> \
>()
#define REGISTER_INT_CONVERTERS2(U) \
REGISTER_INT_CONVERTERS(signed, U); \
REGISTER_INT_CONVERTERS(unsigned, U)
void initialize_builtin_converters()
{
// booleans
slot_rvalue_from_python<bool,bool_rvalue_from_python>();
// integer types
REGISTER_INT_CONVERTERS2(char);
REGISTER_INT_CONVERTERS2(short);
REGISTER_INT_CONVERTERS2(int);
REGISTER_INT_CONVERTERS2(long);
// using Python's macro instead of Boost's - we don't seem to get the
// config right all the time.
# ifdef HAVE_LONG_LONG
slot_rvalue_from_python<signed BOOST_PYTHON_LONG_LONG,long_long_rvalue_from_python>();
slot_rvalue_from_python<unsigned BOOST_PYTHON_LONG_LONG,unsigned_long_long_rvalue_from_python>();
# endif
// floating types
slot_rvalue_from_python<float,float_rvalue_from_python>();
slot_rvalue_from_python<double,float_rvalue_from_python>();
slot_rvalue_from_python<long double,float_rvalue_from_python>();
slot_rvalue_from_python<std::complex<float>,complex_rvalue_from_python>();
slot_rvalue_from_python<std::complex<double>,complex_rvalue_from_python>();
slot_rvalue_from_python<std::complex<long double>,complex_rvalue_from_python>();
// Add an lvalue converter for char which gets us char const*
registry::insert(convert_to_cstring,type_id<char>());
// Register by-value converters to std::string, std::wstring
#if defined(Py_USING_UNICODE) && !defined(BOOST_NO_STD_WSTRING)
slot_rvalue_from_python<std::wstring, wstring_rvalue_from_python>();
# endif
slot_rvalue_from_python<std::string, string_rvalue_from_python>();
}
}}} // namespace boost::python::converter
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
423
]
]
]
|
e803f1d19f52ea57c2a2099963ab3c4131de440b | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/dom/deprecated/DOM_NodeIterator.cpp | b59da86131da9dd8a691f5f53ddd64d434cdf3c5 | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,166 | cpp | /*
* Copyright 1999-2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: DOM_NodeIterator.cpp 176278 2005-01-07 14:38:22Z amassari $
*/
#include "DOM_NodeIterator.hpp"
#include "NodeIteratorImpl.hpp"
#include "RefCountedImpl.hpp"
XERCES_CPP_NAMESPACE_BEGIN
DOM_NodeIterator::DOM_NodeIterator()
{
fImpl = 0;
}
DOM_NodeIterator::DOM_NodeIterator(NodeIteratorImpl *impl)
{
fImpl = impl;
RefCountedImpl::addRef(fImpl);
}
DOM_NodeIterator::DOM_NodeIterator(const DOM_NodeIterator &other)
{
this->fImpl = other.fImpl;
RefCountedImpl::addRef(fImpl);
}
DOM_NodeIterator & DOM_NodeIterator::operator = (const DOM_NodeIterator &other)
{
if (this->fImpl != other.fImpl)
{
RefCountedImpl::removeRef(this->fImpl);
this->fImpl = other.fImpl;
RefCountedImpl::addRef(this->fImpl);
}
return *this;
};
DOM_NodeIterator & DOM_NodeIterator::operator = (const DOM_NullPtr * /*other*/)
{
RefCountedImpl::removeRef(this->fImpl);
this->fImpl = 0;
return *this;
};
DOM_NodeIterator::~DOM_NodeIterator()
{
RefCountedImpl::removeRef (this->fImpl);
fImpl = 0;
};
//
// Comparison operators. Equivalent of Java object reference ==
// Null references compare ==.
//
bool DOM_NodeIterator::operator != (const DOM_NodeIterator & other) const
{
return this->fImpl != other.fImpl;
};
bool DOM_NodeIterator::operator == (const DOM_NodeIterator & other) const
{
return this->fImpl == other.fImpl;
};
bool DOM_NodeIterator::operator != (const DOM_NullPtr * /*other*/) const
{
return this->fImpl != 0;
};
bool DOM_NodeIterator::operator == (const DOM_NullPtr * /*other*/) const
{
return this->fImpl == 0;
}
void DOM_NodeIterator::detach ()
{
fImpl->detach();
}
DOM_Node DOM_NodeIterator::getRoot()
{
return fImpl->getRoot();
}
unsigned long DOM_NodeIterator::getWhatToShow ()
{
return fImpl->getWhatToShow();
}
DOM_NodeFilter* DOM_NodeIterator::getFilter() {
return fImpl->getFilter();
}
/** Get the expandEntity reference flag. */
bool DOM_NodeIterator::getExpandEntityReferences()
{
if (fImpl !=0)
return fImpl->getExpandEntityReferences();
return false;
}
DOM_Node DOM_NodeIterator::nextNode() {
return fImpl->nextNode();
}
DOM_Node DOM_NodeIterator::previousNode() {
return fImpl->previousNode();
}
XERCES_CPP_NAMESPACE_END
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
145
]
]
]
|
2f446b7f73e32809334940e735a3f3636e3c4ac2 | 2b0e9ad72bb37219446e14c3e69bfda6d226218a | /tests/unit/Test_ConnectDisconnect/TestClasses.hpp | 33e7ecfa2f13f4c6853f9a78e95ef0c747ee917b | [
"MIT"
]
| permissive | svn2github/cpp-events | 5a672372e564f14ffd776e7d8f6fcb5a37eb307a | 572af0c42ceb7cbd3ee27d9c6e65412896e88c85 | refs/heads/master | 2020-05-17T01:15:05.179670 | 2011-07-28T15:33:46 | 2011-07-28T15:33:46 | 30,379,625 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,312 | hpp | // Copyright (c) 2010 Nickolas Pohilets
//
// This file is a part of the unit test suit for the CppEvents library.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <Cpp/Events.hpp>
namespace UnitTests {
namespace ConnectDisconnect {
//------------------------------------------------------------------------------
class Sender
{
public:
void fire() { somethingHappened_.fire(); }
Cpp::EventRef<> somethingHappened() { return somethingHappened_; }
private:
Cpp::Event<> somethingHappened_;
};
//------------------------------------------------------------------------------
class Reciever
{
public:
Reciever() : val_() {}
void increment() { ++val_; }
void decrement() { --val_; }
int value() const { return val_; }
void setValue(int v) { val_ = v; }
private:
int val_;
};
//------------------------------------------------------------------------------
class SenderEx : public Sender
{
public:
SenderEx()
{
stageNo_ = 0; // 1 2 3 4 ...
stageStep_ = 1; // 2 4 8 16 ...
}
int stageNo() const { return stageNo_; }
int stageStep() const { return stageStep_; }
void runStage()
{
fire();
++stageNo_;
stageStep_ *= 2;
}
private:
int stageNo_;
int stageStep_;
};
//------------------------------------------------------------------------------
class RecieverEx
{
public:
RecieverEx()
: sender_()
, scope_()
, index_(-1)
, val_()
{}
int index() const { return index_; }
int value() const { return val_; }
void connect(int ind, int arraySize, SenderEx * sender, Cpp::ConnectionScope * scope)
{
index_ = ind;
arraySize_ = arraySize;
sender_ = sender;
scope_ = scope;
scope->connect(sender->somethingHappened(), this, &RecieverEx::work);
}
void work()
{
++val_;
int step = sender_->stageStep();
int nextIndex = index_ + step;
if(nextIndex < arraySize_)
{
RecieverEx * next = this + step;
next->connect(nextIndex, arraySize_, sender_, scope_);
}
}
private:
SenderEx * sender_;
Cpp::ConnectionScope * scope_;
int index_;
int arraySize_;
int val_;
};
//------------------------------------------------------------------------------
} //namespace ConnectDisconnect
} //namespace UnitTests | [
"pohilets@67599820-88c8-11de-9c77-2f49170b69f2"
]
| [
[
[
1,
116
]
]
]
|
140718e8fa209270c9a6ad595666e59a210655ba | b09a4d24f49daac145a26c4e6b0dbd7749fb202b | /development/FileKeeperUT/MainFrm.cpp | c9b2ebaa767ce8eb950e8d2196edb3583756f959 | []
| no_license | buf1024/filekeeper | e4d6ead1413fa5c41e66f95d5a5df2b21f211b9f | cb52a3cb417a73535177658d7f83bf71c778a590 | refs/heads/master | 2021-01-10T12:55:16.930778 | 2010-12-23T15:10:26 | 2010-12-23T15:10:26 | 49,615,444 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,402 | cpp |
// MainFrm.cpp : CMainFrame 类的实现
//
#include "stdafx.h"
#include "UnitTest.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMainFrame
IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_CREATE()
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // 状态行指示器
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
// CMainFrame 构造/析构
CMainFrame::CMainFrame()
{
// TODO: 在此添加成员初始化代码
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndStatusBar.Create(this))
{
TRACE0("未能创建状态栏\n");
return -1; // 未能创建
}
m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT));
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return TRUE;
}
// CMainFrame 诊断
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CFrameWnd::Dump(dc);
}
#endif //_DEBUG
// CMainFrame 消息处理程序
| [
"buf1024@9b6b46d4-6a51-a6c0-14c6-10956b729e0f"
]
| [
[
[
1,
81
]
]
]
|
adea4c4c9993910dcadd38006ad4f393b55d8122 | 206001e5476c2752a71bcdbe79823f80039237c1 | /trunk/Input43D/src/Win32/I43DWin32Keyboard.cpp | 25d82b9739846916134355c355ed4e720098f02e | []
| no_license | BackupTheBerlios/input43d-svn | 90d4e5105483aa5d5bb759b8f48e3bfd5b444b29 | f2a38a891d99a7918643d02130d32334679a2a24 | refs/heads/master | 2020-05-26T23:54:12.968496 | 2005-11-15T23:47:32 | 2005-11-15T23:47:32 | 40,799,900 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,880 | cpp | /* -------------------------------------------------------------------------------------
This source file is part of Input43D : Copyright (c) 2000-2005 The Input43D Team
----------------------------------------------------------------------------------------
LICENSE:
This program 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 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 Lesser General Public License for more details.
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.
------------------------------------------------------------------------------------- */
#include "Win32/I43DWin32Keyboard.h"
namespace I43D {
Win32Keyboard::Win32Keyboard() {
}
Win32Keyboard::~Win32Keyboard() {
}
const std::wstring Win32Keyboard::getLayoutName() {
return NULL;
}
void Win32Keyboard::enableEvents(const bool flag) {
}
bool Win32Keyboard::isKeyPressed(const unsigned short keyNum) {
return false;
}
unsigned int Win32Keyboard::getScanCodeForKeyNum(const unsigned short keyNum) {
return 0;
}
unsigned short Win32Keyboard::getKeyNumForScanCode(const unsigned int scanCode) {
return 0;
}
NPKeyID Win32Keyboard::getNPKForKeyNum(const unsigned short keyNum) {
return NPK_ENTER;
}
unsigned short Win32Keyboard::getKeyNumForNPK(const NPKeyID npk) {
return 0;
}
} // namespace I43D | [
"kraythe@f99f173b-9205-0410-9d38-ddbc092449c0"
]
| [
[
[
1,
58
]
]
]
|
11c424adeb011853e830cc130a6d5dd3c8b25555 | 2766a276404d063d27b29468a113cf5f2b544520 | /quadtree/tree.cpp | a4f3250223365a87c00ffcba1fb782b2947b2169 | []
| no_license | giserh/rasterizer | 3a034beafc2a6a1941840ad7dc28f06c45d78c55 | bb7cb79d28ad660b748ab521e51117ef40e648f2 | refs/heads/master | 2020-12-24T11:33:01.788689 | 2011-05-27T09:12:05 | 2011-05-27T09:12:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,415 | cpp | #include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <algorithm>
#include <string>
#include <cassert>
#include "gdal.h"
#include "cpl_conv.h"
#include "ogr_api.h"
#include "ogr_srs_api.h"
#include "cpl_string.h"
#include "ogrsf_frmts.h"
#include "ogr_api.h"
#include "VFTree.h"
#include "rasterize.h"
using namespace std;
static int cur_len=0;
VFTree::VFTree(const struct sconfig& c)
{
config=c;
lroot=NULL;
for(int k=0;k<DIM;k++)
{
num_hier[k]=new int[config.num_lev+1];
num_hier[k][config.num_lev]=1;
for(int i=config.num_lev-1;i>=0;--i)
num_hier[k][i]=num_hier[k][i+1]*config.scales[k][i];
}
}
VFTree::~VFTree()
{
if(lroot!=NULL)
delete_vf_tree(lroot);
for(int k=0;k<DIM;k++)
{
if(num_hier[k]!=NULL)
delete num_hier[k] ;
}
}
int VFTree::rasterizelayer(const OGRLayerH layer)
{
lroot=new struct vftree;
lroot->gindex[0]=0;
lroot->gindex[1]=0;
lroot->level=0;
lroot->parent=NULL;
lroot->rec=new set<short int>;
int seq=0;
OGR_L_ResetReading( layer );
OGRFeatureH hFeat;
int this_rings=0,this_points=0;
while( (hFeat = OGR_L_GetNextFeature( layer )) != NULL )
{
OGRGeometry *poShape=(OGRGeometry *)OGR_F_GetGeometryRef( hFeat );
if(poShape==NULL)
{
cerr<<"error:............shape is NULL"<<endl;
continue;
}
OGRwkbGeometryType eFlatType = wkbFlatten(poShape->getGeometryType());
if( eFlatType == wkbPolygon )
{
OGRPolygon *poPolygon = (OGRPolygon *) poShape;
this_rings+=(poPolygon->getNumInteriorRings()+1);
}
std::vector<double> aPointX;
std::vector<double> aPointY;
std::vector<int> aPartSize;
GDALCollectRingsFromGeometry( poShape, aPointX, aPointY, aPartSize );
vector<double>::iterator minx,maxx,miny,maxy;
minx = min_element (aPointX.begin(), aPointX.end());
maxx = max_element (aPointX.begin(), aPointX.end());
miny = min_element (aPointY.begin(), aPointY.end());
maxy = max_element (aPointY.begin(), aPointY.end());
this_points=aPartSize.size();
if(aPartSize.size()==0) continue;
GDALdllImageFilledPolygon(aPartSize.size(), &(aPartSize[0]),&(aPointX[0]), &(aPointY[0]));
seq++;
OGR_F_Destroy( hFeat );
}
return seq;
}
int VFTree::gvBurnScanline(int nY, int nXStart, int nXEnd )
{
if(nXStart<0||nXEnd>=num_hier[0][0])
{
if(nXStart<0) nXStart=0;
if(nXEnd>=num_hier[0][0]) nXEnd=num_hier[0][0]-1;
}
if(nXStart>nXEnd)
return 0;
int num_cell=handleSingleLine(lroot,0,0,0,nY,nXStart,nXEnd);
int num_real=nXEnd-nXStart+1;
if(num_cell!=num_real)
{
cout<<" "<<nY<<" "<<nXStart<<" "<<nXEnd<<" "<<num_cell<<" "<<num_real<<endl;
int m=11;
}
return num_cell;
}
int VFTree::handleSingleLine(struct vftree *croot,int lev,int xorg,int yorg,int y,int x1,int x2)
{
int num_cell=0;
croot->level=lev;
croot->xorg=xorg;
croot->yorg=yorg;
int num_children=config.scales[0][lev]*config.scales[1][lev];
if(croot->children==NULL)
{
croot->children=new struct vftree *[num_children];
for(int i=0;i<num_children;i++)
croot->children[i]=NULL;
}
if(lev+1==config.num_lev)
{
//last level
for(int i=x1;i<=x2;i++)
{
int ind=(i-xorg)*config.scales[1][lev]+(y-yorg);
if(croot->children[ind]==NULL)
{
croot->children[ind]=new struct vftree;
croot->children[ind]->level=lev+1;
croot->children[ind]->gindex[0]=i-xorg;
croot->children[ind]->gindex[1]=y-yorg;
croot->children[ind]->parent=croot;
croot->children[ind]->rec=new set<short int>;
}
croot->children[ind]->rec->insert(y);
}
return (x2-x1+1);
}
int xpos1=(x1-xorg)/num_hier[0][lev+1];
int xpos2=(x2-xorg+1)/num_hier[0][lev+1];
int ypos=(y-yorg)/num_hier[1][lev+1];
int next_y_org=yorg+ypos*num_hier[1][lev+1];
bool left_align=(x1-xorg)%num_hier[0][lev+1]==0;
bool right_align=(x2-xorg+1)%num_hier[0][lev+1]==0;
//boundary
int start_ind=left_align?xpos1:xpos1+1;
int end_ind=xpos2;
//middle part
for(int i=start_ind;i<end_ind;i++)
{
int ind=i*config.scales[1][lev]+ypos;
if(croot->children[ind]==NULL)
{
croot->children[ind]=new struct vftree;
croot->children[ind]->level=lev+1;
croot->children[ind]->gindex[0]=i;
croot->children[ind]->gindex[1]=ypos;
croot->children[ind]->rec=new set<short int>;
croot->children[ind]->parent=croot;
}
croot->children[ind]->rec->insert (y);
//print_path(croot->children[ind]);
num_cell+=num_hier[0][lev+1];
}
int next_x1=xorg+start_ind*num_hier[0][lev+1]-1;
int next_x1_org=xorg+xpos1*num_hier[0][lev+1];
int next_ind1=xpos1*config.scales[1][lev]+ypos;
if(x2<=next_x1)
{
//drill down
if(croot->children[next_ind1]==NULL)
{
croot->children[next_ind1]=new struct vftree(lev+1,xpos1,ypos);
croot->children[next_ind1]->level=lev+1;
croot->children[next_ind1]->gindex[0]=xpos1;
croot->children[next_ind1]->gindex[1]=ypos;
croot->children[next_ind1]->rec=new set<short int>;
croot->children[next_ind1]->parent=croot;
}
num_cell+=handleSingleLine(croot->children[next_ind1],lev+1,next_x1_org,next_y_org,y,x1,x2);
}
else
{
if(!left_align)
{
//left part
if(croot->children[next_ind1]==NULL)
{
croot->children[next_ind1]=new struct vftree;
croot->children[next_ind1]->level=lev+1;
croot->children[next_ind1]->gindex[0]=xpos1;
croot->children[next_ind1]->gindex[1]=ypos;
croot->children[next_ind1]->rec=new set<short int>;
croot->children[next_ind1]->parent=croot;
}
num_cell+=handleSingleLine(croot->children[next_ind1],lev+1,next_x1_org,next_y_org,y,x1,next_x1);
}
int next_x2=xorg+xpos2*num_hier[0][lev+1];
if(!right_align)
{
//right part
int next_x2_org=xorg+xpos2*num_hier[0][lev+1];
int next_ind2=xpos2*config.scales[1][lev]+ypos;
if(croot->children[next_ind2]==NULL)
{
croot->children[next_ind2]=new struct vftree(lev+1,xpos2,ypos);
croot->children[next_ind2]->level=lev+1;
croot->children[next_ind2]->gindex[0]=xpos2;
croot->children[next_ind2]->gindex[1]=ypos;
croot->children[next_ind2]->rec=new set<short int>;
croot->children[next_ind2]->parent=croot;
}
num_cell+=handleSingleLine(croot->children[next_ind2],lev+1,next_x2_org,next_y_org,y,next_x2,x2);
}
}
return num_cell;
}
template <class T>
string VFTree::print_path(const T * croot)
{
const T *temp=croot;
vector<short int> vx,vy,vind;
string ret="";
while(temp->parent!=NULL)
{
vx.push_back(temp->gindex[0]);
vy.push_back(temp->gindex[1]);
int d=temp->gindex[0]*config.scales[1][temp->parent->level]+temp->gindex[1];
vind.push_back(d);
temp=temp->parent;
}
for(size_t i=0;i<vx.size();i++)
{
char ss[20];
sprintf(ss,"%d.",vind[vind.size()-1-i]);
ret+=ss;
}
return ret.substr(0,ret.size()-1);
}
void VFTree::delete_vf_tree(vftree *& croot)
{
if(croot==NULL)
return;
if(croot->children==NULL)
{
if(croot->rec!=NULL)
{
delete croot->rec;
croot->rec=NULL;
}
delete croot;
croot=NULL;
return;
}
int lev=croot->level;
for(int i=0;i<config.scales[0][lev];i++)
for(int j=0;j<config.scales[1][lev];j++)
{
int ind=i*config.scales[1][lev]+j;
delete_vf_tree(croot->children[ind]);
}
delete [] croot->children;
int num_children=config.scales[0][lev]*config.scales[1][lev];
croot->children=NULL;
if(croot->rec!=NULL)
{
delete croot->rec;
croot->rec=NULL;
}
delete croot;
croot=NULL;
}
void VFTree::textVFTree(char * id)
{
text_vf_tree(lroot, id);
}
void VFTree::text_vf_tree(const struct vftree *croot, char * id)
{
if(croot==NULL)
return;
if(croot->children==NULL)
{
cout<<print_path(croot)<<"\t"<<id<<endl;
return;
}
int lev=croot->level;
for(int i=0;i<config.scales[0][lev];i++)
for(int j=0;j<config.scales[1][lev];j++)
{
int ind=i*config.scales[1][lev]+j;
text_vf_tree(croot->children[ind], id);
}
}
void VFTree::node2coord(const vftree * croot,int& nx1,int& ny1,int& nx2,int& ny2)
{
int num=0;
const vftree * temp=croot;
while(temp!=lroot)
{
assert(temp!=NULL);
nx1+=temp->gindex[0]*num_hier[0][temp->level];
ny1+=temp->gindex[1]*num_hier[1][temp->level];
temp=temp->parent;
}
nx2=nx1+num_hier[0][croot->level];
ny2=ny1+num_hier[1][croot->level];
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
281
],
[
283,
283
],
[
285,
286
],
[
288,
292
],
[
294,
300
],
[
302,
319
]
],
[
[
282,
282
],
[
284,
284
],
[
287,
287
],
[
293,
293
],
[
301,
301
]
]
]
|
de812c2ebac223774002938189755fbed1411dee | faaac39c2cc373003406ab2ac4f5363de07a6aae | / zenithprime/src/loader/OBJModel.cpp | b1a9f3b02ada17685d896e3b9f11816203e409e9 | []
| no_license | mgq812/zenithprime | 595625f2ec86879eb5d0df4613ba41a10e3158c0 | 3c8ff4a46fb8837e13773e45f23974943a467a6f | refs/heads/master | 2021-01-20T06:57:05.754430 | 2011-02-05T17:20:19 | 2011-02-05T17:20:19 | 32,297,284 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | cpp | #include "OBJModel.h"
OBJModel::OBJModel(void)
{
}
OBJModel::~OBJModel(void)
{
}
static OBJModel* nullSingle = NULL;
OBJModel* OBJModel::NullOBJModel(){
if(nullSingle==NULL){
nullSingle = new OBJModel();
nullSingle->largestX = .5;
nullSingle->largestY = .5;
nullSingle->largestZ = .5;
nullSingle->smallestX = -.5;
nullSingle->smallestY = -.5;
nullSingle->smallestZ = -.5;
}
return nullSingle;
} | [
"mhsmith01@2c223db4-e1a0-a0c7-f360-d8b483a75394"
]
| [
[
[
1,
23
]
]
]
|
8abb5254b6759837dad33d72f1fae08b8d0381b9 | a36d7a42310a8351aa0d427fe38b4c6eece305ea | /core_billiard/RenderState_WireframeNull.hpp | 85c1d6758777fa44099c26eae5968f01edcbf49e | []
| no_license | newpolaris/mybilliard01 | ca92888373c97606033c16c84a423de54146386a | dc3b21c63b5bfc762d6b1741b550021b347432e8 | refs/heads/master | 2020-04-21T06:08:04.412207 | 2009-09-21T15:18:27 | 2009-09-21T15:18:27 | 39,947,400 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 237 | hpp | #pragma once
namespace my_render {
NULL_OBJECT( RenderState_Wireframe ) {
virtual void setSolid() OVERRIDE {}
virtual void setWired() OVERRIDE {}
virtual bool isSolid() const OVERRIDE { return false; }
};
} | [
"wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635"
]
| [
[
[
1,
14
]
]
]
|
040ff38b5c89237dab7a10b38ab6b7758ac33f57 | 8f5d0d23e857e58ad88494806bc60c5c6e13f33d | /Platform/cWIN32Application.cpp | c1093731bccab4a5f444fa97de6e49a291d06b90 | []
| no_license | markglenn/projectlife | edb14754118ec7b0f7d83bd4c92b2e13070dca4f | a6fd3502f2c2713a8a1a919659c775db5309f366 | refs/heads/master | 2021-01-01T15:31:30.087632 | 2011-01-30T16:03:41 | 2011-01-30T16:03:41 | 1,704,290 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,880 | cpp | #include "cWIN32Application.h"
#include "../Core/cLog.h"
#include "../Core/cRoot.h"
// Include Paul Nettle's memory manager
#include "../Memory/mmgr.h"
#define WND_CLASS "LIFE_WND_CLASS"
/////////////////////////////////////////////////////////////////////////////////////
cWIN32Application::cWIN32Application(void)
/////////////////////////////////////////////////////////////////////////////////////
{
}
/////////////////////////////////////////////////////////////////////////////////////
cWIN32Application::~cWIN32Application(void)
/////////////////////////////////////////////////////////////////////////////////////
{
}
/////////////////////////////////////////////////////////////////////////////////////
void cWIN32Application::CheckWIN32Errors()
/////////////////////////////////////////////////////////////////////////////////////
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );
cLog::Singleton()->Print ("Internal WIN32 Error: %s", lpMsgBuf);
// Free the buffer.
LocalFree( lpMsgBuf );
}
/////////////////////////////////////////////////////////////////////////////////////
bool cWIN32Application::RegisterAppClass()
/////////////////////////////////////////////////////////////////////////////////////
{
WNDCLASSEX wcex;
ZeroMemory (&wcex, sizeof(WNDCLASSEX));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = (WNDPROC)WndProc;
wcex.hInstance = m_hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = WND_CLASS;
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&wcex))
{
CheckWIN32Errors();
return false;
}
return true;
}
/////////////////////////////////////////////////////////////////////////////////////
bool cWIN32Application::CreateAppWindow()
/////////////////////////////////////////////////////////////////////////////////////
{
DWORD windowStyle = WS_OVERLAPPEDWINDOW;
RECT rc = {0, 0, m_width, m_height};
DWORD windowExtendedStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
AdjustWindowRectEx (&rc, windowStyle, 0, windowExtendedStyle);
m_hWnd = CreateWindowEx(
windowExtendedStyle, // Extended style
WND_CLASS, // Window class name
m_title.c_str(), // Window title
windowStyle | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, // Window style
0, // X-position
0, // Y-position
rc.right - rc.left, // Window width
rc.bottom-rc.top, // Window height
NULL, // Parent window
NULL, // Menu
m_hInstance, // Instance
this); // L-Param (Pass the app pointer)
if(!m_hWnd)
{
CheckWIN32Errors();
return false;
}
ShowWindow (m_hWnd, SW_SHOWDEFAULT);
cLog::Singleton()->Print ("Created WIN32 application");
return true;
}
/////////////////////////////////////////////////////////////////////////////////////
bool cWIN32Application::InitializeApplication()
/////////////////////////////////////////////////////////////////////////////////////
{
// Register the window class
if (!RegisterAppClass())
return false;
// Create the window
if (!CreateAppWindow())
return false;
return true;
}
/////////////////////////////////////////////////////////////////////////////////////
bool cWIN32Application::CloseApplication()
/////////////////////////////////////////////////////////////////////////////////////
{
// Close the window
if (m_hWnd)
DestroyWindow (m_hWnd);
m_hWnd = 0;
// Unregister the class
UnregisterClass (WND_CLASS, m_hInstance);
LOG()->Print ("Successfully destroyed WIN32 application");
return true;
}
/////////////////////////////////////////////////////////////////////////////////////
LRESULT CALLBACK cWIN32Application::WndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
/////////////////////////////////////////////////////////////////////////////////////
{
// Static pointer to the application class
static cWIN32Application *app = NULL;
switch (uMsg)
{
// Called on window creation
case WM_CREATE:
app = (cWIN32Application*)lParam;
return 0;
// Called on window termination
case WM_CLOSE:
PostMessage (hWnd, WM_QUIT, 0, 0);
return 0;
case WM_SIZE:
if (cRoot::Singleton()->GetOGLSystem())
cRoot::Singleton()->GetOGLSystem()->UpdateViewport(LOWORD(lParam), HIWORD(lParam));
return 0;
}
// Default to the default window procedure
return DefWindowProc (hWnd, uMsg, wParam, lParam);
}
/////////////////////////////////////////////////////////////////////////////////////
bool cWIN32Application::HandleMessages()
/////////////////////////////////////////////////////////////////////////////////////
{
static MSG msg;
//if (GetMessage (&msg, m_hWnd, 0, 0))
if (PeekMessage (&msg, m_hWnd, 0, 0, PM_REMOVE) != 0)
{
// Check For WM_QUIT Message
if (msg.message == WM_QUIT)
{
return false;
}
else
{
TranslateMessage (&msg);
DispatchMessage(&msg);
}
}
return true;
}
/////////////////////////////////////////////////////////////////////////////////////
void cWIN32Application::SetTitle (std::string title)
/////////////////////////////////////////////////////////////////////////////////////
{
cApplication::SetTitle (title);
SetWindowText ( m_hWnd, title.c_str() );
} | [
"[email protected]"
]
| [
[
[
1,
202
]
]
]
|
4ba872170baf94be3cef3a2300e0bdd6273f5374 | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/src/odephysics/nodehashspace_cmds.cc | cd0c5923025a2e2427df2b64294db708921012dd | []
| no_license | DSPNerd/m-nebula | 76a4578f5504f6902e054ddd365b42672024de6d | 52a32902773c10cf1c6bc3dabefd2fd1587d83b3 | refs/heads/master | 2021-12-07T18:23:07.272880 | 2009-07-07T09:47:09 | 2009-07-07T09:47:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,677 | cc | #define N_IMPLEMENTS nOdeHashSpace
//------------------------------------------------------------------------------
// (c) 2003 Vadim Macagon
//------------------------------------------------------------------------------
#include "odephysics/nodehashspace.h"
#include "kernel/npersistserver.h"
static void n_setlevels( void* slf, nCmd* cmd );
static void n_getlevels( void* slf, nCmd* cmd );
//------------------------------------------------------------------------------
/**
@scriptclass
nodehashspace
@superclass
nodecollidespace
@classinfo
Encapsulates an ODE hash space.
*/
void
n_initcmds( nClass* clazz )
{
clazz->BeginCmds();
clazz->AddCmd( "v_setlevels_ii", 'SLVL', n_setlevels );
clazz->AddCmd( "ii_getlevels_v", 'GLVL', n_getlevels );
clazz->EndCmds();
}
//------------------------------------------------------------------------------
/**
@cmd
setlevels
@input
i(MinLevel), i(MaxLevel)
@output
v
@info
Set the smallest and largest cell sizes to be used in the hash space.
For more information lookup dHashSpaceSetLevels in the ODE manual.
*/
static
void
n_setlevels( void* slf, nCmd* cmd )
{
nOdeHashSpace* self = (nOdeHashSpace*)slf;
int minLevel = cmd->In()->GetI();
int maxLevel = cmd->In()->GetI();
self->SetLevels( minLevel, maxLevel );
}
//------------------------------------------------------------------------------
/**
@cmd
getlevels
@input
v
@output
i(MinLevel), i(MaxLevel)
@info
Get the smallest and largest cell sizes to be used in the hash space.
For more information lookup dHashSpaceSetLevels in the ODE manual.
*/
static
void
n_getlevels( void* slf, nCmd* cmd )
{
nOdeHashSpace* self = (nOdeHashSpace*)slf;
int minLevel, maxLevel;
self->GetLevels( &minLevel, &maxLevel );
cmd->Out()->SetI( minLevel );
cmd->Out()->SetI( maxLevel );
}
//------------------------------------------------------------------------------
/**
@param ps Writes the nCmd object contents out to a file.
@return Success or failure.
*/
bool
nOdeHashSpace::SaveCmds( nPersistServer* ps )
{
if ( nOdeCollideSpace::SaveCmds( ps ) )
{
// setlevels
int minLevel, maxLevel;
this->GetLevels( &minLevel, &maxLevel );
nCmd* cmd = ps->GetCmd( this, 'SLVL' );
cmd->In()->SetI( minLevel );
cmd->In()->SetI( maxLevel );
ps->PutCmd( cmd );
return true;
}
return false;
}
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
| [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
]
| [
[
[
1,
107
]
]
]
|
71f215421e24ebc59c0e0ddc0df9f1ab4eb292bf | 723202e673511cf9f243177d964dfeba51cb06a3 | /09/oot/epa_labs/l2/src/Sketcher.h | da348224cadb61afd78bd621ebc2b1c6536f84fb | []
| no_license | aeremenok/a-team-777 | c2ffe04b408a266f62c523fb8d68c87689f2a2e9 | 0945efbe00c3695c9cc3dbcdb9177ff6f1e9f50b | refs/heads/master | 2020-12-24T16:50:12.178873 | 2009-06-16T14:55:41 | 2009-06-16T14:55:41 | 32,388,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,351 | h | // Sketcher.h : main header file for the SKETCHER application
//
#if !defined(AFX_SKETCHER_H__623441A3_57EA_11D0_9257_00201834E2A3__INCLUDED_)
#define AFX_SKETCHER_H__623441A3_57EA_11D0_9257_00201834E2A3__INCLUDED_
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CSketcherApp:
// See Sketcher.cpp for the implementation of this class
//
#include "OurConstants.h"
class CSketcherApp : public CWinApp
{
public:
CSketcherApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSketcherApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CSketcherApp)
afx_msg void OnAppAbout();
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SKETCHER_H__623441A3_57EA_11D0_9257_00201834E2A3__INCLUDED_)
| [
"emmanpavel@9273621a-9230-0410-b1c6-9ffd80c20a0c"
]
| [
[
[
1,
48
]
]
]
|
d4bd1fd5c98673e22d49d4ebd1d520fea8a9cebf | 4a2b2d6d07714e82ecf94397ea6227edbd7893ad | /Curl/TMOC/CameraData.cpp | 0f1ced08f099895c110f3f073f0168143d9c9a37 | []
| 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 | 2,401 | cpp | #include "StdAfx.h"
#include ".\cameradata.h"
//------------------------------------------------------------------------
// Constructors/Destructors:
//------------------------------------------------------------------------
/** Default Constructor. */
CameraData::CameraData() : intercom(""), url(""), username(""), password("")
{
}
/** Constructor that sets the URL only. */
CameraData::CameraData(string intercom) : intercom(""), username(""), password("")
{
this->intercom = intercom;
}
/** Constructor that sets the URL, username and password. */
CameraData::CameraData(string url, string username, string password) : intercom("")
{
this->url = url;
this->username = username;
this->password = password;
}
/** Constructor that sets the Intercom, URL, username and password. */
CameraData::CameraData(string intercom, string url, string username, string password)
{
this->intercom = intercom;
this->url = url;
this->username = username;
this->password = password;
}
/** Destructor. */
CameraData::~CameraData(void)
{
// nothing to do
}
//------------------------------------------------------------------------
// Getters:
//------------------------------------------------------------------------
string CameraData::getUrl()
{
return this->url;
}
string CameraData::getUsername()
{
return this->username;
}
string CameraData::getPassword()
{
return this->password;
}
string CameraData::getIntercom()
{
return this->intercom;
}
//------------------------------------------------------------------------
// Setters:
//------------------------------------------------------------------------
void CameraData::setUrl(string url)
{
this->url = url;
}
void CameraData::setUsername(string username)
{
this->username = username;
}
void CameraData::setPassword(string password)
{
this->password = password;
}
void CameraData::setIntercom(string intercom)
{
this->intercom = intercom;
}
/**
* Overloaded Assignment operator; this allows us to "assign"
* a CameraData to another CameraData; it literally just copies
* the data in.
*/
CameraData& CameraData::operator=(const CameraData &old)
{
if(this != &old)
{
this->intercom = old.intercom;
this->url = old.url;
this->username = old.username;
this->password = old.password;
}
return *this;
} | [
"einternicola@8c6822e2-464b-4b1f-8ae9-3c1f0a8e8225"
]
| [
[
[
1,
107
]
]
]
|
6e6e5d835451bdf72238a897aefc7305716111e7 | 720466c088f243d6d54046e34872a91e3c911c58 | /math/polynomials/ml_poly_interpolation.h | e0574deb9047f656b6824a60f1c9129d900b5b4d | []
| no_license | tmarkovich/mathlib | 57f0d788a34e235b003bb49da4cb47bceb812026 | a24353d59d38e18a44e084c5fc2accee6c1750a1 | refs/heads/master | 2021-01-17T18:24:02.477880 | 2011-03-05T23:17:58 | 2011-03-05T23:17:58 | 14,571,612 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,807 | h | #ifndef ML_POLY_INTERPOLATION
#define ML_POLY_INTERPOLATION
#include "ml_poly.h"
template<class T>
inline T nev_Pij(T const & x,int const & i,int const & j, T const * X, T const * Y )
{
// function used for neville's algorithm for polynomial interpolation
//
//assert(i>=0); assert(i<N); assert(j<N);assert(i<=j);
if (i == j)
return Y[i];
else
return ((x-X[j])*nev_Pij(x,i,j-1,X,Y) +(X[i]-x)*nev_Pij(x,i+1,j,X,Y))/(X[i]-X[j]);
}
template<class T>
T nev_interp(T x, T * X, T * Y, int N)
{
// neville's algorithm for polynomial interpolation
// interpolates at the point x, between points (x_i,y_i) for x_i in X and y_i in Y,
// and 0 <= i < N
return nev_Pij(x,0,N-1,X,Y);
}
template< class T >
inline const T divided_difference(const int & k, const T * x_, const T * y_ )
{
// computes the forward divided difference of the k+1 number of 2-tuples (x_i,y_i)
if (!k)
return y_[0];
else
return (divided_difference(k-1,x_+1,y_+1)-divided_difference(k-1,x_,y_))/(x_[k]-x_[0]);
}
template< class T >
inline const T divided_difference_save(const int & k, const T * x_, const T * y_, T * a_ )
{
// computes the forward divided difference of the k+1 number of 2-tuples (x_i,y_i),
// saving the results a_j = [y_0,y_1,..,y_j]
//
// usage: if there are n 2-tuples, then call
// divided_difference_save(n-1,x_,y_,a_+n-1);
//
// where a_ is a pointer to an array of size n, it will be written to in reverse order
//
if (!k)
{
*a_ = y_[0];
return y_[0];
}
else
{
*a_ = (divided_difference(k-1,x_+1,y_+1)-divided_difference_save(k-1,x_,y_,a_-1))/(x_[k]-x_[0]);
return *a_;
}
}
template< class T >
void expand_product_binomial_roots(int degree, T * roots, ml_poly<T > & E)
{
// takes the polynomial
// product( (x-roots_i) , 0 <= i < degree )
//
// and expands it into the monomial basis
//
E.resize(1);
ml_poly<T > q(1);
E[0] = -roots[0];
E[1] = 1.0;
for (int k=1; k<degree; k++)
{
q[0] = -roots[k];
q[1] = 1.0;
E *= q;
}
}
template< class T >
ml_poly<T > * gen_newton_basis(int n, T * roots)
{
// generatres the newtom basis,
// { N_j(x) }, 1 <= j < n
//
// where N_j(x) = product( (x-roots_i) , 0 <= i < j )
//
// N_0(x) = 1.0, N_1(x) = (x-x_0), ...
//
// delete N when done
ml_poly<T > * N = new ml_poly<T > [n];
N[0].resize(0);
N[0][0] = 1.0;
for (int j=1; j<n; j++)
{
N[j].resize(1);
N[j][0] = -roots[j-1];
N[j][1] = 1.0;
N[j] *= N[j-1];
}
return N;
}
template<class T >
void gen_newton_interp_poly(int n, T * x_, T * y_, ml_poly<T > & P )
{
// generatres the newton interpolation polynomial,
// n-1 th degree, for n data points (x_i,y_i)
//
ml_poly<T > * N = gen_newton_basis(n,x_ );
T * a_ = new T [n];
divided_difference_save(n-1,x_,y_,a_+n-1);
P.resize(n-1);
P = 0;
for (int j=0; j<n; j++)
{
N[j] *= a_[j];
P += N[j];
}
delete [] N;
delete [] a_;
}
template<class D >
ml_poly<D > * gen_orthoNorm_polys( int N, double a, double b )
{
// generate a set of N, N-1 th degree, polynomials,
// using modified gram-schmidt, starting with monomials,
// using the L2 inner product over the interval (a,b)
//
ml_poly<D > * V = new ml_poly<D > [N];
for (int i = 0; i<N; i++)
{
V[i].resize(N-1);
V[i] = 0.0;
V[i][i] = 1.0;
}
ml_poly<D > p,q;
p = V[0];
p *= V[0];
V[0] /= mp_real(sqrt(p.integrate(a,b)));
for (int k=1; k<N; k++)
for (int j = 0; j<k; j++)
{
p = V[j];
p *= V[k];
q = V[j];
q *= p.integrate(a,b);
V[k] -= q;
p = V[k];
p *= V[k];
V[k] /= mp_real(sqrt(p.integrate(a,b)));
}
return V;
}
#ifdef ARPREC_MPREAL_H
ml_poly<double > * gen_orthoNorm_polys_mp_real_double( int N, double a, double b, int digits=70 )
{
// generate a set of N, N-1 th degree, polynomials,
// using modified gram-schmidt, starting with monomials,
// using the L2 inner product over the interval (a,b)
//
// using mp_reals, converted to double.
//
mp::mp_init(digits);
ml_poly<mp_real > * B_ = gen_orthoNorm_polys<mp_real > (N,a,b);
ml_poly<double > * B = new ml_poly<double> [N];
for (int j = 0; j<N; j++)
{
B[j].copy(B_[j]);
ML_POLY_LOOP( B[j] )
B[j][i] = dble(B_[j][i]);
}
delete [] B_;
return B;
}
#endif
#endif
| [
"nick@nick-desktop.(none)"
]
| [
[
[
1,
219
]
]
]
|
064ba37f4506b0e2f002b7d71fc1430e31401657 | dadf8e6f3c1adef539a5ad409ce09726886182a7 | /airplay/src/toeDefaultHitTest.cpp | d90b87c815a5b4161703bf986ce0786025a39269 | []
| no_license | sarthakpandit/toe | 63f59ea09f2c1454c1270d55b3b4534feedc7ae3 | 196aa1e71e9f22f2ecfded1c3da141e7a75b5c2b | refs/heads/master | 2021-01-10T04:04:45.575806 | 2011-06-09T12:56:05 | 2011-06-09T12:56:05 | 53,861,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,525 | cpp | #include <IwTextParserITX.h>
#include <IwResManager.h>
#include "toeDefaultHitTest.h"
using namespace TinyOpenEngine;
//Instantiate the default factory function for a named class
IW_CLASS_FACTORY(CtoeDefaultHitTest);
//This macro is required within some source file for every class derived from CIwManaged. It implements essential functionality
IW_MANAGED_IMPLEMENT(CtoeDefaultHitTest);
namespace TinyOpenEngine
{
}
//Constructor
CtoeDefaultHitTest::CtoeDefaultHitTest()
{
}
//Desctructor
CtoeDefaultHitTest::~CtoeDefaultHitTest()
{
}
//Update subsystem state
void CtoeDefaultHitTest::Update(iwfixed dt)
{
}
//Find all entities under the pointer
void CtoeDefaultHitTest::PointerHitTest(HitTestContext* htc)
{
int32 i = items.GetFirstItem();
while (i >= 0)
{
htc->callback(htc, items.GetItemAt(i)->GetEntity());
i = items.GetNextItem(i);
}
}
//Render image on the screen surface
void CtoeDefaultHitTest::Render()
{
}
//Prepare subsystem
void CtoeDefaultHitTest::Initialize(CtoeWorld*w)
{
TtoeSubsystem<CtoeComponent>::Initialize(w);
}
//Reads/writes a binary file using @a IwSerialise interface.
void CtoeDefaultHitTest::Serialise ()
{
TtoeSubsystem<CtoeComponent>::Serialise();
}
#ifdef IW_BUILD_RESOURCES
//Parses from text file: parses attribute/value pair.
bool CtoeDefaultHitTest::ParseAttribute(CIwTextParserITX* pParser, const char* pAttrName)
{
return TtoeSubsystem<CtoeComponent>::ParseAttribute(pParser,pAttrName);
}
#endif | [
"[email protected]"
]
| [
[
[
1,
68
]
]
]
|
e840464b7241673d7b5fd89481edafe0184fa5e7 | efed0b8073c74464728e031c7b9581299a3f699f | /VisualDX/WinDX/AssemblyInfo.cpp | 1425eb0f28565772863d78b8b65cc6e13845d4d3 | []
| no_license | BackupTheBerlios/opendx2 | 57b933bfd9f2d86f849b6afa59389733d29a0710 | 17ef6dbd13ab65192adaeccd8944674fea9e9583 | refs/heads/master | 2021-01-23T02:29:46.290263 | 2008-04-13T15:43:59 | 2008-04-13T15:43:59 | 40,069,100 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,344 | cpp | #include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("WinDX")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("VIS, Inc.")];
[assembly:AssemblyProductAttribute("WinDX")];
[assembly:AssemblyCopyrightAttribute("Copyright (c) VIS, Inc. 2006")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly:AssemblyVersionAttribute("1.0.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
| [
"dthompsn"
]
| [
[
[
1,
40
]
]
]
|
9c5ef130e64aacbace26f0852e7c133b4660ba65 | f177993b13e97f9fecfc0e751602153824dfef7e | /ImProSln/TouchLibFilter/Touchlib/include/BrightnessContrastFilter.h | f26baf180df5dbc87e76c6ebb8dc310479daac87 | []
| no_license | svn2github/imtophooksln | 7bd7412947d6368ce394810f479ebab1557ef356 | bacd7f29002135806d0f5047ae47cbad4c03f90e | refs/heads/master | 2020-05-20T04:00:56.564124 | 2010-09-24T09:10:51 | 2010-09-24T09:10:51 | 11,787,598 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 989 | h |
#ifndef __TOUCHLIB_FILTER_BRIGHTNESSCONTRAST__
#define __TOUCHLIB_FILTER_BRIGHTNESSCONTRAST__
#include <TouchlibFilter.h>
#define DEFAULT_BRIGHTNESS 0.0
#define DEFAULT_CONTRAST 0.2
class BrightnessContrastFilter : public Filter
{
public:
BrightnessContrastFilter(char*);
void kernel();
void kernelWithROI();
virtual ~BrightnessContrastFilter();
void setBrightness(float value);
void setContrast(float value);
float getContrast(void) {return contrast;}
float getBrightness(void) {return brightness;}
virtual void getParameters(ParameterMap& pMap);
virtual void setParameter(const char *name, const char *value);
virtual void showOutput(bool value, int windowx, int windowy);
private:
void updateLUT( void );
uchar lut[256*4];
int brightness_slider;
int contrast_slider;
float brightness;
float contrast;
CvMat* lutmat;
};
#endif // __TOUCHLIB_FILTER_BRIGHTNESSCONTRAST__
| [
"ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a"
]
| [
[
[
1,
47
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.