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
41d436ec07a16f7473cadb94983709a947fc79f5
41c264ec05b297caa2a6e05e4476ce0576a8d7a9
/OpenHoldem/OpenHoldemDoc.cpp
35fe0e3e37b48dfdfa1e6eea4432eb93963c477b
[]
no_license
seawei/openholdem
cf19a90911903d7f4d07f956756bd7e521609af3
ba408c835b71dc1a9d674eee32958b69090fb86c
refs/heads/master
2020-12-25T05:40:09.628277
2009-01-25T01:17:10
2009-01-25T01:17:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,934
cpp
// OpenHoldemDoc.cpp : implementation of the COpenHoldemDoc class // #include "stdafx.h" #include "OpenHoldemDoc.h" #include "OpenHoldem.h" #include "MainFrm.h" #include "CPreferences.h" #include "CDllExtension.h" #include "DialogFormulaScintilla.h" // COpenHoldemDoc IMPLEMENT_DYNCREATE(COpenHoldemDoc, CDocument) BEGIN_MESSAGE_MAP(COpenHoldemDoc, CDocument) END_MESSAGE_MAP() // COpenHoldemDoc construction/destruction COpenHoldemDoc::COpenHoldemDoc() { __SEH_SET_EXCEPTION_HANDLER p_formula->ClearFormula(); } COpenHoldemDoc::~COpenHoldemDoc() { } BOOL COpenHoldemDoc::OnNewDocument() { CMainFrame *pMyMainWnd = (CMainFrame *) (theApp.m_pMainWnd); if (!CDocument::OnNewDocument()) return FALSE; // Kill the formula dialog, if it is open if(m_formulaScintillaDlg) { delete m_formulaScintillaDlg; m_formulaScintillaDlg = NULL; pMyMainWnd->m_MainToolBar.GetToolBarCtrl().CheckButton(ID_MAIN_TOOLBAR_FORMULA, false); } // Default bot p_formula->SetDefaultBot(); // Try to unload dll p_dll_extension->UnloadDll(); // Create hand list matrices p_formula->CreateHandListMatrices(); // Create parse trees for default formula p_formula->ParseAllFormula(pMyMainWnd->GetSafeHwnd()); SetTitle("Default"); //SetModifiedFlag(true); // Load dll, if set in preferences if (prefs.dll_load_on_startup()) p_dll_extension->LoadDll(""); return true; } // COpenHoldemDoc serialization void COpenHoldemDoc::Serialize(CArchive& ar) { CMainFrame *pMyMainWnd = (CMainFrame *) (theApp.m_pMainWnd); // Writing a file if (ar.IsStoring()) { // Store archive in the specified format, // whether it is OHF or WHF. bool use_new_OHF_format = !IsWinHoldemFormat(ar.GetFile()->GetFileName()); p_formula->WriteFormula(ar, use_new_OHF_format); // Do not close this archive here. // It's expected to stay open at this point! if (IsWinHoldemFormat(ar.GetFile()->GetFileName())) { // If the file was in the old WHF format, // store it also in the new OHF format. CString the_new_FileName = GetPathName(); the_new_FileName.Replace("whf", "ohf"); // Notification MessageBox(0, "Converting file formats\n{whf, whx} -> {ohf}", "File Conversion", MB_OK | MB_ICONINFORMATION); // Open new style formula (OHF) CFile OHF_File; OHF_File.Open(the_new_FileName, CFile::modeCreate | CFile::modeWrite); CArchive OHF_Archive(&OHF_File, CArchive::store); // Write new style formula (OHF) in any case p_formula->WriteFormula(OHF_Archive, true); // Close archive and file OHF_Archive.Close(); OHF_File.Close(); } } // Reading a file else { // Kill the formula dialog, if it is open if(m_formulaScintillaDlg) { delete m_formulaScintillaDlg; m_formulaScintillaDlg = NULL; pMyMainWnd->m_MainToolBar.GetToolBarCtrl().CheckButton(ID_MAIN_TOOLBAR_FORMULA, false); } // Read ohf / whf file ReadFormula(ar); SetModifiedFlag(false); p_formula->set_formula_name(ar.GetFile()->GetFileName()); // Try to unload dll p_dll_extension->UnloadDll(); // Create hand list matrices p_formula->CreateHandListMatrices(); // Create parse trees for newly loaded formula p_formula->ParseAllFormula(pMyMainWnd->GetSafeHwnd()); // Load dll, if set in preferences if (prefs.dll_load_on_startup()) p_dll_extension->LoadDll(""); } } void COpenHoldemDoc::ReadFormula(CArchive& ar) { // Clear everything p_formula->ClearFormula(); // There are two types of formulas // * ohf // * whf and optional whx // In the latter case we have to read both files. p_formula->ReadFormulaFile(ar, true); CFile *cf_whf = ar.GetFile(); CString CSpath = cf_whf->GetFilePath(); if (IsWinHoldemFormat(CSpath)) { CFile *cf_whf = ar.GetFile(); CFile cf_whx; CString CSpath = cf_whf->GetFilePath(); CSpath.Replace(".whf", ".whx"); if (cf_whx.Open(CSpath, CFile::modeNoTruncate | CFile::modeRead| CFile::shareDenyWrite)) { CArchive ar_whx(&cf_whx, CArchive::load); // Read whx file, too. //??? p_formula->ReadFormulaFile(ar_whx, false); } } // Check and add missing... p_formula->CheckForDefaultFormulaEntries(); } BOOL COpenHoldemDoc::IsWinHoldemFormat(CString the_FileName) { unsigned int Length = the_FileName.GetLength(); // Path maybe undefined at startup... if (Length < 3) return false; // Checking the first character of the file extension // Assuming an extension of size 3: "ohf" or "whf". char critical_Character = the_FileName.GetString()[Length - 3]; return (critical_Character == 'w'); } COpenHoldemDoc * COpenHoldemDoc::GetDocument() { CFrameWnd * pFrame = (CFrameWnd *)(AfxGetApp()->m_pMainWnd); return (COpenHoldemDoc *) pFrame->GetActiveDocument(); }
[ [ [ 1, 189 ] ] ]
27b76ce66aa7c2976176af89b3cf60e5110bbf43
aab4c401149d8cdee10094d4fb4de98f490be3b6
/src/gui/cLuaGL.cpp
e6f15c87c6b8533c01e4302c0b4eca49077944cf
[]
no_license
soulik/quads
a7a49e32dcd137fd32fd45b60fa26b5c0747bd03
ce440c5d35448908fd936797bff0cb7a9ff78b6e
refs/heads/master
2016-09-08T00:18:28.704939
2008-09-01T14:18:42
2008-09-01T14:18:42
32,122,815
0
0
null
null
null
null
UTF-8
C++
false
false
40,785
cpp
#include "gui/cGL.h" #include "gui/cLuaGL.h" #include <SDL/SDL_opengl.h> #include "modules/renderer.h" #include "modules/qTexturer.h" #include "modules/script.h" #include "common.h" #include "base.h" #define SELECT_BUF_SIZE 512 extern cBase * __parent; GLuint selectBuffer[SELECT_BUF_SIZE]; static void setTableValuei(lua_State * L, const char * name, int value){ lua_pushstring(L,name); lua_pushinteger(L,value); lua_settable(L,-3); } static void setTableValuef(lua_State * L, const char * name, float value){ lua_pushstring(L,name); lua_pushnumber(L,value); lua_settable(L,-3); } static void setTableValues(lua_State * L, const char * name, const char * value){ lua_pushstring(L,name); lua_pushstring(L,value); lua_settable(L,-3); } static int gl_GetImage(lua_State * L){ try{ qImage * image = __TEXTURE->getImage(lua_tostring(L,1)); if (image){ lua_newtable(L); setTableValuei(L,"id",image->getID()); setTableValues(L,"name",image->getName()); setTableValuei(L,"flags",image->getFlags()); setTableValuei(L,"width",image->getWidth()); setTableValuei(L,"height",image->getHeight()); //lua_settable(L,-6); }else{ lua_pushnil(L); } return 1; }catch (cException e) { fprintf(stderr,"%s",e.what()); return 0; } } static void processHits (GLint hits, GLuint buffer[]){ unsigned int i, j; GLuint names, *ptr, minZ,*ptrNames=NULL, numberOfNames=0; if (!buffer) return; ptr = (GLuint *) buffer;//=NULL; minZ = 0xffffffff; for (i = 0; i < (unsigned int)hits; i++) { names = *ptr; ptr++; if (*ptr < minZ) { numberOfNames = names; minZ = *ptr; ptrNames = ptr+2; } ptr += names+2; } ptr = ptrNames; for (j = 0; j < numberOfNames; j++,ptr++) { __SCRIPT->call("pickedObject",*ptr); } } static int startPicking(lua_State * L){ GLint viewport[4]; GLdouble cursorX = lua_tonumber(L,1); GLdouble cursorY = lua_tonumber(L,2); glSelectBuffer(SELECT_BUF_SIZE,selectBuffer); glRenderMode(GL_SELECT); glInitNames(); glPushName(0); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glGetIntegerv(GL_VIEWPORT,viewport); gluPickMatrix(cursorX,viewport[3]-cursorY, 5,5,viewport); //gluPerspective(45,(GLfloat) (viewport[2]-viewport[0])/(GLfloat) (viewport[3]-viewport[1]),0.1,1000); //__RENDER->drawPlayerView(); //glMatrixMode(GL_MODELVIEW); return 0; } static int stopPicking(lua_State * L){ int hits; // restoring the original projection matrix glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glFlush(); // returning to normal rendering mode hits = glRenderMode(GL_RENDER); // if there are hits process them if (hits != 0){ processHits(hits,selectBuffer); } return 0; } static int gl_MatrixMode(lua_State * L){ glMatrixMode((GLuint)lua_tonumber(L,1)); return 0; } static int gl_LoadIdentity(lua_State * L){ glLoadIdentity(); return 0; } static int gl_Viewport(lua_State * L){ glViewport((GLuint)lua_tonumber(L,1),(GLuint)lua_tonumber(L,2),(GLuint)lua_tonumber(L,3),(GLuint)lua_tonumber(L,4)); return 0; } static int gl_Ortho(lua_State * L){ glOrtho((GLdouble)lua_tonumber(L,1),(GLdouble)lua_tonumber(L,2),(GLdouble)lua_tonumber(L,3),(GLdouble)lua_tonumber(L,4),(GLdouble)lua_tonumber(L,5),(GLdouble)lua_tonumber(L,6)); return 0; } static int gl_FrontFace(lua_State * L){ glFrontFace((GLuint)lua_tonumber(L,1)); return 0; } static int gl_ClearColor(lua_State * L){ glClearColor((GLclampf)lua_tonumber(L,1),(GLclampf)lua_tonumber(L,2),(GLclampf)lua_tonumber(L,3),(GLclampf)lua_tonumber(L,4)); return 0; } static int gl_Clear(lua_State * L){ glClear((GLuint)lua_tonumber(L,1)); return 0; } static int gl_Scalef(lua_State * L){ glScalef((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2),(GLfloat)lua_tonumber(L,3)); return 0; } static int gl_Rotatef(lua_State * L){ glRotatef((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2),(GLfloat)lua_tonumber(L,3),(GLfloat)lua_tonumber(L,4)); return 0; } static int gl_Translatef(lua_State * L){ glTranslatef((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2),(GLfloat)lua_tonumber(L,3)); return 0; } static int gl_CopyTexSubImage2D(lua_State * L){ glCopyTexSubImage2D((GLuint)lua_tonumber(L,1),(GLuint)lua_tonumber(L,2),(GLuint)lua_tonumber(L,3),(GLuint)lua_tonumber(L,4),(GLuint)lua_tonumber(L,5),(GLuint)lua_tonumber(L,6),(GLuint)lua_tonumber(L,7),(GLuint)lua_tonumber(L,8)); return 0; } static int gl_BindTexture(lua_State * L){ glBindTexture((GLuint)lua_tonumber(L,1),(GLuint)lua_tonumber(L,2)); return 0; } static int gl_Enable(lua_State * L){ glEnable((GLuint)lua_tonumber(L,1)); return 0; } static int gl_Disable(lua_State * L){ glDisable((GLuint)lua_tonumber(L,1)); return 0; } static int gl_TexParameteri(lua_State * L){ glTexParameteri((GLuint)lua_tonumber(L,1),(GLuint)lua_tonumber(L,2),(GLint)lua_tonumber(L,3)); return 0; } static int gl_BlendFunc(lua_State * L){ glBlendFunc((GLuint)lua_tonumber(L,1),(GLuint)lua_tonumber(L,2)); return 0; } static int gl_Begin(lua_State * L){ uint temp= (GLuint)lua_tonumber(L,1); glBegin(temp); return 0; } static int gl_End(lua_State * L){ glEnd(); return 0; } static int gl_EndList(lua_State * L){ glEndList(); return 0; } static int gl_Color3f(lua_State * L){ glColor3f((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2),(GLfloat)lua_tonumber(L,3)); return 0; } static int gl_Color4f(lua_State * L){ glColor4f((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2),(GLfloat)lua_tonumber(L,3),(GLfloat)lua_tonumber(L,4)); return 0; } static int gl_Vertex2f(lua_State * L){ glVertex2f((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2)); return 0; } static int gl_Vertex2i(lua_State * L){ glVertex2i((GLint)lua_tonumber(L,1),(GLint)lua_tonumber(L,2)); return 0; } static int gl_Vertex3f(lua_State * L){ glVertex3f((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2),(GLfloat)lua_tonumber(L,3)); return 0; } static int gl_TexCoord2f(lua_State * L){ glTexCoord2f((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2)); return 0; } static int gl_PrepareOrthogonal(lua_State * L){ __RENDER->prepareOrthogonal(); return 0; } static int gl_printf(lua_State * L){ __RENDER->font->printf((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2),qRGBA((uint)lua_tonumber(L,3)),lua_tostring(L,4)); return 0; } static int gl_tprintfEx(lua_State * L){ __RENDER->font->tprintfEx((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2),qRGBA((uint)lua_tonumber(L,3)),lua_tostring(L,4)); return 0; } static int gl_tprintf(lua_State * L){ qFont * _font = __RENDER->font; try{ _font->tprintf((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2),(GLfloat)lua_tonumber(L,3),(GLfloat)lua_tonumber(L,4),qRGBA((uint)lua_tonumber(L,5)),lua_tostring(L,6)); }catch (cException e){ __RENDER->dprintf("Exception: %s",e.what()); } return 0; } static int gl_tglyph(lua_State * L){ qFont * _font = __RENDER->font; float w = (GLfloat)lua_tonumber(L,3); float h = (GLfloat)lua_tonumber(L,4); try{ //_font->tglyph((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2),w,h,(GLfloat)lua_tonumber(L,5),qRGBA((uint)lua_tonumber(L,6)),(unsigned short)lua_tointeger(L,7)); }catch (cException e){ __RENDER->dprintf("Exception: %s",e.what()); } lua_pushnumber(L,w); lua_pushnumber(L,h); return 2; } static int gl_load_font(lua_State * L){ qFont * _font = __RENDER->font; _font->loadFont(lua_tostring(L,1),(int)lua_tonumber(L,2)); return 0; } static int gl_Accum(lua_State * L){ glAccum((GLuint)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2)); return 0; } static int gl_AreTexturesResident(lua_State * L){ //glAreTextureResident((GLuint)lua_tonumber(L,1),(GLuint)lua_tonumber(L,2)); __RENDER->dprintf("Stub(%s)","glAreTexturesResident()"); return 0; } static int gl_AlphaFunc(lua_State * L){ glAlphaFunc((GLenum)lua_tonumber(L,1),(GLclampf)lua_tonumber(L,2)); return 0; } static int gl_ArrayElement(lua_State * L){ glArrayElement((GLint)lua_tonumber(L,1)); return 0; } static int gl_BeginCurve(lua_State * L){ //glBeginCurve( __RENDER->dprintf("Stub(%s)","glBeginCurve()"); return 0; } static int gl_BeginPolygon(lua_State * L){ __RENDER->dprintf("Stub(%s)","glBeginPolygon()"); return 0; } static int gl_BeginSurface(lua_State * L){ __RENDER->dprintf("Stub(%s)","glBeginSurface()"); return 0; } static int gl_BeginTrim(lua_State * L){ __RENDER->dprintf("Stub(%s)","glBeginTrim()"); return 0; } static int gl_Bitmap(lua_State * L){ //glBitmap( __RENDER->dprintf("Stub(%s)","glBeginBitmap()"); return 0; } static int gl_BlendColorEXT(lua_State * L){ __RENDER->dprintf("Stub(%s)","glBlendColorEXT()"); return 0; } static int glu_Build1DMipmaps(lua_State * L){ __RENDER->dprintf("Stub(%s)","glBuild1DMipmaps()"); return 0; } static int glu_Build2DMipmaps(lua_State * L){ int ret = gluBuild2DMipmaps((GLenum)lua_tonumber(L,1),(GLint)lua_tonumber(L,2),(GLint)lua_tonumber(L,3),(GLint)lua_tonumber(L,4),(GLenum)lua_tonumber(L,5),(GLenum)lua_tonumber(L,6),(const void*)lua_topointer(L,7)); lua_pushnumber(L,ret); return 1; } static int gl_CallList(lua_State * L){ glCallList((GLuint)lua_tonumber(L,1)); return 0; } static int gl_CallLists(lua_State * L){ glCallLists((GLsizei)lua_tonumber(L,1),(GLenum)lua_tonumber(L,2),(const GLvoid*)lua_topointer(L,3)); return 0; } static int gl_ClearAccum(lua_State * L){ glClearAccum((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2),(GLfloat)lua_tonumber(L,3),(GLfloat)lua_tonumber(L,4)); return 0; } static int gl_ClearDepth(lua_State * L){ glClearDepth((GLclampd)lua_tonumber(L,1)); return 0; } static int gl_ClearIndex(lua_State * L){ glClearIndex((GLfloat)lua_tonumber(L,1)); return 0; } static int gl_ClearStencil(lua_State * L){ glClearStencil((GLint)lua_tonumber(L,1)); return 0; } double lGetFieldd(lua_State * L, int i){ lua_pushnumber(L,1); lua_gettable(L,-2); double ret = lua_tonumber(L,1); lua_pop(L,1); return ret; } static int gl_ClipPlane(lua_State * L){ GLdouble eq[4]; int plane = (int)lua_tonumber(L,1); lua_pushvalue(L,2); if (lua_istable(L, -1)){ eq[0] = lGetFieldd(L,1); eq[1] = lGetFieldd(L,2); eq[2] = lGetFieldd(L,3); eq[3] = lGetFieldd(L,4); } glClipPlane((GLenum)plane,(GLdouble*)eq); return 0; } static int gl_Color3d(lua_State * L){ glColor3d((GLdouble)lua_tonumber(L,1),(GLdouble)lua_tonumber(L,2),(GLdouble)lua_tonumber(L,3)); return 0; } static int gl_Color3dv(lua_State * L){ __RENDER->dprintf("Stub(%s)","glColor3dv()"); return 0; } static int gl_Color3fv(lua_State * L){ __RENDER->dprintf("Stub(%s)","glColor3fv()"); return 0; } static int gl_Color4d(lua_State * L){ glColor3d((GLdouble)lua_tonumber(L,1),(GLdouble)lua_tonumber(L,2),(GLdouble)lua_tonumber(L,3)); return 0; } static int gl_Color4dv(lua_State * L){ __RENDER->dprintf("Stub(%s)","glColor3dv()"); return 0; } static int gl_Color4fv(lua_State * L){ __RENDER->dprintf("Stub(%s)","glColor4fv()"); return 0; } static int gl_ColorMask(lua_State * L){ glColorMask((GLboolean)lua_tonumber(L,1),(GLboolean)lua_tonumber(L,2),(GLboolean)lua_tonumber(L,3),(GLboolean)lua_tonumber(L,4)); return 0; } static int gl_ColorMaterial(lua_State * L){ glColorMaterial((GLenum)lua_tonumber(L,1),(GLenum)lua_tonumber(L,2)); return 0; } static int gl_ColorPointer(lua_State * L){ __RENDER->dprintf("Stub(%s)","glColorPointer()"); //glColorPointer( return 0; } static int gl_CopyPixels(lua_State * L){ glCopyPixels((GLint)lua_tonumber(L,1),(GLint)lua_tonumber(L,2),(GLsizei)lua_tonumber(L,3),(GLsizei)lua_tonumber(L,4),(GLenum)lua_tonumber(L,5)); return 0; } static int gl_CopyTexImage1D(lua_State * L){ glCopyTexImage1D((GLenum)lua_tonumber(L,1),(GLint)lua_tonumber(L,2),(GLenum)lua_tonumber(L,3),(GLint)lua_tonumber(L,4),(GLint)lua_tonumber(L,5),(GLsizei)lua_tonumber(L,6),(GLint)lua_tonumber(L,7)); return 0; } static int gl_CopyTexImage2D(lua_State * L){ glCopyTexImage2D((GLenum)lua_tonumber(L,1),(GLint)lua_tonumber(L,2),(GLenum)lua_tonumber(L,3),(GLint)lua_tonumber(L,4),(GLint)lua_tonumber(L,5),(GLsizei)lua_tonumber(L,6),(GLsizei)lua_tonumber(L,7),(GLint)lua_tonumber(L,8)); return 0; } static int gl_CopyTexSubImage1D(lua_State * L){ glCopyTexSubImage1D((GLenum)lua_tonumber(L,1),(GLint)lua_tonumber(L,2),(GLint)lua_tonumber(L,3),(GLint)lua_tonumber(L,4),(GLsizei)lua_tonumber(L,5),(GLsizei)lua_tonumber(L,6)); return 0; } static int gl_CullFace(lua_State * L){ glCullFace((GLenum)lua_tonumber(L,1)); return 0; } static int gl_DeleteLists(lua_State * L){ __RENDER->dprintf("Stub(%s)","glDeleteLists()"); //glDeleteList( return 0; } static int gl_DeleteTextures(lua_State * L){ __RENDER->dprintf("Stub(%s)","glDeleteTextures()"); //glDeleteTextures( return 0; } static int gl_DepthFunc(lua_State * L){ glDepthFunc((GLenum)lua_tonumber(L,1)); return 0; } static int gl_DepthMask(lua_State * L){ __RENDER->dprintf("Stub(%s)","glDepthMask()"); //glDepthMask( return 0; } static int gl_DepthRange(lua_State * L){ glDepthRange((GLclampd)lua_tonumber(L,1),(GLclampd)lua_tonumber(L,2)); return 0; } static int gl_DepthTextures(lua_State * L){ __RENDER->dprintf("Stub(%s)","glDepthTextures()"); //glDepthTextures( return 0; } static int gl_DrawArrays(lua_State * L){ __RENDER->dprintf("Stub(%s)","glDrawArrays()"); return 0; } static int gl_DrawBuffer(lua_State * L){ __RENDER->dprintf("Stub(%s)","glDrawBuffer()"); return 0; } static int gl_DrawElements(lua_State * L){ __RENDER->dprintf("Stub(%s)","glDrawElements()"); //glDrawElements( return 0; } static int gl_DrawPixels(lua_State * L){ __RENDER->dprintf("Stub(%s)","glDrawPixels()"); return 0; } static int gl_EdgeFlag(lua_State * L){ glEdgeFlag((GLboolean)lua_toboolean(L,1)); return 0; } static int gl_EdgeFlagPointer(lua_State * L){ __RENDER->dprintf("Stub(%s)","glEdgeFlagPointer()"); return 0; } static int gl_EnableClientState(lua_State * L){ glEnableClientState((GLenum)lua_tonumber(L,1)); return 0; } static int gl_DisableClientState(lua_State * L){ glDisableClientState((GLenum)lua_tonumber(L,1)); return 0; } static int glu_ErrorString(lua_State * L){ int name = (int)lua_tonumber(L,1); const char * str = (const char *)gluErrorString(name); if (!str) str= "(NULL)"; lua_pushstring(L,str); return 1; } static int gl_EvalCoord(lua_State * L){ __RENDER->dprintf("Stub(%s)","glEvalCoord()"); return 0; } static int gl_EvalMesh(lua_State * L){ __RENDER->dprintf("Stub(%s)","glEvalMesh()"); return 0; } static int gl_EvalPoint(lua_State * L){ __RENDER->dprintf("Stub(%s)","glEvalPoint()"); return 0; } static int gl_FeedbackBuffer(lua_State * L){ __RENDER->dprintf("Stub(%s)","glFeedbackBuffer()"); //glFeedbackBuffer((GLdouble)lua_tonumber(L,1),(GLdouble)lua_tonumber(L,1),(GLdouble)lua_tonumber(L,1)); return 0; } static int gl_Fog(lua_State * L){ glFogf((GLenum)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2)); return 0; } static int gl_Finish(lua_State * L){ glFinish(); return 0; } static int gl_Flush(lua_State * L){ glFlush(); return 0; } static int gl_Frustum(lua_State * L){ glFrustum((GLdouble)lua_tonumber(L,1),(GLdouble)lua_tonumber(L,2),(GLdouble)lua_tonumber(L,3),(GLdouble)lua_tonumber(L,4),(GLdouble)lua_tonumber(L,5),(GLdouble)lua_tonumber(L,6)); return 0; } static int gl_GenLists(lua_State * L){ GLuint ret = glGenLists((GLsizei)lua_tonumber(L,1)); lua_pushnumber(L,ret); return 1; } static int gl_GenTextures(lua_State * L){ GLuint tex[255]; int count = (GLsizei)lua_tonumber(L,1); if (count<=255){ glGenTextures(count,tex); for (int i=0; i <count; i++){ lua_pushnumber(L,tex[i]); } }else{ count = 0; } return count; } static int gl_Get(lua_State * L){ __RENDER->dprintf("Stub(%s)","glGet()"); //glGet( return 0; } static int gl_GetClipPlane(lua_State * L){ __RENDER->dprintf("Stub(%s)","glGetClipPlane()"); return 0; } static int gl_GetError(lua_State * L){ int error = glGetError(); lua_pushnumber(L,error); return 1; } static int gl_GetLight(lua_State * L){ //glGetLight( return 0; } static int gl_GetMap(lua_State * L){ //glGetMapf( return 0; } static int gl_GetMaterial(lua_State * L){ //glGetMateriald( return 0; } static int gl_GetPixelMap(lua_State * L){ return 0; } static int gl_GetPointer(lua_State * L){ return 0; } static int gl_GetPolygonStipple(lua_State * L){ return 0; } static int gl_GetString(lua_State * L){ int name = (int)lua_tonumber(L,1); const char * str = (const char *)glGetString(name); if (!str) str= "(NULL)"; lua_pushstring(L,str); return 1; } static int glu_GetString(lua_State * L){ return 0; } static int gl_GetTessProperty(lua_State * L){ return 0; } static int gl_GetTexEnv(lua_State * L){ return 0; } static int gl_GetTexGen(lua_State * L){ return 0; } static int gl_GetTexImage(lua_State * L){ return 0; } static int gl_GetTexLevelParameter(lua_State * L){ return 0; } static int gl_GetTexParameter(lua_State * L){ return 0; } static int gl_Hint(lua_State * L){ glHint((GLenum)lua_tonumber(L,1),(GLenum)lua_tonumber(L,2)); return 0; } static int gl_Index(lua_State * L){ glIndexf((GLfloat)lua_tonumber(L,1)); return 0; } static int gl_IndexMask(lua_State * L){ glIndexMask((GLuint)lua_tonumber(L,1)); return 0; } static int gl_IndexPointer(lua_State * L){ return 0; } static int gl_InitNames(lua_State * L){ glInitNames(); return 0; } static int gl_InterleavedArrays(lua_State * L){ return 0; } static int gl_IsEnabled(lua_State * L){ GLboolean ret = glIsEnabled((GLenum)lua_tonumber(L,1)); lua_pushboolean(L,ret); return 1; } static int gl_IsList(lua_State * L){ GLboolean ret = glIsList((GLuint)lua_tonumber(L,1)); lua_pushboolean(L,ret); return 1; } static int gl_IsTexture(lua_State * L){ //glIsTexure((GLuint)lua_tonumber(L,1)); return 0; } static int gl_Lighti(lua_State * L){ glLighti((GLenum)lua_tonumber(L,1),(GLenum)lua_tonumber(L,2),(GLint)lua_tonumber(L,3)); return 0; } static int gl_Lightf(lua_State * L){ glLightf((GLenum)lua_tonumber(L,1),(GLenum)lua_tonumber(L,2),(GLfloat)lua_tonumber(L,3)); return 0; } static int gl_Lightfv(lua_State * L){ GLenum p1 = (GLenum)lua_tonumber(L,1); GLenum p2 = (GLenum)lua_tonumber(L,2); GLfloat * param = getArrayf(L,3); glLightfv(p1,p2,param); delete[] param; return 0; } static int gl_LightModelf(lua_State * L){ glLightModelf((GLenum)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2)); return 0; } static int gl_LightModelfv(lua_State * L){ GLfloat param [4]; param[0] = (GLfloat)lua_tonumber(L,2); param[1] = (GLfloat)lua_tonumber(L,3); param[2] = (GLfloat)lua_tonumber(L,4); param[3] = (GLfloat)lua_tonumber(L,5); glLightModelfv((GLenum)lua_tonumber(L,1),param); return 0; } static int gl_LineStipple(lua_State * L){ glLineStipple((GLint)lua_tonumber(L,1),(GLushort)lua_tonumber(L,2)); return 0; } static int gl_LineWidth(lua_State * L){ glLineWidth((GLfloat)lua_tonumber(L,1)); return 0; } static int gl_ListBase(lua_State * L){ glListBase((GLuint)lua_tonumber(L,1)); return 0; } static int gl_LoadMatrix(lua_State * L){ //glLoadMatrix( return 0; } static int gl_LoadName(lua_State * L){ glLoadName((GLuint)lua_tonumber(L,1)); return 0; } static int glu_LoadSamplingMatrices(lua_State * L){ return 0; } static int glu_LookAt(lua_State * L){ gluLookAt((GLdouble)lua_tonumber(L,1),(GLdouble)lua_tonumber(L,2),(GLdouble)lua_tonumber(L,3),(GLdouble)lua_tonumber(L,4),(GLdouble)lua_tonumber(L,5),(GLdouble)lua_tonumber(L,6),(GLdouble)lua_tonumber(L,7),(GLdouble)lua_tonumber(L,8),(GLdouble)lua_tonumber(L,9)); return 0; } static int gl_Map1(lua_State * L){ //glMap1f( return 0; } static int gl_Map2(lua_State * L){ return 0; } static int gl_MapGrid(lua_State * L){ return 0; } static int gl_Materialf(lua_State * L){ glMaterialf((GLenum)lua_tonumber(L,1),(GLenum)lua_tonumber(L,2),(GLfloat)lua_tonumber(L,3)); return 0; } static int gl_Materialfv(lua_State * L){ GLfloat * param = getArrayf(L,3); glMaterialfv((GLenum)lua_tonumber(L,1),(GLenum)lua_tonumber(L,2),param); delete[] param; return 0; } static int gl_MultMatrix(lua_State * L){ //glMultMatrixf( return 0; } static int gl_NewList(lua_State * L){ glNewList((GLuint)lua_tonumber(L,1),(GLenum)lua_tonumber(L,2)); return 0; } static int glu_NewNurbsRenderer(lua_State * L){ return 0; } static int glu_NewQuadric(lua_State * L){ GLUquadric * ret = gluNewQuadric(); lua_pushlightuserdata(L,ret); return 1; } static int glu_NewTess(lua_State * L){ GLUtesselator * ret = gluNewTess(); lua_pushlightuserdata(L,ret); return 1; } static int glu_NextContour(lua_State * L){ return 0; } static int gl_Normal3f(lua_State * L){ glNormal3f((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2),(GLfloat)lua_tonumber(L,3)); return 0; } static int gl_Normal3d(lua_State * L){ glNormal3d((GLdouble)lua_tonumber(L,1),(GLdouble)lua_tonumber(L,2),(GLdouble)lua_tonumber(L,3)); return 0; } static int gl_NormalPointer(lua_State * L){ return 0; } static int gl_NurbsCallback(lua_State * L){ return 0; } static int gl_NurbsCurve(lua_State * L){ return 0; } static int gl_NurbsProperty(lua_State * L){ return 0; } static int gl_NurbsSurface(lua_State * L){ return 0; } static int glu_Ortho2D(lua_State * L){ gluOrtho2D((GLdouble)lua_tonumber(L,1),(GLdouble)lua_tonumber(L,2),(GLdouble)lua_tonumber(L,3),(GLdouble)lua_tonumber(L,4)); return 0; } static int glu_PartialDisk(lua_State * L){ gluPartialDisk((GLUquadric*)lua_touserdata(L,1),lua_tonumber(L,2),lua_tonumber(L,3),(int)lua_tonumber(L,4),(int)lua_tonumber(L,5),lua_tonumber(L,6),lua_tonumber(L,7)); return 0; } static int gl_PassThrough(lua_State * L){ glPassThrough((GLfloat)lua_tonumber(L,1)); return 0; } static int glu_Perspective(lua_State * L){ gluPerspective((GLdouble)lua_tonumber(L,1),(GLdouble)lua_tonumber(L,2),(GLdouble)lua_tonumber(L,3),(GLdouble)lua_tonumber(L,4)); return 0; } static int glu_PickMatrix(lua_State * L){ //gluPickMatrix( return 0; } static int gl_PixelMap(lua_State * L){ return 0; } static int gl_PixelStore(lua_State * L){ //glPixelStore( return 0; } static int gl_PixelTransfer(lua_State * L){ //glPixelTransfer( return 0; } static int gl_PixelZoom(lua_State * L){ glPixelZoom((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2)); return 0; } static int gl_PointSize(lua_State * L){ glPointSize((GLfloat)lua_tonumber(L,1)); return 0; } static int gl_PolygonMode(lua_State * L){ glPolygonMode((GLenum)lua_tonumber(L,1),(GLenum)lua_tonumber(L,2)); return 0; } static int gl_PolygonOffset(lua_State * L){ glPolygonOffset((GLfloat)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2)); return 0; } static int gl_PolygonStipple(lua_State * L){ //glPolygonStipple( return 0; } static int gl_PrioritizeTextures(lua_State * L){ //glPrioritizeTextures( return 0; } static int glu_Project(lua_State * L){ //gluProject( return 0; } static int gl_PopAttrib(lua_State * L){ glPopAttrib(); return 0; } static int gl_PopClientAttrib(lua_State * L){ glPopClientAttrib(); return 0; } static int gl_PopMatrix(lua_State * L){ glPopMatrix(); return 0; } static int gl_PopName(lua_State * L){ glPopName(); return 0; } static int gl_PushAttrib(lua_State * L){ glPushAttrib((GLbitfield)lua_tonumber(L,1)); return 0; } static int gl_PushClientAttrib(lua_State * L){ glPushClientAttrib((GLbitfield)lua_tonumber(L,1)); return 0; } static int gl_PushMatrix(lua_State * L){ glPushMatrix(); return 0; } static int gl_PushName(lua_State * L){ glPushName((GLuint)lua_tonumber(L,1)); return 0; } static int glu_PwlCurve(lua_State * L){ //gluPwlCurve( return 0; } static int glu_QuadricCallback(lua_State * L){ //gluQuadricCallback( return 0; } static int glu_QuadricDrawStyle(lua_State * L){ gluQuadricDrawStyle((GLUquadric*)lua_touserdata(L,1),(GLenum)lua_tonumber(L,2)); return 0; } static int glu_QuadricNormals(lua_State * L){ GLUquadric * ptr = (GLUquadric *) lua_touserdata(L,1); int normals = (int)lua_tonumber(L,1); gluQuadricNormals(ptr,normals); return 0; } static int glu_QuadricOrientation(lua_State * L){ GLUquadric * ptr = (GLUquadric *) lua_touserdata(L,1); int orientation = (int)lua_tonumber(L,1); gluQuadricOrientation(ptr,orientation); return 0; } static int glu_QuadricTexture(lua_State * L){ GLUquadric * ptr = (GLUquadric *) lua_touserdata(L,1); int textures = (int)lua_toboolean(L,1); gluQuadricTexture(ptr,textures); return 0; } static int gl_RasterPos(lua_State * L){ return 0; } static int gl_ReadBuffer(lua_State * L){ return 0; } static int gl_ReadPixels(lua_State * L){ return 0; } static int gl_Rect(lua_State * L){ return 0; } static int gl_RenderMode(lua_State * L){ GLint ret = glRenderMode((GLenum)lua_tonumber(L,1)); lua_pushnumber(L,ret); return 1; } static int glu_ScaleImage(lua_State * L){ //gluScaleImage( return 0; } static int gl_Scissor(lua_State * L){ glScissor((GLint)lua_tonumber(L,1),(GLint)lua_tonumber(L,2),(GLsizei)lua_tonumber(L,3),(GLsizei)lua_tonumber(L,4)); return 0; } static int gl_SelectBuffer(lua_State * L){ //glSelectBuffer( return 0; } static int gl_ShadeModel(lua_State * L){ glShadeModel((GLenum)lua_tonumber(L,1)); return 0; } static int glu_Sphere(lua_State * L){ gluSphere((GLUquadric*)lua_touserdata(L,1),lua_tonumber(L,2),(int)lua_tonumber(L,3),(int)lua_tonumber(L,4)); return 0; } static int gl_StencilFunc(lua_State * L){ glStencilFunc((GLenum)lua_tonumber(L,1),(GLint)lua_tonumber(L,2),(GLuint)lua_tonumber(L,3)); return 0; } static int gl_StencilMask(lua_State * L){ glStencilMask((GLuint)lua_tonumber(L,1)); return 0; } static int gl_StencilOp(lua_State * L){ glStencilOp((GLenum)lua_tonumber(L,1),(GLenum)lua_tonumber(L,2),(GLenum)lua_tonumber(L,3)); return 0; } static int glu_TessBeginContour(lua_State * L){ return 0; } static int glu_TessBeginPolygon(lua_State * L){ return 0; } static int glu_TessCallback(lua_State * L){ return 0; } static int glu_TessEndPolygon(lua_State * L){ return 0; } static int glu_TessNormal(lua_State * L){ return 0; } static int glu_TessProperty(lua_State * L){ return 0; } static int glu_TessVertex(lua_State * L){ return 0; } static int gl_TexCoordPointer(lua_State * L){ return 0; } static int gl_TexEnvi(lua_State * L){ glTexEnvi((GLenum)lua_tonumber(L,1),(GLenum)lua_tonumber(L,2),(GLint)lua_tonumber(L,3)); return 0; } static int gl_TexEnvf(lua_State * L){ glTexEnvf((GLenum)lua_tonumber(L,1),(GLenum)lua_tonumber(L,2),(GLfloat)lua_tonumber(L,3)); return 0; } static int gl_TexGen(lua_State * L){ //glTexGen( return 0; } static int gl_TexImage1D(lua_State * L){ return 0; } static int gl_TexImage2D(lua_State * L){ //glTexImage2D( return 0; } static int gl_TexParameter(lua_State * L){ //glTexParameter( return 0; } static int gl_TexSubImage1D(lua_State * L){ return 0; } static int gl_TexSubImage2D(lua_State * L){ return 0; } static int glu_UnloadProject(lua_State * L){ return 0; } static int gl_VertexPointer(lua_State * L){ return 0; } static int gl_CreateProgramObject(lua_State * L){ int so = glCreateProgramObjectARB(); lua_pushnumber(L,so); return 1; } static int gl_CreateShaderObject(lua_State * L){ int so = glCreateShaderObjectARB((GLenum)lua_tonumber(L,1)); lua_pushnumber(L,so); return 1; } static int gl_ShaderSource(lua_State * L){ const char * shader_source = lua_tostring(L,3); glShaderSourceARB((GLhandleARB)lua_tonumber(L,1), (int)lua_tonumber(L,2), (const char **)&shader_source, NULL); return 0; } static int gl_CompileShader(lua_State * L){ glCompileShaderARB((GLuint) lua_tonumber(L,1)); return 0; } static int gl_UseProgram(lua_State * L){ glUseProgramObjectARB((GLuint) lua_tonumber(L,1)); return 0; } static int gl_AttachObject(lua_State * L){ glAttachObjectARB((GLhandleARB) lua_tonumber(L,1),(GLhandleARB) lua_tonumber(L,2)); return 0; } static int gl_LinkProgram(lua_State * L){ glLinkProgramARB((GLhandleARB) lua_tonumber(L,1)); return 0; } static int gl_GetInfoLog(lua_State * L){ int len; char buffer[1000]; glGetInfoLogARB((GLhandleARB) lua_tonumber(L,1),(GLsizei)lua_tonumber(L,2),&len,buffer); lua_pushstring(L,buffer); return 1; } static int gl_DeleteObject(lua_State * L){ glDeleteObjectARB((GLhandleARB) lua_tonumber(L,1)); return 0; } static int gl_DetachShader(lua_State * L){ glDetachObjectARB((GLhandleARB) lua_tonumber(L,1), (GLhandleARB) lua_tonumber(L,2)); return 0; } static int gl_GetProgramiv(lua_State * L){ //glGetProgramiv(program, GL_LINK_STATUS, compileResults); return 0; } static int gl_GetUniformLocation(lua_State * L){ int ret = (int) glGetUniformLocationARB((GLhandleARB)lua_tonumber(L,1),(const GLcharARB*) lua_tostring(L,2)); lua_pushnumber(L,ret); return 1; } static int gl_Uniform1f(lua_State * L){ glUniform1fARB((GLint)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2)); return 0; } static int gl_Uniform1i(lua_State * L){ glUniform1iARB((GLint)lua_tonumber(L,1),(GLint)lua_tonumber(L,2)); return 0; } static int gl_Uniform2f(lua_State * L){ glUniform2fARB((GLint)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2),(GLfloat)lua_tonumber(L,3)); return 0; } static int gl_Uniform2i(lua_State * L){ glUniform2iARB((GLint)lua_tonumber(L,1),(GLint)lua_tonumber(L,2),(GLint)lua_tonumber(L,3)); return 0; } static int gl_Uniform3f(lua_State * L){ glUniform3fARB((GLint)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2),(GLfloat)lua_tonumber(L,3),(GLfloat)lua_tonumber(L,4)); return 0; } static int gl_Uniform3i(lua_State * L){ glUniform3iARB((GLint)lua_tonumber(L,1),(GLint)lua_tonumber(L,2),(GLint)lua_tonumber(L,3),(GLint)lua_tonumber(L,4)); return 0; } static int gl_Uniform4f(lua_State * L){ glUniform4fARB((GLint)lua_tonumber(L,1),(GLfloat)lua_tonumber(L,2),(GLfloat)lua_tonumber(L,3),(GLfloat)lua_tonumber(L,4),(GLfloat)lua_tonumber(L,5)); return 0; } static int gl_Uniform4i(lua_State * L){ glUniform4iARB((GLint)lua_tonumber(L,1),(GLint)lua_tonumber(L,2),(GLint)lua_tonumber(L,3),(GLint)lua_tonumber(L,4),(GLint)lua_tonumber(L,5)); return 0; } static int gl_ActiveTexture(lua_State * L){ glActiveTextureARB((GLenum) lua_tonumber(L,1)); return 0; } static int gl_ClientActivetexture(lua_State * L){ glClientActivetexture((GLenum) lua_tonumber(L,1)); return 0; } static int gl_MultitexCoord2f(lua_State * L){ glMultitexCoord2f((GLenum) lua_tonumber(L,1),(float) lua_tonumber(L,2),(float) lua_tonumber(L,3)); return 0; } static int setFontStyle(lua_State * L){ qFont * _font = __RENDER->font; _font->setStyle(lua_tointeger(L,1)); return 0; } static int getFontStyle(lua_State * L){ qFont * _font = __RENDER->font; int style = _font->getStyle(); lua_pushnumber(L,style); return 1; } static int getGlyphsCached(lua_State * L){ qFont * _font = __RENDER->font; int num = 0; if (_font){ num = _font->getGlyphsCached(); } lua_pushnumber(L,num); return 1; } static int setupView(lua_State * L){ __RENDER->drawPlayerView((int)lua_tonumber(L,1)); return 0; } static int prepareGLSL(lua_State * L){ prepareGLSLFunctions(); return 0; } static int prepareMultiTexturing(lua_State * L){ prepareMultiTexturingFunctions(); return 0; } static int prepareVBO(lua_State * L){ prepareVBOfunctions(); return 0; } static const luaL_reg luaGL[] = { {"Accum",gl_Accum}, {"ActiveTexture",gl_ActiveTexture}, {"AreTexturesResident",gl_AreTexturesResident}, {"AlphaFunc",gl_AlphaFunc}, {"ArrayElement",gl_ArrayElement}, {"AttachObject",gl_AttachObject}, //--------------------------- {"Begin",gl_Begin}, {"BeginCurve",gl_BeginCurve}, {"BeginPolygon",gl_BeginPolygon}, {"BeginSurface",gl_BeginSurface}, {"BeginTrim",gl_BeginTrim}, {"BindTexture",gl_BindTexture}, {"Bitmap",gl_Bitmap}, {"BlendColorEXT",gl_BlendColorEXT}, {"BlendFunc",gl_BlendFunc}, {"Build1DMipmaps",glu_Build1DMipmaps}, {"Build2DMipmaps",glu_Build2DMipmaps}, //--------------------------- {"CallList",gl_CallList}, {"CallLists",gl_CallLists}, {"Clear",gl_Clear}, {"ClearAccum",gl_ClearAccum}, {"ClearColor",gl_ClearColor}, {"ClearDepth",gl_ClearDepth}, {"ClearIndex",gl_ClearIndex}, {"ClearStencil",gl_ClearStencil}, {"ClientActivetexture",gl_ClientActivetexture}, {"ClipPlane",gl_ClipPlane}, {"Color3d",gl_Color3d}, {"Color3dv",gl_Color3dv}, {"Color3f",gl_Color3f}, {"Color3fv",gl_Color3fv}, {"Color4d",gl_Color4d}, {"Color4dv",gl_Color4dv}, {"Color4f",gl_Color4f}, {"Color4fv",gl_Color4fv}, {"ColorMask",gl_ColorMask}, {"ColorMaterial",gl_ColorMaterial}, {"ColorPointer",gl_ColorPointer}, {"CompileShader",gl_CompileShader}, {"CopyPixels",gl_CopyPixels}, {"CopyTexImage1D",gl_CopyTexImage1D}, {"CopyTexImage2D",gl_CopyTexImage2D}, {"CopyTexSubImage1D",gl_CopyTexSubImage1D}, {"CopyTexSubImage2D",gl_CopyTexSubImage2D}, {"CopyTexSubImage1D",gl_CopyTexSubImage1D}, {"CreateProgramObject",gl_CreateProgramObject}, {"CreateShaderObject",gl_CreateShaderObject}, {"CullFace",gl_CullFace}, //--------------------------- {"DeleteLists",gl_DeleteLists}, {"DeleteObject",gl_DeleteObject}, {"DeleteTextures",gl_DeleteTextures}, {"DepthTextures",gl_DepthTextures}, {"DepthFunc",gl_DepthFunc}, {"DepthMask",gl_DepthMask}, {"DepthRange",gl_DepthRange}, {"DetachShader",gl_DetachShader}, {"Disable",gl_Disable}, {"DisableClientState",gl_DisableClientState}, {"DrawArrays",gl_DrawArrays}, {"DrawBuffer",gl_DrawBuffer}, {"DrawElements",gl_DrawElements}, {"DrawPixels",gl_DrawPixels}, //--------------------------- {"EdgeFlag",gl_EdgeFlag}, {"EdgeFlagPointer",gl_EdgeFlagPointer}, {"Enable",gl_Enable}, {"EnableClientState",gl_EnableClientState}, {"End",gl_End}, {"EndList",gl_EndList}, {"ErrorString",glu_ErrorString}, {"EvalCoord",gl_EvalCoord}, {"EvalMesh",gl_EvalMesh}, {"EvalPoint",gl_EvalPoint}, //--------------------------- {"FeedbackBuffer",gl_FeedbackBuffer}, {"Finish",gl_Finish}, {"Flush",gl_Flush}, {"Fog",gl_Fog}, {"FrontFace",gl_FrontFace}, {"Frustum",gl_Frustum}, //--------------------------- {"GenLists",gl_GenLists}, {"GenTextures",gl_GenTextures}, {"Get",gl_Get}, {"GetClipPlane",gl_GetClipPlane}, {"GetError",gl_GetError}, {"GetFontStyle",getFontStyle}, {"GetGlyphsCached",getGlyphsCached}, {"GetImage",gl_GetImage}, {"GetInfoLog",gl_GetInfoLog}, {"GetLight",gl_GetLight}, {"GetMap",gl_GetMap}, {"GetMaterial",gl_GetMaterial}, {"GetPixelMap",gl_GetPixelMap}, {"GetPointer",gl_GetPointer}, {"GetPolygonStipple",gl_GetPolygonStipple}, {"GetString",gl_GetString}, {"GetString2",glu_GetString}, {"GetTessProperty",gl_GetTessProperty}, {"GetTexEnv",gl_GetTexEnv}, {"GetTexGen",gl_GetTexGen}, {"GetTexImage",gl_GetTexImage}, {"GetTexLevelParameter",gl_GetTexLevelParameter}, {"GetTexParameter",gl_GetTexParameter}, {"GetUniformLocation",gl_GetUniformLocation}, //--------------------------- {"Hint",gl_Hint}, //--------------------------- {"Index",gl_Index}, {"IndexMask",gl_IndexMask}, {"IndexPointer",gl_IndexPointer}, {"InitNames",gl_InitNames}, {"InterleavedArrays",gl_InterleavedArrays}, {"IsEnabled",gl_IsEnabled}, {"IsList",gl_IsList}, {"IsTexture",gl_IsTexture}, //--------------------------- {"Lighti",gl_Lighti}, {"Lightf",gl_Lightf}, {"Lightfv",gl_Lightfv}, {"LightModelf",gl_LightModelf}, {"LightModelfv",gl_LightModelfv}, {"LineStipple",gl_LineStipple}, {"LineWidth",gl_LineWidth}, {"LinkProgram",gl_LinkProgram}, {"ListBase",gl_ListBase}, {"LoadFont",gl_load_font}, {"LoadIdentity",gl_LoadIdentity}, {"LoadMatrix",gl_LoadMatrix}, {"LoadName",gl_LoadName}, {"LoadSamplingMatrices",glu_LoadSamplingMatrices}, {"LookAt",glu_LookAt}, //--------------------------- {"Map1",gl_Map1}, {"Map2",gl_Map2}, {"MapGrid",gl_MapGrid}, {"Materialf",gl_Materialf}, {"Materialfv",gl_Materialfv}, {"MatrixMode",gl_MatrixMode}, {"MultMatrix",gl_MultMatrix}, {"MultitexCoord2f",gl_MultitexCoord2f}, //--------------------------- {"NewList",gl_NewList}, {"NewNurbsRenderer",glu_NewNurbsRenderer}, {"NewQuadric",glu_NewQuadric}, {"NewTess",glu_NewTess}, {"NextContour",glu_NextContour}, {"Normal3f",gl_Normal3f}, {"Normal3d",gl_Normal3d}, {"NormalPointer",gl_NormalPointer}, {"NurbsCallback",gl_NurbsCallback}, {"NurbsCurve",gl_NurbsCurve}, {"NurbsProperty",gl_NurbsProperty}, {"NurbsSurface",gl_NurbsSurface}, //--------------------------- {"Ortho",gl_Ortho}, {"Ortho2D",glu_Ortho2D}, //--------------------------- {"PartialDisk",glu_PartialDisk}, {"PassThrough",gl_PassThrough}, {"Perspective",glu_Perspective}, {"PickMatrix",glu_PickMatrix}, {"PixelMap",gl_PixelMap}, {"PixelStore",gl_PixelStore}, {"PixelTransfer",gl_PixelTransfer}, {"PixelZoom",gl_PixelZoom}, {"PointSize",gl_PointSize}, {"PolygonMode",gl_PolygonMode}, {"PolygonOffset",gl_PolygonOffset}, {"PolygonStipple",gl_PolygonStipple}, {"PrepareOrthogonal",gl_PrepareOrthogonal}, {"printf",gl_printf}, {"PrioritizeTextures",gl_PrioritizeTextures}, {"Project",glu_Project}, {"PopAttrib",gl_PopAttrib}, {"PopClientAttrib",gl_PopClientAttrib}, {"PopMatrix",gl_PopMatrix}, {"PopName",gl_PopName}, {"prepareGLSL",prepareGLSL}, {"prepareMultiTexturing",prepareMultiTexturing}, {"prepareVBO",prepareVBO}, {"PushAttrib",gl_PushAttrib}, {"PushClientAttrib",gl_PushClientAttrib}, {"PushMatrix",gl_PushMatrix}, {"PushName",gl_PushName}, {"PwlCurve",glu_PwlCurve}, //--------------------------- {"QuadricCallback",glu_QuadricCallback}, {"QuadricDrawStyle",glu_QuadricDrawStyle}, {"QuadricNormals",glu_QuadricNormals}, {"QuadricOrientation",glu_QuadricOrientation}, {"QuadricTexture",glu_QuadricTexture}, //--------------------------- {"RasterPos",gl_RasterPos}, {"ReadBuffer",gl_ReadBuffer}, {"ReadPixels",gl_ReadPixels}, {"Rect",gl_Rect}, {"RenderMode",gl_RenderMode}, {"Rotatef",gl_Rotatef}, //--------------------------- {"Scalef",gl_Scalef}, {"ScaleImage",glu_ScaleImage}, {"Scissor",gl_Scissor}, {"SelectBuffer",gl_SelectBuffer}, {"SetFontStyle",setFontStyle}, {"SetupView",setupView}, {"ShadeModel",gl_ShadeModel}, {"ShaderSource",gl_ShaderSource}, {"Sphere",glu_Sphere}, {"StartPicking",startPicking}, {"StencilFunc",gl_StencilFunc}, {"StencilMask",gl_StencilMask}, {"StencilOp",gl_StencilOp}, {"StopPicking",stopPicking}, //--------------------------- {"TessBeginContour",glu_TessBeginContour}, {"TessBeginPolygon",glu_TessBeginPolygon}, {"TessCallback",glu_TessCallback}, {"TessEndPolygon",glu_TessEndPolygon}, {"TessNormal",glu_TessNormal}, {"TessProperty",glu_TessProperty}, {"TessVertex",glu_TessVertex}, {"TexCoord2f",gl_TexCoord2f}, {"TexCoordPointer",gl_TexCoordPointer}, {"TexParameteri",gl_TexParameteri}, {"TexEnvf",gl_TexEnvf}, {"TexEnvi",gl_TexEnvi}, {"TexGen",gl_TexGen}, {"TexImage1D",gl_TexImage1D}, {"TexImage2D",gl_TexImage2D}, {"TexParameter",gl_TexParameter}, {"TexSubImage1D",gl_TexSubImage1D}, {"TexSubImage2D",gl_TexSubImage2D}, {"tglyph",gl_tglyph}, {"tprintf",gl_tprintf}, {"tprintfEx",gl_tprintfEx}, {"Translatef",gl_Translatef}, //--------------------------- {"Uniform1f",gl_Uniform1f}, {"Uniform1i",gl_Uniform1i}, {"Uniform2f",gl_Uniform2f}, {"Uniform2i",gl_Uniform2i}, {"Uniform3f",gl_Uniform3f}, {"Uniform3i",gl_Uniform3i}, {"Uniform4f",gl_Uniform4f}, {"Uniform4i",gl_Uniform4i}, {"UnloadProject",glu_UnloadProject}, {"UseProgram",gl_UseProgram}, //--------------------------- {"Vertex2f",gl_Vertex2f}, {"Vertex2i",gl_Vertex2i}, {"Vertex3f",gl_Vertex3f}, {"VertexPointer",gl_VertexPointer}, {"Viewport",gl_Viewport}, //--------------------------- {NULL,NULL} }; void cLuaGL::prepareFunctions(lua_State * Lua){ luaL_openlib(Lua, "gl", luaGL, 0); }
[ "soulik42@89f801e3-d555-0410-a9c1-35b9be595399" ]
[ [ [ 1, 1436 ] ] ]
399edd63c3c537bd555c246837582fd69b199992
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/Vector2.inl
eda44616345079a1f9b749d5bb172544f85c9cfc
[]
no_license
halak/halak-plusplus
d09ba78640c36c42c30343fb10572c37197cfa46
fea02a5ae52c09ff9da1a491059082a34191cd64
refs/heads/master
2020-07-14T09:57:49.519431
2011-07-09T14:48:07
2011-07-09T14:48:07
66,716,624
0
0
null
null
null
null
UTF-8
C++
false
false
2,225
inl
namespace Halak { Vector2::Vector2() : X(0.0f), Y(0.0f) { } Vector2::Vector2(int x, int y) : X(static_cast<float>(x)), Y(static_cast<float>(y)) { } Vector2::Vector2(float x, float y) : X(x), Y(y) { } Vector2::Vector2(const Vector2& original) : X(original.X), Y(original.Y) { } float Vector2::Dot(Vector2 right) const { return (X * right.X) + (Y * right.Y); } Vector2 Vector2::operator + () const { return Vector2(+X, +Y); } Vector2 Vector2::operator - () const { return Vector2(-X, -Y); } Vector2& Vector2::operator = (const Vector2& original) { X = original.X; Y = original.Y; return *this; } Vector2& Vector2::operator += (const Vector2& right) { X += right.X; Y += right.Y; return *this; } Vector2& Vector2::operator -= (const Vector2& right) { X -= right.X; Y -= right.Y; return *this; } Vector2& Vector2::operator *= (float right) { X *= right; Y *= right; return *this; } Vector2& Vector2::operator /= (float right) { X /= right; Y /= right; return *this; } Vector2 Vector2::operator + (const Vector2& right) const { return Vector2(X + right.X, Y + right.Y); } Vector2 Vector2::operator - (const Vector2& right) const { return Vector2(X - right.X, Y - right.Y); } Vector2 Vector2::operator * (float right) const { return Vector2(X * right, Y * right); } Vector2 Vector2::operator / (float right) const { return Vector2(X / right, Y / right); } bool Vector2::operator == (const Vector2& right) const { return X == right.X && Y == right.Y; } bool Vector2::operator != (const Vector2& right) const { return !operator == (right); } Vector2 operator * (float left, const Vector2& right) { return Vector2(left * right.X, left * right.Y); } }
[ [ [ 1, 107 ] ] ]
351b0d8c3d55ef5e653c00edc34f726a3eb1cd6a
f76e8eb54d95cedcc6c4e35d753a4690b8ead68e
/OnePlayer/OnePlayer.cpp
0325b6eb030eb1554189b404f0a73130eec591f9
[]
no_license
Henry-T/one-player
42701d290359adf3ff3545efa0b8514a3929f704
a0b549d3a87290ad4eae07cf6e1fc0a29cade511
refs/heads/master
2021-01-10T17:50:03.155313
2011-04-20T09:59:46
2011-04-20T09:59:46
50,159,785
0
0
null
null
null
null
GB18030
C++
false
false
1,988
cpp
// OnePlayer.cpp : 定义应用程序的类行为。 // #include "stdafx.h" #include "OnePlayer.h" #include "OnePlayerDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // COnePlayerApp BEGIN_MESSAGE_MAP(COnePlayerApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // COnePlayerApp 构造 COnePlayerApp::COnePlayerApp() { // TODO: 在此处添加构造代码, // 将所有重要的初始化放置在 InitInstance 中 } // 唯一的一个 COnePlayerApp 对象 COnePlayerApp theApp; // COnePlayerApp 初始化 BOOL COnePlayerApp::InitInstance() { // 如果一个运行在 Windows XP 上的应用程序清单指定要 // 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式, //则需要 InitCommonControlsEx()。否则,将无法创建窗口。 INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // 将它设置为包括所有要在应用程序中使用的 // 公共控件类。 InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); AfxEnableControlContainer(); // 标准初始化 // 如果未使用这些功能并希望减小 // 最终可执行文件的大小,则应移除下列 // 不需要的特定初始化例程 // 更改用于存储设置的注册表项 // TODO: 应适当修改该字符串, // 例如修改为公司或组织名 SetRegistryKey(_T("应用程序向导生成的本地应用程序")); COnePlayerDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: 在此处放置处理何时用“确定”来关闭 // 对话框的代码 } else if (nResponse == IDCANCEL) { // TODO: 在此放置处理何时用“取消”来关闭 // 对话框的代码 } // 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序, // 而不是启动应用程序的消息泵。 return FALSE; }
[ [ [ 1, 78 ] ] ]
510eb05e2e21cd82faa96b9b90ade9d889e12c1d
1c9f99b2b2e3835038aba7ec0abc3a228e24a558
/Projects/elastix/elastix_sources_v4/src/Components/Optimizers/AdaptiveStochasticGradientDescent/elxAdaptiveStochasticGradientDescent.cxx
0091e632ad371fd6f1af39e1515601fb55983d1a
[]
no_license
mijc/Diploma
95fa1b04801ba9afb6493b24b53383d0fbd00b33
bae131ed74f1b344b219c0ffe0fffcd90306aeb8
refs/heads/master
2021-01-18T13:57:42.223466
2011-02-15T14:19:49
2011-02-15T14:19:49
1,369,569
0
0
null
null
null
null
UTF-8
C++
false
false
684
cxx
/*====================================================================== This file is part of the elastix software. Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. ======================================================================*/ #include "elxAdaptiveStochasticGradientDescent.h" elxInstallMacro( AdaptiveStochasticGradientDescent );
[ [ [ 1, 17 ] ] ]
35c118f4cae12a26ae5f275b99182ca3236cdbd5
08d0c8fae169c869d3c24c7cdfb4cbcde4976658
/Timer.cpp
f580b50094b78f43c785ed0a8e01e514a9e7c913
[]
no_license
anelson/asynciotest
6b24615b69007cb4fa4b1a5e31dd933b638838ff
e79cea40e1595468401488accc27229a4aedd899
refs/heads/master
2016-09-09T19:35:15.153615
2010-11-07T18:40:56
2010-11-07T18:40:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
774
cpp
#include "StdAfx.h" #include ".\timer.h" Timer::Timer() { LARGE_INTEGER zero = {0}; m_value = zero; } Timer::Timer(const LARGE_INTEGER& value) { m_value = value; } Timer::Timer(const Timer& src) { m_value = src.m_value; } Timer::~Timer(void) { } // Computes the time between two timers Timer Timer::operator-(const Timer& rhs) { LARGE_INTEGER diff; diff.QuadPart = m_value.QuadPart - rhs.m_value.QuadPart; return Timer(diff); } // Computers the number of seconds represented by the timer value Timer::operator double() { return Seconds(); } double Timer::Seconds() { LARGE_INTEGER freq = {0}; ::QueryPerformanceFrequency(&freq); return static_cast<double>(m_value.QuadPart) / static_cast<double>(freq.QuadPart); }
[ [ [ 1, 41 ] ] ]
4f72859d9d2de2329cc18d3f786bf4a8633f24f1
7dd19b99378bc5ca4a7c669617a475f551015d48
/openclient/rtsp_stack/DvrWnd.cpp
2b4f7b03cca189ae24f87793b33198882d2ef1cc
[]
no_license
Locnath/openpernet
988a822eb590f8ed75f9b4e8c2aa7b783569b9da
67dad1ac4cfe7c336f8a06b8c50540f12407b815
refs/heads/master
2020-06-14T14:32:17.351799
2011-06-23T08:51:04
2011-06-23T08:51:04
41,778,769
0
0
null
null
null
null
UTF-8
C++
false
false
1,921
cpp
#include <stdio.h> #include <wtypes.h> #include <string.h> #include "HikData.h" //extern HINSTANCE hookInst; static LRESULT CALLBACK WndProc(HWND hWnd, UINT message,WPARAM wParam, LPARAM lParam) { char msg[256]; switch (message) { case WM_DVR_MSG: sprintf(msg, "WM_DVR_MSG, lParam = %d\n", lParam); OutputDebugString("OnDvrMsg\n"); break; } return 0; } void Hik_ReleaseInstance(HikInstance* inst) { DestroyWindow(inst->hWnd); delete inst; } HWND CreateWnd() { WNDCLASSEX wc; HWND tmp; static BOOL reg = FALSE; wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = (WNDPROC)WndProc; wc.hInstance = hookInst; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)COLOR_WINDOW; wc.lpszClassName = "AnyWnd"; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszMenuName = "Menu"; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if (!reg) { if (!RegisterClassEx(&wc)) { DWORD err = GetLastError(); return NULL; } } reg = TRUE; tmp = CreateWindowEx(NULL,"AnyWnd","", WS_OVERLAPPEDWINDOW,CW_USEDEFAULT, CW_USEDEFAULT,CW_USEDEFAULT, CW_USEDEFAULT,NULL,NULL,hookInst,NULL); return tmp; } DWORD WINAPI MessageLoop(LPVOID pParam) { MSG msg; HikInstance* pInst = (HikInstance*)pParam; pInst->hWnd = CreateWnd(); pInst->state = HikInstance_Running; while (GetMessage(&msg, pInst->hWnd, NULL, NULL) && pInst->state != HikInstance_Quit) { TranslateMessage(&msg); DispatchMessage(&msg); } Hik_ReleaseInstance(pInst); return 0; } void StopHikMessageLoop(HikInstance* inst) { inst->state = HikInstance_Quit; ::PostMessage(inst->hWnd, WM_QUIT, 0, 0); }
[ [ [ 1, 88 ] ] ]
fca3d4d830b27b45c0d49af971f20eb73dfe3a79
5750620062af54ed24792c39d0bf19a6f8f1e3bf
/src/crypter.cpp
439a38cebf6db48e3dd0ec6f9f8a0d8a76f10afa
[]
no_license
makomk/soldcoin
4088e49928efe7436eee8bae40b0b1b9ce9e2720
f964acdd1a76d58f7e27e386fffbed22a1916307
refs/heads/master
2021-01-17T22:18:53.603480
2011-09-04T19:29:57
2011-09-04T19:29:57
2,344,688
0
0
null
null
null
null
UTF-8
C++
false
false
4,692
cpp
// Copyright (c) 2011 The SolidCoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <openssl/aes.h> #include <openssl/evp.h> #include <vector> #include <string> #include "headers.h" #ifdef __WXMSW__ #include <windows.h> #endif #include "crypter.h" #include "main.h" #include "util.h" bool CCrypter::SetKeyFromPassphrase(const std::string& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod) { if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE) return false; // Try to keep the keydata out of swap (and be a bit over-careful to keep the IV that we don't even use out of swap) // Note that this does nothing about suspend-to-disk (which will put all our key data on disk) // Note as well that at no point in this program is any attempt made to prevent stealing of keys by reading the memory of the running process. mlock(&chKey[0], sizeof chKey); mlock(&chIV[0], sizeof chIV); int i = 0; if (nDerivationMethod == 0) i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0], (unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV); if (i != WALLET_CRYPTO_KEY_SIZE) { memset(&chKey, 0, sizeof chKey); memset(&chIV, 0, sizeof chIV); return false; } fKeySet = true; return true; } bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV) { if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE) return false; // Try to keep the keydata out of swap // Note that this does nothing about suspend-to-disk (which will put all our key data on disk) // Note as well that at no point in this program is any attempt made to prevent stealing of keys by reading the memory of the running process. mlock(&chKey[0], sizeof chKey); mlock(&chIV[0], sizeof chIV); memcpy(&chKey[0], &chNewKey[0], sizeof chKey); memcpy(&chIV[0], &chNewIV[0], sizeof chIV); fKeySet = true; return true; } bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext) { if (!fKeySet) return false; // max ciphertext len for a n bytes of plaintext is // n + AES_BLOCK_SIZE - 1 bytes int nLen = vchPlaintext.size(); int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0; vchCiphertext = std::vector<unsigned char> (nCLen); EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV); EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen); EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen); EVP_CIPHER_CTX_cleanup(&ctx); vchCiphertext.resize(nCLen + nFLen); return true; } bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext) { if (!fKeySet) return false; // plaintext will always be equal to or lesser than length of ciphertext int nLen = vchCiphertext.size(); int nPLen = nLen, nFLen = 0; vchPlaintext = CKeyingMaterial(nPLen); EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV); EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen); EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen); EVP_CIPHER_CTX_cleanup(&ctx); vchPlaintext.resize(nPLen + nFLen); return true; } bool EncryptSecret(CKeyingMaterial& vMasterKey, const CSecret &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext) { CCrypter cKeyCrypter; std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE); if(!cKeyCrypter.SetKey(vMasterKey, chIV)) return false; return cKeyCrypter.Encrypt((CKeyingMaterial)vchPlaintext, vchCiphertext); } bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CSecret& vchPlaintext) { CCrypter cKeyCrypter; std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE); if(!cKeyCrypter.SetKey(vMasterKey, chIV)) return false; return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext)); }
[ [ [ 1, 132 ] ] ]
04e33a957b61b1ec25ea6828934dd8e895c35481
ed9ecdcba4932c1adacac9218c83e19f71695658
/CJEngine_2010/CJEngine/CJEngine/Texture.cpp
63df89827419d5ca26e99ac2ce58dfabc6861df5
[]
no_license
karansapra/futurattack
59cc71d2cc6564a066a8e2f18e2edfc140f7c4ab
81e46a33ec58b258161f0dd71757a499263aaa62
refs/heads/master
2021-01-10T08:47:01.902600
2010-09-20T20:25:04
2010-09-20T20:25:04
45,804,375
0
0
null
null
null
null
UTF-8
C++
false
false
1,180
cpp
#include "./Texture.h" #include "./Core.h" Texture::Texture(const char * filename) { data_ = NULL; format_ = 0; size_t size; wchar_t wfilename[256]; mbstowcs_s(&size,wfilename,256,filename,256); Gdiplus::Bitmap bmp(wfilename); width_ = bmp.GetWidth(); height_ = bmp.GetHeight(); if (width_==0 || height_==0) throw Exception("Texture::Texture : File not handled"); Gdiplus::Rect locked_region(0,0,width_,height_); Gdiplus::BitmapData data; if (bmp.LockBits(&locked_region,Gdiplus::ImageLockModeRead,PixelFormat32bppARGB,&data)!=Gdiplus::Ok) throw Exception("Texture::Texture : Can't read file"); format_ = 4; stride_ = data.Stride; data_ = new unsigned char[stride_*height_]; CopyMemory(data_,data.Scan0,stride_*height_); bmp.UnlockBits(&data); glGenTextures(1,&gltexture_id_); glBindTexture(GL_TEXTURE_2D,gltexture_id_); glTexImage2D(GL_TEXTURE_2D,0,4,width_,height_,0,GL_BGRA_EXT,GL_UNSIGNED_BYTE,data_); delete[] data_; } Texture::~Texture(void) { glDeleteTextures(1,&gltexture_id_); } unsigned int Texture::GetWidth() { return width_; } unsigned int Texture::GetHeight() { return height_; }
[ "clems71@52ecbd26-af3e-11de-a2ab-0da4ed5138bb" ]
[ [ [ 1, 49 ] ] ]
3c8f0bbfa5ed151cb291319601189d5d51217895
ffa46b6c97ef6e0c03e034d542fa94ba02d519e5
/qpropertydialog.h
0fa72f2801264cdd49f8fe2664d5096c3acc1e24
[]
no_license
jason-cpc/chmcreator
50467a2bc31833aef931e24be1ac68f5c06efd97
5da66666a9df47c5cf67b71bfb115b403f41b72b
refs/heads/master
2021-12-04T11:22:23.616758
2010-07-20T23:50:15
2010-07-20T23:50:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
980
h
#ifndef TABDIALOG_H #define TABDIALOG_H #include <QtGui> QT_BEGIN_NAMESPACE class QDialogButtonBox; class QFileInfo; class QTabWidget; QT_END_NAMESPACE //! [0] class GeneralTab : public QWidget { Q_OBJECT public: GeneralTab(const QFileInfo &fileInfo, QWidget *parent = 0); }; //! [0] //! [1] class FilesTab : public QWidget { Q_OBJECT public: FilesTab(const QFileInfo &fileInfo, QWidget *parent = 0); }; //! [1] //! [2] class ComplierTab : public QWidget { Q_OBJECT public: ComplierTab(const QFileInfo &fileInfo, QWidget *parent = 0); }; class WindowTab : public QWidget { Q_OBJECT public: WindowTab(const QFileInfo &fileInfo, QWidget *parent = 0); }; class QPropertyDialog : public QDialog { Q_OBJECT public: QPropertyDialog(const QString &fileName, QWidget *parent = 0); private: QTabWidget *tabWidget; QDialogButtonBox *buttonBox; }; //! [3] #endif
[ "zhurx4g@35deca34-8bc2-11de-b999-7dfecaa767bb" ]
[ [ [ 1, 64 ] ] ]
fb575a3160406ec68ce0c398467a08022a015791
ad9f0e8b1b5ffae0685027b897032272a4b55acd
/hex grid node crafter/hex grid node crafter/unitClass.h
ee01fbc60c6a3adecdf42c16465991ddb06d5af4
[]
no_license
robertmcconnell2007/chickamauga
33c36f61f9a467f0cca56c0ea9914ab57da98556
1883d055482973ba421e303661ce0acd529ca886
refs/heads/master
2021-01-23T00:14:57.431579
2010-08-31T19:36:15
2010-08-31T19:36:15
32,115,025
0
0
null
null
null
null
UTF-8
C++
false
false
6,988
h
#pragma once #include "sdl/SDL.h" #include "GraphicsLoader.h" #include <fstream> struct vector2d { int x; int y; }; enum terrainTypes; struct map_node; struct node_edge; class mapSuperClass; class unitClass { private: int power; SDL_Rect unitRect; vector2d position; public: unitClass(); int getX(){return position.x;} int getY(){return position.y;} int getPower(){return power;} void setPower(int p){power=p;} SDL_Rect getSize(); void setPosition(int,int); void drawUnit(int xShift,int yShift,int mapWidth,int mapHeight, SDL_Surface* a_screen,SDL_Surface *armyColors); }; unitClass::unitClass() { //power=3; unitRect.x=unitRect.y=0; unitRect.h=unitRect.w=25; //position.x=position.y=2; } void unitClass::setPosition(int nX,int nY) { position.x=nX; position.y=nY; } SDL_Rect unitClass::getSize() { return unitRect; } void unitClass::drawUnit(int screenShiftx,int screenShifty,int mapWidth,int mapHeight,SDL_Surface *a_screen,SDL_Surface *armyColors) { for(int i = 0; i < mapWidth; ++i) { for(int k = 0; k < mapHeight; ++k) { if(position.x-1==k&&position.y-1==i) { if(i%2==0) { drawATile(armyColors,&unitRect,power-1,a_screen, (i * 50) - (i*12) + screenShiftx+12, k * 44 + screenShifty+10); } else { drawATile(armyColors,&unitRect,power-1,a_screen, (i * 50) - (i*12) + screenShiftx+12, k * 44 + screenShifty+30); } } } } } class armyClass { private: SDL_Surface *armyColors; public: unitClass *armyArray; int size; armyClass(int); armyClass(char * unitFile,char * armyColorFile); void drawArmy(int xShift,int yShift,int mapWidth,int mapHeight, SDL_Surface* a_screen); }; armyClass::armyClass(int s) { size=s; armyArray=new unitClass[size]; for(int i=0; i<size; i++) { armyArray[i].setPosition(rand()%24+1,rand()%27+1); armyArray[i].setPower(rand()%6+1); } armyArray[0].setPosition(0,0); armyArray[0].setPower(7); } armyClass::armyClass(char * fileName, char * armyColorFile) { int px,py,pow; ifstream infile; infile.open(fileName); infile>>size; armyArray=new unitClass[size]; for(int i=0; i<size; i++) { infile>>py; infile>>px; infile>>pow; armyArray[i].setPosition(px,py); armyArray[i].setPower(pow); } infile.close(); armyColors=load_my_image(armyColorFile); } void armyClass::drawArmy(int xShift,int yShift,int mapWidth,int mapHeight, SDL_Surface* a_screen) { for(int i=0; i<size; i++) { armyArray[i].drawUnit(xShift,yShift,mapWidth,mapHeight,a_screen,armyColors); } } int checkEdge(node_edge* edge, int pos) { if(edge == NULL) return -1; map_node* nodePointer; if(pos > 2) nodePointer = edge->lowerNode; else nodePointer = edge->upperNode; if(nodePointer->enemy) { return -2; } int numOccupy = nodePointer->numOfUnits; if(numOccupy >= 2) return -1; int movementRequired = 0; bool cleartype = false; bool foresttype = false; bool roughtype = false; bool roughforesttype = false; bool rivertype = false; bool roadtype = edge->road_edge; bool trailtype = edge->trail_edge; bool fordtype = edge->ford_edge; bool creektype = edge->creek_edge; bool bridgetype = edge->bridge_edge; if(nodePointer->type == clear) cleartype = true; if(nodePointer->type == forest) foresttype = true; if(nodePointer->type == rough) roughtype = true; if(nodePointer->type == roughForest) roughforesttype = true; if(nodePointer->type == river) rivertype = true; if(creektype || rivertype) { movementRequired = 7; } else if(cleartype || roadtype) { movementRequired = 1; } else if(trailtype) { movementRequired = 2; } else if(foresttype || roughtype) { movementRequired = 3; } else if(roughforesttype) { movementRequired = 6; } if(fordtype) { movementRequired += 1; } return movementRequired; } void moveTo(map_node* node,int movement) { node->movement = movement; if(movement == 0) return; int tempMove; for(int i = 0; i < 6; i++) { tempMove = checkEdge(node->nodeEdges[i],i); if(tempMove != -1) { if(i > 2) { if(node->nodeEdges[i]->lowerNode->movement >= 0 && tempMove != -2 && tempMove != -1 && movement-tempMove > node->nodeEdges[i]->lowerNode->movement) { moveTo(node->nodeEdges[i]->lowerNode,movement-tempMove); } else if(tempMove != -2 && tempMove != -1 && movement-tempMove >= 0) { moveTo(node->nodeEdges[i]->lowerNode,movement-tempMove); } else if(tempMove != -1 && movement-tempMove >= 0) { moveTo(node->nodeEdges[i]->lowerNode,0); } } else { if(node->nodeEdges[i]->upperNode->movement >= 0 && tempMove != -2 && tempMove != -1 && movement-tempMove > node->nodeEdges[i]->upperNode->movement) { moveTo(node->nodeEdges[i]->upperNode,movement-tempMove); } else if(tempMove != -2 && tempMove != -1 && movement-tempMove >= 0) { moveTo(node->nodeEdges[i]->upperNode,movement-tempMove); } else if(tempMove != -1 && movement-tempMove >= 0) { moveTo(node->nodeEdges[i]->upperNode,0); } } } } } void setEnemyNodes(armyClass enemyArmy, mapSuperClass* map) { for(int k = 0; k < enemyArmy.size; k++) { map->setEnemy(enemyArmy.armyArray[k].getX()-1,enemyArmy.armyArray[k].getY()-1); } } void checkUnitStacks(mapSuperClass* map, armyClass first, armyClass second) { map_node** mapPointer = map->getMap(); for(int i = 0; i < map->height; i++) { for(int j = 0; j < map->width; j++) { for(int f = 0; f < first.size; f++) { if(first.armyArray[f].getX()-1 == j && first.armyArray[f].getY()-1 == i) { mapPointer[i][j].numOfUnits += 1; } } for(int s = 0; s < second.size; s++) { if(second.armyArray[s].getX()-1 == j && second.armyArray[s].getY()-1 == i) { mapPointer[i][j].numOfUnits += 1; } } } } } bool firstClick(mapSuperClass* map, map_node* node, armyClass currentArmy, armyClass enemyArmy) { map->clearMovement(); checkUnitStacks(map,currentArmy,enemyArmy); for(int k = 0; k < currentArmy.size; k++) { if(currentArmy.armyArray[k].getY()-1 == node->col && currentArmy.armyArray[k].getX()-1 == node->row) { setEnemyNodes(enemyArmy, map); moveTo(node,6); return true; } } map->clearEnemy(); map->clearMovement(); return false; } bool secondClick(mapSuperClass* map, map_node* node, armyClass currentArmy, armyClass enemyArmy) { for(int k = 0; k < currentArmy.size; k++) { if(currentArmy.armyArray[k].getY()-1 == node->col && currentArmy.armyArray[k].getX()-1 == node->row) { //move unit code here return true; } } return false; } void cancelClick(mapSuperClass* map, map_node* node, armyClass currentArmy, armyClass enemyArmy) { map->clearEnemy(); map->clearMovement(); }
[ "ignatusfordon@40b09f04-00bc-11df-b8ab-b3eb4b1fa784", "robertmcconnell2007@40b09f04-00bc-11df-b8ab-b3eb4b1fa784" ]
[ [ [ 1, 1 ], [ 3, 300 ] ], [ [ 2, 2 ] ] ]
537b76b828d4205f52322838f5d424c22d93a44b
2f77d5232a073a28266f5a5aa614160acba05ce6
/01.DevelopLibrary/03.Code/UI/SmsFindResultWnd.cpp
f6bb4bddc4a74fd6618cea606625463adeb33978
[]
no_license
radtek/mobilelzz
87f2d0b53f7fd414e62c8b2d960e87ae359c81b4
402276f7c225dd0b0fae825013b29d0244114e7d
refs/heads/master
2020-12-24T21:21:30.860184
2011-03-26T02:19:47
2011-03-26T02:19:47
58,142,323
0
0
null
null
null
null
GB18030
C++
false
false
3,577
cpp
#include "stdafx.h" #include "resource.h" #include "SmsFindResultWnd.h" #include "SmsLookMsgDetailWnd.h" class ListItemData { public: CMzString StringTitle; // 项的主文本 CMzString StringDescription; // 项的描述文本 BOOL Selected; // 项是否被选中 }; ///////////////////CSmsLookCtorWnd/////////////////////////////////////////////////////// CSmsFindResultWnd::CSmsFindResultWnd(void) { } CSmsFindResultWnd::~CSmsFindResultWnd(void) { } BOOL CSmsFindResultWnd::OnInitDialog() { if ( !CEasySmsWndBase::OnInitDialog() ) { return FALSE; } SetWindowText( L"查找结果" ); return SubInitialize(); } void CSmsFindResultWnd::OnMzCommand( WPARAM wParam, LPARAM lParam ) { UINT_PTR id = LOWORD( wParam ); switch(id) { case MZ_IDC_SMS_UNREAD_TOOLBAR: { int nIndex = lParam; if ( 2 == nIndex ) { this->EndModal( ID_CANCEL ); } else if ( 0 == nIndex ) { //选项 // 使用对话框方式弹出 GridMenu if ( m_GridMenu.IsContinue() ) { m_GridMenu.EndGridMenu(); } else { m_GridMenu.TrackGridMenuDialog( m_hWnd, MZM_HEIGHT_TOOLBARPRO ); } } break; } // 处理 GridMenu 的命令消息 case MZ_IDC_FIND_RESULT_BACK: { if ( m_GridMenu.IsContinue() ) { m_GridMenu.EndGridMenu(); } } default: break; } } BOOL CSmsFindResultWnd::SubInitialize() { //ini list m_list_base.SetID( MZ_IDC_SMS_UNREAD_LIST ); m_list_base.EnableDragModeH(true); m_list_base.SetMultiSelectMode( UILISTEX_MULTISELECT_LEFT ); m_list_base.SetSplitLineMode ( UILISTEX_SPLITLINE_RIGHT ); AddUiWin( &m_list_base ); //ini toolbar m_toolBar_base.SetID( MZ_IDC_SMS_UNREAD_TOOLBAR ); m_toolBar_base.SetButton( 0, true, true, L"选项" ); AddUiWin( &m_toolBar_base ); //Ini GridMenu m_GridMenu.AppendMenuItem(MZ_IDC_FIND_RESULT_ALL_SELECT, L"全选" ); m_GridMenu.AppendMenuItem(MZ_IDC_FIND_RESULT_DELETE, L"删除" ); m_GridMenu.AppendMenuItem(MZ_IDC_FIND_RESULT_LOCK, L"加锁" ); m_GridMenu.AppendMenuItem(MZ_IDC_FIND_RESULT_BACK, L"返回" ); /////////////test///////////////////////////////////////////////////////////// CMzString content = L"短信内容 SmsContent%d:"; CMzString stime = L"12:20"; CMzString content1(30); for (int i = 0; i < 100; i++) { swprintf(content1.C_Str(),content.C_Str(),i); ListItemEx* item = new ListItemEx; item->m_pData = (void*)i; item->m_textPostscript1 = stime.C_Str(); if (i == 2) { item->m_textDescription = L"content: I&apos;m dying to see u! what? I couldn&apos;t get it"; } else if(i == 6) { item->m_textDescription = L"我这里天快要黑了,那里呢?我这里天气凉凉的那里呢? 我这里一切都变了,而那你呢?"; } else { item->m_textDescription = content1.C_Str(); } item->m_pImgFirst = m_imgContainer_base.LoadImage(MzGetInstanceHandle(), IDR_PNG_CTR_LIST_READ, true); item->m_itemBgType = UILIST_ITEM_BGTYPE_YELLOW; m_list_base.AddItem(item); } /////////////test///////////////////////////////////////////////////////////// return TRUE; } void CSmsFindResultWnd::DoSthForItemBtnUpSelect( ListItemEx* pItem ) { CSmsLookMsgDetailWnd clCSmsLookMsgDetailWnd; //Test // wchar_t chTemp[ 256 ] = L"从查找结果画页进入这个页面"; // clCSmsLookMsgDetailWnd.SetListItem( pItem ); int iRlt = DoModalBase( &clCSmsLookMsgDetailWnd ); if ( ID_CASCADE_EXIT == iRlt ) { ReturnToMainWnd(); } }
[ [ [ 1, 155 ] ] ]
2bf47a0549b8c6d388ba418b846d3ba7ff22047c
cecdfda53e1c15e7bd667440cf5bf8db4b3d3e55
/Map Editor/MyFont.h
e1528f1c513c4848e2cc465479f4b8284d749406
[]
no_license
omaskery/mini-stalker
f9f8713cf6547ccb9b5e51f78dfb65a4ae638cda
954e8fce9e16740431743f020c6ddbc866e69002
refs/heads/master
2021-01-23T13:29:26.557156
2007-08-04T12:44:52
2007-08-04T12:44:52
33,090,577
1
0
null
null
null
null
UTF-8
C++
false
false
897
h
#include <string> class Text { SDL_Surface *font; public: Text(const std::string &font_file) { font = SDL_LoadBMP(font_file.c_str()); if(font) SDL_SetColorKey(font,SDL_SRCCOLORKEY|SDL_RLEACCEL,SDL_MapRGB(font->format,0,0,0)); } void draw(SDL_Surface *s, int x, int y, const std::string &text, int alpha = 255) { if(alpha > 255) alpha = 255; else if(alpha < 0) alpha = 0; if(!alpha) return; SDL_SetAlpha(font,SDL_SRCALPHA|SDL_RLEACCEL,alpha); int src_x = 0; int x_offset = 0; for(unsigned int i = 0; i < text.size(); ++i) { char c = text[i]; SDL_Rect src, dest; src.x = (int)c * 9; src.y = 0; src.w = 9; src.h = 13; dest.x = x+x_offset; dest.y = y; dest.w = 9; dest.h = 13; if(src_x != -1) SDL_BlitSurface(font,&src,s,&dest); x_offset += 9; } SDL_SetAlpha(font,0,alpha); } };
[ "ollie.the.pie.lord@823218a8-ad34-0410-91fc-f9441fec9dcb" ]
[ [ [ 1, 44 ] ] ]
af37b8c93e528498883a0a3d0983948237c22dd8
7cf0bc0c3120c2040c3ed534421082cd93f0242f
/ab_mfc/ab_mfc/serversocket.cpp
abb6d6d024cd6ac976abacab177b926bb4b0fbde
[]
no_license
zephyrer/ab-mfc
3d7be0283fa3fff3dcb7120fc1544e60a3811d88
f228b27a6fdbcb55f481155e9e9d77302335336a
refs/heads/master
2021-01-13T02:15:55.470629
2010-12-10T12:16:23
2010-12-10T12:16:23
40,066,957
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,881
cpp
#include "stdafx.h" #include "serversocket.h" ServerSocket::ServerSocket() { if(WSAStartup(MAKEWORD(2,2), &WSAData) != 0) //³õʼ»¯Ì×½Ó×Ö { printf("sock init fail!\n"); } else printf("sock init success!\n"); } ServerSocket::~ServerSocket() { Close(); closesocket(sockfd); WSACleanup(); } int UDPserver::Socket() { sockfd = socket(AF_INET , SOCK_DGRAM, 0); return sockfd; } int TCPserver::Socket() { sockfd = socket(AF_INET, SOCK_STREAM, 0); return sockfd; } int ServerSocket::Socket() { sockfd = socket(AF_INET, SOCK_STREAM, 0); return sockfd; } void ServerSocket::SetPort(unsigned short in_port) { struct hostent *host; char strIP[128]; gethostname(strIP, 128); host = gethostbyname(strIP); my_addr.sin_family = AF_INET; port = in_port; my_addr.sin_port = htons(port); my_addr.sin_addr.S_un.S_addr = inet_addr(inet_ntoa(*(struct in_addr*)*host->h_addr_list)); } void ServerSocket::SetRemotePort(unsigned short in_port) { their_addr.sin_port = htons(in_port); } unsigned short ServerSocket::GetRemotePort(){ return ntohs(get_addr.sin_port); } bool ServerSocket::Bind() { if(bind(sockfd, (struct sockaddr FAR *)&my_addr, sizeof(my_addr)) == SOCKET_ERROR) { perror("bind error!\n"); return false; } return true; } int ServerSocket::Recvfrom(char *buf,int len) { int numbytes; int addr_len = sizeof(get_addr); numbytes = recvfrom(sockfd, buf, len, 0, (struct sockaddr *)&get_addr, &addr_len); if(numbytes == -1) { return false; } buf[numbytes] = '\0'; return numbytes; } int ServerSocket::Sendto(const char *buf,int len) { return sendto(sockfd,buf, len, 0,(struct sockaddr *)&their_addr,sizeof(struct sockaddr)); } void ServerSocket::Close() { closesocket(new_fd); } void ServerSocket::Listen() { if(listen(sockfd, 10)== -1 ) perror("listen err!\n"); } void ServerSocket::Accept() { int size = sizeof(struct sockaddr_in); new_fd = accept(sockfd, (struct sockaddr *)&get_addr, &size); if(new_fd==-1) { perror("accept err!\n"); exit(1); } } int ServerSocket::Recv(char *buf,int len) { return recv(new_fd, buf, len, 0); } int ServerSocket::Send(const char * buf, int len) { return send(new_fd, buf, len, 0); } bool ServerSocket::Connect() { if(connect(sockfd,(struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == false) return false; return true; }
[ [ [ 1, 142 ] ] ]
f2dab7a5de95acf1ebe086a4d5654798c192d7b3
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SERenderers/SE_DX10_Renderer/SEDX10RendererRegister.cpp
8392caa9452cf6d85381cda14886fb232936ea41
[]
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
UTF-8
C++
false
false
1,898
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 "SEDX10RendererPCH.h" #include "SEDX10RendererRegister.h" // DX10 Rendering #include "SEDX10FrameBuffer.h" #include "SEDX10Renderer.h" // DX10 Shaders #include "SEDX10Program.h" #include "SEDX10ProgramInterface.h" using namespace Swing; //---------------------------------------------------------------------------- void Swing::SE_DX10Renderer_Register() { // DX10 Rendering SE_REGISTER_INITIALIZE(SEDX10FrameBuffer); SE_REGISTER_INITIALIZE(SEDX10Renderer); SE_REGISTER_INITIALIZE(SEDX10Program); SE_INVOKE_INITIALIZE(SEDX10FrameBuffer); SE_INVOKE_INITIALIZE(SEDX10Renderer); SE_INVOKE_INITIALIZE(SEDX10Program); SE_REGISTER_TERMINATE(SEDX10Renderer); SE_INVOKE_TERMINATE(SEDX10Renderer); // DX10 Shaders SE_REGISTER_STREAM(SEDX10ProgramInterface); SE_INVOKE_STREAM(SEDX10ProgramInterface); } //----------------------------------------------------------------------------
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 51 ] ] ]
64f9fbd8d7f732a3c6f0c0b8dbf3e9a9603be3e7
de0881d85df3a3a01924510134feba2fbff5b7c3
/addons/ofxGui/ofxGuiButton.cpp
d9daa81423acc00f411e710aa5d68389f3fef7a9
[]
no_license
peterkrenn/ofx-dev
6091def69a1148c05354e55636887d11e29d6073
e08e08a06be6ea080ecd252bc89c1662cf3e37f0
refs/heads/master
2021-01-21T00:32:49.065810
2009-06-26T19:13:29
2009-06-26T19:13:29
146,543
1
1
null
null
null
null
UTF-8
C++
false
false
4,265
cpp
/* * ofxGuiButton.cpp * openFrameworks * * Created by Stefan Kirch on 18.06.08. * Copyright 2008 alphakanal. All rights reserved. * */ // ---------------------------------------------------------------------------------------------------- #include "ofxGuiButton.h" // ---------------------------------------------------------------------------------------------------- ofxGuiButton::ofxGuiButton() { mParamType = kofxGui_Object_Button; } // ---------------------------------------------------------------------------------------------------- void ofxGuiButton::init(int id, string name, int x, int y, int width, int height, bool value, int mode) { int textWidth = (name == "") ? 0 : mGlobals->mButtonXText + roundInt(mGlobals->mHeadFont.stringWidth(name)); mParamId = id; mParamName = name; mObjX = x; mObjY = y; mObjWidth = textWidth + width; mObjHeight = height; mMode = mode; setValue(value); setControlRegion(0, 0, width, height); } // ---------------------------------------------------------------------------------------------------- void ofxGuiButton::setValue(bool value) { mValue = value; } // ---------------------------------------------------------------------------------------------------- bool ofxGuiButton::update(int id, int task, void* data, int length) { bool handled = false; if(id == mParamId && length == sizeof(bool)) { setValue(*(bool*)data); handled = true; } return handled; //if(radio == true) //{ setValue(false); } } } // ---------------------------------------------------------------------------------------------------- void ofxGuiButton::draw() { glPushMatrix(); glTranslatef(mObjX, mObjY, 0.0f); if(mParamName != "") //drawParamString(mCtrWidth + mGlobals->mButtonXText, mGlobals->mButtonYText, mParamName, false); ofDrawBitmapString(mParamName, mCtrWidth + mGlobals->mButtonXText +10, mGlobals->mButtonYText+15); ofFill(); // background //glColor4f(mGlobals->mCoverColor.r, mGlobals->mCoverColor.g, mGlobals->mCoverColor.b, mGlobals->mCoverColor.a); glColor4f(0.2,0.2,0.4,0.8); ofRect(mCtrX, mCtrY, mCtrWidth, mCtrHeight); if(mValue == 1) { // handle glColor4f(mGlobals->mButtonColor.r, mGlobals->mButtonColor.g, mGlobals->mButtonColor.b, mGlobals->mButtonColor.a); ofRect(mCtrX , mCtrY, mCtrWidth, mCtrHeight); } ofNoFill(); // frame glColor4f(mGlobals->mFrameColor.r, mGlobals->mFrameColor.g, mGlobals->mFrameColor.b, mGlobals->mFrameColor.a); ofRect(mCtrX, mCtrY, mCtrWidth, mCtrHeight); glPopMatrix(); } // ---------------------------------------------------------------------------------------------------- bool ofxGuiButton::mouseDragged(int x, int y, int button) { return mMouseIsDown; } // ---------------------------------------------------------------------------------------------------- bool ofxGuiButton::mousePressed(int x, int y, int button) { mMouseIsDown = isPointInsideMe(mouseToLocal(x, y)); if(mMouseIsDown) { if(mMode == kofxGui_Button_Trigger) setValue(true); else setValue(!mValue); mGlobals->mListener->handleGui(mParamId, kofxGui_Set_Bool, &mValue, sizeof(bool)); } return mMouseIsDown; } // ---------------------------------------------------------------------------------------------------- bool ofxGuiButton::mouseReleased(int x, int y, int button) { bool handled = mMouseIsDown; if(mMouseIsDown) { if(mMode == kofxGui_Button_Trigger) { setValue(false); mGlobals->mListener->handleGui(mParamId, kofxGui_Set_Bool, &mValue, sizeof(bool)); } mMouseIsDown = false; } return handled; } // ---------------------------------------------------------------------------------------------------- void ofxGuiButton::buildFromXml() { mGlobals->mListener->handleGui(mParamId, kofxGui_Set_Bool, &mValue, sizeof(bool)); } // ---------------------------------------------------------------------------------------------------- void ofxGuiButton::saveToXml() { int id = saveObjectData(); bool value = (mMode == kofxGui_Button_Trigger) ? false : mValue; mGlobals->mXml.setValue("OBJECT:VALUE", value, id); } // ----------------------------------------------------------------------------------------------------
[ [ [ 1, 170 ] ] ]
bddf8ce7075524676b5d8a5e7d6d2a77cab9fdde
c0bd82eb640d8594f2d2b76262566288676b8395
/src/shared/Database/DBC.cpp
2a74d538d6c4b6ac6529fe25324f97072b20e5c7
[ "FSFUL" ]
permissive
vata/solution
4c6551b9253d8f23ad5e72f4a96fc80e55e583c9
774fca057d12a906128f9231831ae2e10a947da6
refs/heads/master
2021-01-10T02:08:50.032837
2007-11-13T22:01:17
2007-11-13T22:01:17
45,352,930
0
1
null
null
null
null
UTF-8
C++
false
false
6,039
cpp
#include "DBC.h" #include <math.h> class DBC; DBC::DBC() { tbl = NULL; db = NULL; loaded = false; format = NULL; } void DBC::Load(const char *filename) { FILE *f = fopen(filename, "rb"); if(!f) { printf("DBC %s Doesnt exist!\n",filename); return; } char buffer[256] = {NULL}; fread(buffer, 4, 1, f); fread(&rows,4, 1, f); fread(&cols, 4, 1, f); fread(&weird2, 4, 1, f); int percol = weird2/cols; fread(&dblength, 4, 1, f); tbl = new unsigned int[rows * cols]; db = new char[dblength]; format = new DBCFmat[cols]; strcpy(name,filename); fread(tbl,rows*cols*4,1,f); fread(db,dblength,1,f); fclose(f); loaded = true; #ifdef DBC_PRINT printf("DBC %s loaded.\n",filename); #endif } void DBC::Lookup(char* out, int row,int col,char isstr,bool onlystr) { int fst = tbl[row*cols+col]; char* str = db+fst; if((fst > 0 && fst < dblength && col > 0 && !onlystr) || isstr == 1) { char bla = *(char*)(db+fst-1); if(bla == '\0' && fst != 1) { printf("%u\n",col); sprintf(out,"%s",str); return; } } sprintf(out,"%u",*(tbl+(row*cols+col))); return; } void DBC::CSV(char* filename, bool info) { if(weird2 != cols*4) filename = strcat(filename,"-NOT.csv"); FILE *f = fopen(filename, "wb"); FILE *out = info ? f : stdout; fprintf(out,"Rows:%u\x0d\x0a",rows); fprintf(out,"Cols:%u\x0d\x0a",cols); fprintf(out,"Weird:%u\x0d\x0a",weird2); fprintf(out,"Theory:%u\x0d\x0a",(weird2 == cols*4)); fprintf(out,"DBlength:%u\x0d\x0a",dblength); fprintf(out,"\x0d\x0a"); for(int i=0; i < rows; i++) { for(int j=0; j < cols; j++) { char* str = new char[65535]; Lookup(str,i,j); fprintf(f,"%s,",str); delete [] str; } fprintf(f,"\x0d\x0a"); } fclose(f); } void DBC::RowToStruct(void* out, int row) { memcpy(out,tbl+(row*cols),weird2); } void DBC::FormatCSV(const char* filename, bool info) { //if(weird2 != cols*4) filename = strcat(filename,"-NOT.csv"); - Cause its a const. FILE *f = fopen(filename, "wb"); FILE *out = info ? f : stdout; fprintf(out,"Rows:%u\x0d\x0a",rows); fprintf(out,"Cols:%u\x0d\x0a",cols); fprintf(out,"Weird:%u\x0d\x0a",weird2); fprintf(out,"Theory:%u\x0d\x0a",(weird2 == cols*4)); fprintf(out,"DBlength:%u\x0d\x0a",dblength); fprintf(out,"\x0d\x0a"); printf("Writing file (%s): 0%%",name); int percent=0,npercent; int fst; for(int i=0; i < rows; i++) { for(int j=0; j < cols; j++) { /*char* str = new char[512]; LookupFormat(str,i,j); fprintf(f,"%s,",str); delete [] str;*/ // Old code -> too slow. keeping it for reference fst = tbl[i*cols+j]; if(format[j] == F_STRING) fprintf(f,"\"%s\"",(char*)(db+fst)); else if(format[j] == F_FLOAT) fprintf(f,"%f",*(float*)&fst); else fprintf(f,"%u",fst); fprintf(f,","); npercent = (int)((float)(i*cols+j)/(float)(rows*cols) * 100); if(npercent > percent) { printf("\rWriting file (%s): %u%%",name,npercent); percent = npercent; } } fprintf(f,"\x0d\x0a"); } printf("\rWriting file (%s): 100%% - Done!\n",name); fclose(f); } void DBC::GuessFormat() { int *ints,*floats,*strings; ints = new int[cols]; memset(ints,0x00,sizeof(int)*cols); floats = new int[cols]; memset(floats,0x00,sizeof(int)*cols); strings = new int[cols]; memset(strings,0x00,sizeof(int)*cols); printf("Guessing format (%s): 0%%",name); int percent=0,npercent; for(int i=0;i<rows;i++) for(int j=0;j<cols;j++) { DBCFmat f = GuessFormat(i,j); if(f == F_STRING) strings[j]++; else if(f == F_INT) ints[j]++; else if(f == F_FLOAT) floats[j]++; npercent = (int)((float)(i*cols+j)/(float)(rows*cols+cols) * 100); if(npercent > percent) { printf("\rGuessing format (%s): %u%%",name,npercent); percent = npercent; } } for(int j=0;j<cols;j++) { if(strings[j] > ints[j]) { if(strings[j] > floats[j]) format[j] = F_STRING; else format[j] = F_FLOAT; } else { if(ints[j] > floats[j]) format[j] = F_INT; else format[j] = F_FLOAT; } npercent = (int)((float)(rows*cols+j)/(float)(rows*cols+cols) * 100); if(npercent > percent) { printf("\r%u%%",npercent); percent = npercent; } } delete [] ints; delete [] floats; delete [] strings; printf("\rGuessing format (%s): 100%% - Done!\n",name); } DBCFmat DBC::GuessFormat(int row, int col) { unsigned int fst = tbl[row*cols+col]; if(fst == 0) return F_NADA; else if(fst == 1) return F_INT; if(fst > 0 && fst < (unsigned int)dblength && col > 0 && *(char*)(db+fst-1) == 0x00) return F_STRING; if(fst > 100000000) return F_FLOAT; return F_INT; } void DBC::LookupFormat(char *out, int row, int col) { int fst = tbl[row*cols+col]; if(format[col] == F_STRING) sprintf(out,"%s",(char*)(db+fst)); else if(format[col] == F_FLOAT) sprintf(out,"%f",*(float*)&fst); else sprintf(out,"%u",fst); } DBC::~DBC() { if(tbl) delete [] tbl; if(db) delete [] db; if(format) delete [] format; }
[ [ [ 1, 215 ] ] ]
1aa8dbf0a37ca00d2ef37626ab20aaefa129134b
83da738aa8446efa499555e0073a7215b3f874a3
/code/MyFrame.cpp
b8082645bdabc4c4bbeb70908ad188b45903aaa5
[]
no_license
duponamk/wxawesomium
38a65d1b775d8c8a2071740324c433ec6bfdce81
05bd19bd9f6abe2d998c1039f7da06b6e76b434e
refs/heads/master
2016-08-11T09:13:37.429058
2009-09-18T12:30:16
2009-09-18T12:30:16
44,711,453
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,382
cpp
///////////// Copyright © 2009 DesuraNet. All rights reserved. ///////////// // // Project : wxAwesomium // File : MyFrame.cpp // Description : // [TODO: Write the purpose of MyFrame.cpp.] // // Created On: 9/18/2009 2:48:33 PM // Created By: Mark Chandler <mailto:[email protected]> //////////////////////////////////////////////////////////////////////////// //#include "common.h" #include "MyFrame.h" BEGIN_EVENT_TABLE( MyFrame, wxFrame ) EVT_BUTTON( wxID_ANY, MyFrame::onButClick ) EVT_RECEIVETITLE( MyFrame::onTitleChange ) EVT_CALLBACK( MyFrame::onJSCallBack ) END_EVENT_TABLE() MyFrame::MyFrame( const wxString& title) : wxFrame( NULL, wxID_ANY, title, wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE|wxWANTS_CHARS ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); wxFlexGridSizer* fgSizer1; fgSizer1 = new wxFlexGridSizer( 2, 1, 0, 0 ); fgSizer1->AddGrowableCol( 0 ); fgSizer1->AddGrowableRow( 1 ); fgSizer1->SetFlexibleDirection( wxBOTH ); fgSizer1->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); wxFlexGridSizer* fgSizer2; fgSizer2 = new wxFlexGridSizer( 1, 2, 0, 0 ); fgSizer2->AddGrowableCol( 0 ); fgSizer2->AddGrowableRow( 0 ); fgSizer2->SetFlexibleDirection( wxBOTH ); fgSizer2->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); m_textCtrl2 = new wxTextCtrl( this, wxID_ANY, wxT("http://lodle.net/moddb/cookie.php"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer2->Add( m_textCtrl2, 0, wxALL|wxEXPAND, 5 ); m_button2 = new wxButton( this, wxID_ANY, wxT("Go"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer2->Add( m_button2, 0, wxTOP|wxBOTTOM|wxRIGHT, 5 ); fgSizer1->Add( fgSizer2, 1, wxEXPAND, 5 ); m_pBrowser = new wxAwesomium( this ); m_pBrowser->registerJSCallBack( "clearBreadCrumbs" ); m_pBrowser->registerJSCallBack( "addBreadCrumb" ); m_pBrowser->addCookie("http://lodle.net/moddb", "TestCookie", "Mmm Cookies!"); fgSizer1->Add( m_pBrowser, 1, wxEXPAND, 5 ); this->SetSizer( fgSizer1 ); this->Layout(); } MyFrame::~MyFrame() { } void MyFrame::onButClick( wxCommandEvent& event ) { m_pBrowser->loadUrl(m_textCtrl2->GetValue()); } void MyFrame::onTitleChange(wxAWSReceiveTitleEvent& event) { this->SetTitle(event.m_szTitle); } void MyFrame::onJSCallBack(wxAWSCallBackEvent& event) { }
[ "lodle.05@87dc4f06-a44e-11de-b1fe-bba1d6bec496" ]
[ [ [ 1, 76 ] ] ]
82eb31e81092371a94a39efb434c78816a2d0a29
d8f64a24453c6f077426ea58aaa7313aafafc75c
/utils/BR5Viewer/TextureLoader.h
7995dc63ddf993e6b4b31c880b76fcb6425830e4
[]
no_license
dotted/wfto
5b98591645f3ddd72cad33736da5def09484a339
6eebb66384e6eb519401bdd649ae986d94bcaf27
refs/heads/master
2021-01-20T06:25:20.468978
2010-11-04T21:01:51
2010-11-04T21:01:51
32,183,921
1
0
null
null
null
null
UTF-8
C++
false
false
1,294
h
#ifndef TEXTURE_LOADER_H #define TEXTURE_LOADER_H namespace loaders { class CTextureLoader { public: CTextureLoader(); ~CTextureLoader(); struct sLoaderResult { POINT texture_dimensions; bool done; sLoaderResult() { done=false; } }; struct sRgbPixel { BYTE r,g,b; sRgbPixel() { r=g=b=0; } sRgbPixel(BYTE *bytes) { this->r=bytes[0]; this->g=bytes[1]; this->b=bytes[2]; } sRgbPixel(BYTE r, BYTE g, BYTE b) { this->r=r; this->g=g; this->b=b; } }; struct sRgbResult { sRgbPixel *rgb; GLint size; GLvoid resetSize(GLint size) { this->size=size; delete rgb; rgb = new sRgbPixel[size*size]; } GLvoid clean() { delete [] rgb; } sRgbResult() { size=0; rgb=NULL; } }; static sLoaderResult buildTexture(const char *file, GLuint &texture, bool trans=false, GLint texture_filter=GL_LINEAR, bool auto_transparent=true, GLubyte R=0, GLubyte G=0, GLubyte B=0, bool full_path=false); // memory leaks will remain if not deleted properly! // texture must be NxN in size static sRgbResult readPixels(char *file); }; }; #endif // TEXTURE_LOADER_H
[ [ [ 1, 81 ] ] ]
428cc15741cdba55e8a116c4b195402f6dc49132
48ab31a0a6a8605d57b5e140309c910f46eb5b35
/Root/Implementation/BerkeleyDatabase/BerkeleyManualIndexCursor.cpp
0da2b242a2d07ecfb75109daedbbc21119b3a783
[]
no_license
firebreath/indexeddb
4c3106027a70e233eb0f91c6e0b5d60847d75800
50136d2fadced369788a42d249157b8a0d06eb88
refs/heads/master
2023-08-31T11:28:42.664028
2011-01-03T23:29:46
2011-01-03T23:29:46
1,218,008
2
1
null
null
null
null
UTF-8
C++
false
false
2,692
cpp
/**********************************************************\ Copyright Brandon Haynes http://code.google.com/p/indexeddb GNU Lesser General Public License \**********************************************************/ #include "BerkeleyManualIndexCursor.h" #include "BerkeleyManualIndex.h" #include "BerkeleyDatabase.h" #include "BerkeleyObjectStore.h" #include "../ImplementationException.h" using boost::mutex; using boost::lock_guard; namespace BrandonHaynes { namespace IndexedDB { namespace Implementation { namespace BerkeleyDB { BerkeleyManualIndexCursor::BerkeleyManualIndexCursor(BerkeleyManualIndex& index, const Key& left, const Key& right, const bool openLeft, const bool openRight, const bool isReversed, const bool omitDuplicates, const bool dataArePrimaryKeys, TransactionContext& transactionContext) : BerkeleyCursor(index.implementation, left, right, openLeft, openRight, isReversed, omitDuplicates, transactionContext), index(index), dataArePrimaryKeys(dataArePrimaryKeys), currentValue(Data::getUndefinedData()) { ensurePrimaryKeyExists(transactionContext); } Data BerkeleyManualIndexCursor::getData(TransactionContext& transactionContext) { ensureOpen(); return currentValue; } bool BerkeleyManualIndexCursor::next(Dbc* cursor, TransactionContext& transactionContext) { return BerkeleyCursor::next(cursor, transactionContext) && ensurePrimaryKeyExists(transactionContext); } bool BerkeleyManualIndexCursor::ensurePrimaryKeyExists(TransactionContext& transactionContext) { Dbt secondaryKey, primaryKeyDbt; Data result = Data::getUndefinedData(); ensureOpen(); try { if(getCursor()->get(&secondaryKey, &primaryKeyDbt, DB_CURRENT) == 0) { Key& primaryKey(BerkeleyDatabase::ToKey(primaryKeyDbt)); if(!index.objectStore.exists(primaryKey, transactionContext)) { index.remove(BerkeleyDatabase::ToKey(secondaryKey), transactionContext); return next(getCursor(), transactionContext); } else currentValue = (dataArePrimaryKeys || primaryKey == Data::getUndefinedData() ? primaryKey : index.objectStore.get(primaryKey, transactionContext)); } } catch(DbDeadlockException& e) { throw ImplementationException("DEADLOCK_ERR", ImplementationException::DEADLOCK_ERR, e.get_errno()); } catch(DbException &e) { throw ImplementationException("UNKNOWN_ERR", ImplementationException::UNKNOWN_ERR, e.get_errno()); } return true; } void BerkeleyManualIndexCursor::remove() { currentValue = Data::getUndefinedData(); BerkeleyCursor::remove(); } } } } }
[ [ [ 1, 81 ] ] ]
7dfb190f63616c8380378291c401b51d3d6bb3cc
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Common/Internal/GeometryProcessing/ConvexHull/hkgpConvexHull.h
d596bf79f0c5db7714b210a84be93b6b9fa21985
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
19,056
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HKGP_CONVEX_HULL_H #define HKGP_CONVEX_HULL_H class hkAabb; class hkPseudoRandomGenerator; struct hkStridedVertices; /// Default cosine of the angle above which two plane are merged. #define HKGPCONVEXHULL_DEFAULT_MIN_COS_ANGLE 0.9999f /// Default thickness used for splitting. #define HKGPCONVEXHULL_DEFAULT_SPLIT_THICKNESS 0.0000001f /// This class handles Convex hull generation. It also exposes utilities such as connectivity, mass properties and Boolean operations. /// Convex hull generation is fast enough to be called at runtime on moderate input size ( < 10000 points ) /// /// It handles convex hull of dimensions up to 3 such as: /// /// - 0D : Point /// - 1D : Line /// - 2D : Plane convex hull /// - 3D : Volume convex hull /// /// Notes A): Internally, the convex hull stores two sets of coordinates for each input point, /// the internal representation may differ slightly from the actual inputs. /// For that reason, some methods need to be called with the coordinates type specified. /// in this case, 'Source' refer to the input coordinates used to build the convex hull. /// /// B): Sources are never modified, including the 'W' component. /// class hkgpConvexHull : public hkReferencedObject { public: HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_GEOMETRY); struct Vertex {}; struct Triangle {}; public: /// Build configuration structure. struct BuildConfig { BuildConfig(); hkBool m_allowLowerDimensions; /// hkReal m_minCosAngle; /// hkBool m_setSourceIndices; /// hkBool m_buildIndices; /// hkBool m_buildMassProperties; /// hkBool m_sortInputs; /// hkBool m_internalInputs; /// /// Internally, the algorithm might modify input coordinates to ensure numerically robust results. /// As a result, the plane equations might not exactly confine the input points set. /// Setting this value to true will make sure the plane equations enclose both sources and internals points representations. (default: false). hkBool m_ensurePlaneEnclosing; }; /// Simplification configuration structure. struct SimplifyConfig { SimplifyConfig(); int m_maxVertices; /// hkBool m_ensureContainment; /// hkReal m_minArea; /// hkReal m_minEdgeLength; /// hkBool m_removeUnreferencedVertices; /// hkBool m_forceRebuild; /// }; /// Absolute scale configuration structure. struct AbsoluteScaleConfig { enum Method { SKM_VERTICES, /// Scale by shifting vertices. SKM_PLANES, /// Scale by shifting planes. }; AbsoluteScaleConfig(); Method m_method; /// hkReal m_minComDistance; /// }; /// Input coordinates to use. enum Inputs { SOURCE_VERTICES, /// INTERNAL_VERTICES, /// }; /// Result of 'classify' and 'splitByPlane'. enum Side { ZERO , /// POSITIVE , /// NEGATIVE , /// CROSSING , /// INVALID /// }; /// User object interface. struct IUserObject { virtual ~IUserObject() {} virtual IUserObject* clone() const=0; virtual void append(const IUserObject* iOther)=0; }; /// Boolean function of convex hulls. struct IBooleanFunction { virtual ~IBooleanFunction() {} virtual hkBool operator()(const hkgpConvexHull*const* hulls,int numHulls) const=0; }; public: /// Constructor hkgpConvexHull(); /// Destructor. virtual ~hkgpConvexHull(); /// Get a unique identifier for that convex hull. hkUint32 uid() const; /// Reset the convex hull to an empty set of dimension -1. void reset(); /// Clone the convex hull, userData and properties. hkgpConvexHull* clone() const; /// Get user data. void*& userData() const; /// Get the user object. IUserObject*& userObject() const; /// Delete the user object. void deleteUserObject(); /// Builds a convex hull given a points set, return the resulting convex hull dimension or -1 if failed. int build(const hkVector4* points, int numPoints, const BuildConfig& config=BuildConfig()); /// Builds a convex hull given a points set, return the resulting convex hull dimension or -1 if failed. int build(const hkStridedVertices& points, const BuildConfig& config=BuildConfig()); /// Builds a planar convex hull given a points set and a projection plane, return the resulting convex hull dimension or -1 if failed. int buildPlanar(const hkVector4* points, int numPoints, const hkVector4& plane, const BuildConfig& config=BuildConfig()); /// Builds a planar convex hull given a points set and a projection plane, return the resulting convex hull dimension or -1 if failed. int buildPlanar(const hkStridedVertices& points, const hkVector4& plane, const BuildConfig& config=BuildConfig()); /// Builds a convex hull given a planes set, return the resulting convex hull dimension or -1 if failed. int buildFromPlanes(const hkVector4* planes, int numPlanes, const BuildConfig& config=BuildConfig()); /// Builds a convex hull given a planes set and a projection plane, return the resulting convex hull dimension or -1 if failed. int buildFromPlanes(const hkVector4* planes, int numPlanes, const hkVector4& projectionPlane, const BuildConfig& config=BuildConfig()); /// Simplify a convex hull. void simplify(const SimplifyConfig& config); /// Expand the convex hull to ensure that it contains \a points. void ensureContainment(const hkArray<hkVector4>& points); /// Decimate vertices of a convex hull. /// If \a ensureContainment is true, ensureContainment() is called automatically. bool decimateVertices(int numVerticesToKeep, bool ensureContainment); /// Expand convex hull with margin using face normal. bool expandByPlanarMargin(const hkReal margin); /// Absolute scaling of convex hull. void absoluteScale(hkReal offset,const AbsoluteScaleConfig& config=AbsoluteScaleConfig()); /// Assigns plane, vertex and triangle indices. /// This data is needed for e.g. getIndex(), getPlaneIndex() and generateIndexedFaces(). /// Planes are merged if PAxyz.PBxyz > minCosAngle. /// Note: this is automatically called by build if BuildConfig.m_buildIndices is set (default). void buildIndices(hkReal minCosAngle = HKGPCONVEXHULL_DEFAULT_MIN_COS_ANGLE, bool forceRebuild=false); /// Calculates and stores mass properties. See getVolume(), getLocalInertia(). hkResult buildMassProperties( ); /// Checks whether a point is a vertex of the convex hull. bool isVertexUsed(const hkVector4& point) const; /// Checks whether a point is inside or on the convex hull. /// For maximum performance, call buildIndices() and set \a usePlanes to true. /// All planes will be expanded by \a planeThickness. bool isPointInside( const hkVector4& point, bool usePlanes = false, hkReal planeThickness=0) const; /// Clips lines against planes, returning false if the line is completely outside the convex hull. /// All planes will be expanded by \a planeThickness. bool clipLine(const hkVector4& a, const hkVector4& b, hkReal& t0, hkReal& t1, hkReal planeThickness=0) const; /// Retrieves the maximum distance to the planes of a given point. hkReal maximumDistanceToPlanes(const hkVector4& point) const; /// Retrieves configuration used to build the convex hull. const BuildConfig& getConfiguration() const; /// Gets the number of dimensions of the convex hull, returns -1 for invalid. int getDimensions() const; /// Gets the axis-aligned bounding box of the convex hull. hkAabb getBoundingBox(Inputs inputs, hkReal scale=1, hkReal radialScale=0) const; /// Gets the oriented bounding box of the convex hull. void getOrientedBoundingBox(hkVector4& halfExtents, hkTransform& worldTransform) const; /// Gets the oriented rectangle of the convex hull given a projection axis. void getOrientedRectangle(const hkVector4& projectionPlane, hkVector4& halfExtents, hkTransform& worldTransform) const; /// Gets the projection axis (only for convex hull of dimension 1). hkVector4 getProjectionAxis() const; /// Gets the projection plane (only for convex hull of dimension 2). hkVector4 getProjectionPlane() const; /// Retrieves the total number of planes, returned as the number of faces. int getNumPlanes() const; /// Retrieves a plane by index. const hkVector4& getPlane(int index) const; /// Retrieves the total number of vertices. int getNumVertices() const; /// Retrieves the first vertex of the convex hull. Vertex* getFirstVertex() const; /// Retrieves the vertex index for the specified vertex. int getIndex(const Vertex* vertex) const; /// Retrieves the next vertex, which is part of the convex hull. Vertex* getNext(const Vertex* vertex) const; /// Retrieves the world position of a vertex. hkVector4 getPosition(const Vertex* vertex) const; /// Retrieves the source position (used for building) of a vertex. const hkVector4& getSourcePosition(const Vertex* vertex) const; /// Retrieves the total number of triangles. int getNumTriangles() const; /// Retrieves the next triangle. Triangle* getFirstTriangle() const; /// Retrieves triangle index. int getIndex(const Triangle* triangle) const; /// Retrieves the next triangle. Triangle* getNext(const Triangle* triangle) const; /// Retrieves the plane index of a triangle. int getPlaneIndex(const Triangle* triangle) const; /// Retrieves the plane equation of a triangle. hkVector4 getPlaneEquation(const Triangle* triangle) const; /// Retrieves a vertex of triangle. Vertex* getVertex(const Triangle* triangle, int index) const; /// Retrieves the neighbor triangle given an edge index. Triangle* getNeighbour(Triangle* triangle, int index) const; /// Gets 'width*|direction|' of the convex hull. hkReal getWidth(const hkVector4& direction) const; /// Gets the minimum distance from a plane. hkReal getMinimumDistanceFromPlane(const hkVector4& plane) const; /// Gets the maximum distance from a plane hkReal getMaximumDistanceFromPlane(const hkVector4& plane) const; /// Support mapping. void getSupportingVertex(const hkVector4& direction,hkVector4& vertexOut) const; /// Gets nearest vertex from a given points. void getNearestVertex(Inputs inputs, const hkVector4& point, hkVector4& vertexOut) const; /// Gets farthest vertex from a given point. void getFarthestVertex(Inputs inputs, const hkVector4& point, hkVector4& vertexOut) const; /// Gets the centroid of the convex hull. const hkVector4& getCentroid() const; /// Returns the sum of all edge lengths. hkReal getEdgeLengths() const; /// Returns the sphericity of the convex hull. hkReal getSphericity() const; /// Returns the volume of the convex hull. /// You need to call buildMassProperties() before you call this method. hkReal getVolume() const; /// Returns the surface area of the convex hull. /// You need to call buildMassProperties() before you call this method. hkReal getSurfaceArea() const; /// Retrieves inertia space and inertia diagonal. /// You need to call buildMassProperties() before you call this method. void getLocalInertia(hkTransform& inertiaSpace, hkVector4& inertiaDiagonal) const; /// Retrieves world inertia matrix. /// You need to call buildMassProperties() before you call this method. const hkMatrix3& getWorldInertia() const; /// Retrieves the center of mass. /// You need to call buildMassProperties() before you call this method. const hkVector4& getCenterOfMass() const; /// Retrieves major (world) plane/axis from inertia. /// You need to call buildMassProperties() before you call this method. hkVector4 getMajorPlane() const; /// Retrieves width-sorted planes/axis from inertia. void getMajorPlanes(hkVector4 planesOut[3]) const; /// Retrieves the best projection plane. hkVector4 getBestProjectionPlane() const; /// Classifies relative to a plane and retrieve distance to plane bounds. Side classify(const hkVector4& plane, hkReal thickness, hkReal* bounds=0) const; /// Splits the convex hull by a plane. /// Note: Even in the case where the return value is CROSSING, posOut, negOut or both can be null is they are degenerate. /// Handling of those cases are application dependent. Side splitByPlane(const hkVector4& plane, hkgpConvexHull** posOut, hkgpConvexHull** negOut, hkReal cuttingPlaneThickness=HKGPCONVEXHULL_DEFAULT_SPLIT_THICKNESS) const; /// Recursively subdivides the convex hull along its major axis. void subdivide(int recursions, hkArray<hkgpConvexHull*>& output, hkReal thickness=HKGPCONVEXHULL_DEFAULT_SPLIT_THICKNESS) const; /// Fetches all vertex positions. void fetchPositions(Inputs inputs, hkArray<hkVector4>& positionsOut) const; /// Fetches all planes. void fetchPlanes(hkArray<hkVector4>& planes) const; /// Fetches bevel planes. void fetchBevelPlanes( hkReal maxCosAngle, hkArray<hkVector4>& bevelPlanesOut ) const; /// Generates indexed faces, returns the number of faces/planes. /// This data is needed by hkpConvexVerticesConnectivity. /// Note: if inputs == SOURCES, indices will be the one stored in source position with hkVector4::setInt24W. int generateIndexedFaces(Inputs inputs, hkArray<hkUint8>& verticesPerFace, hkArray<hkUint16>& indices, bool maximizeArea) const; /// Generates indexed faces, returns the number of faces/planes. /// Note: if inputs == SOURCES, is set, indices will be the one stored in source position with hkVector4::setInt24W. int generateIndexedFaces(Inputs inputs, hkArray<int>& verticesPerFace, hkArray<int>& indices, bool maximizeArea) const; /// Generates vertex adjacency graph as COUNT,EDGES for each vertex. void generateVertexAdjacencyGraph(hkArray<int>& edgesOut, hkArray<int>& vertexOffsetsOut) const; /// Generates hkGeometry. void generateGeometry(Inputs inputs, struct hkGeometry& geometryOut) const; // // Boolean operations // /// Boolean split of A with B. static void HK_CALL booleanSplit(const hkgpConvexHull* operandA, const hkgpConvexHull* operandB, hkgpConvexHull** inside, hkArray<hkgpConvexHull*>* outside, hkReal thickness=HKGPCONVEXHULL_DEFAULT_SPLIT_THICKNESS); /// Boolean intersection of two convex hull (A & B). static bool HK_CALL booleanIntersection(const hkgpConvexHull* operandA, const hkgpConvexHull* operandB, hkgpConvexHull*& output, hkReal thickness=HKGPCONVEXHULL_DEFAULT_SPLIT_THICKNESS); /// Boolean subtraction of two convex hull (A - B). static bool HK_CALL booleanSubtraction(const hkgpConvexHull* operandA, const hkgpConvexHull* operandB, hkArray<hkgpConvexHull*>& output, hkReal thickness=HKGPCONVEXHULL_DEFAULT_SPLIT_THICKNESS); /// Boolean subtraction of two convex hull (A - Bs). static bool HK_CALL booleanSubtraction(const hkgpConvexHull* operandA, const hkArray<hkgpConvexHull*>& operandsB, hkArray<hkgpConvexHull*>& output, hkReal thickness=HKGPCONVEXHULL_DEFAULT_SPLIT_THICKNESS); // // Utilities // /// Volume based simplification, removed vertices until volume difference is greater than \a threshold (0.0f = 0% , 1.0f = 100%). /// If \a ensureContainment is true, ensureContainment() is called automatically static hkgpConvexHull* HK_CALL volumeSimplify(const hkgpConvexHull* hull, hkReal threshold, bool ensureContainment); /// compute Minkowski sum or difference {x + y * bScale | x e A, y e B} static hkgpConvexHull* HK_CALL computeMinkowski(const hkStridedVertices& A, const hkStridedVertices& B, hkSimdRealParameter bScale); /// Finds the best splitting plane from convex hull a that maximizes the volume of -b and satisfies f(a U -b , +b); returns the volume of -b. static hkReal HK_CALL findBestUnion(const hkgpConvexHull* a, const hkgpConvexHull* b, const IBooleanFunction& f, hkgpConvexHull*& aUnb, hkgpConvexHull*& pb); /// Creates a compound convex hull from a given set. static hkgpConvexHull* HK_CALL createCompound(Inputs inputs, const hkgpConvexHull* const* hulls, int numHulls); /// Creates a compound convex hull from a given set. static hkgpConvexHull* HK_CALL createCompound(Inputs inputs, const hkgpConvexHull* a, const hkgpConvexHull* b); /// Creates random samples inside the convex hull. static void HK_CALL createRandomSamples(const hkgpConvexHull* domain,hkPseudoRandomGenerator& generator,int numSamples,hkArray<hkVector4>& samples); /// Creates Voronoi cells from a convex domain and a points set. static void HK_CALL createVoronoiCells(const hkgpConvexHull* domain,const hkArray<hkVector4>& points,hkArray<hkgpConvexHull*>& cells,hkReal margin=0); /// Creates Voronoi edges from a convex domain and a points set. static void HK_CALL createVoronoiEdges(const hkgpConvexHull* domain,const hkArray<hkVector4>& points,hkArray<hkgpConvexHull*>& cells,hkReal margin=0); /// Creates Voronoi features from a convex domain and a points set. static void HK_CALL createVoronoiFeatures(const hkgpConvexHull* domain,const hkArray<hkVector4>& points,hkArray<hkgpConvexHull*>& cells,hkArray<hkgpConvexHull*>& edges,hkReal margin=0); private: inline hkgpConvexHull(const hkgpConvexHull& ch) : hkReferencedObject(ch) {} void operator=(const hkgpConvexHull&) {} private: friend class hkgpConvexHullImpl; class hkgpConvexHullImpl* m_data; mutable void* m_userData; mutable IUserObject* m_userObject; }; #endif // HKGP_CONVEX_HULL_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 443 ] ] ]
015bbf4127c8fc23dad3811d0fd62a863923c98a
2e5fd1fc05c0d3b28f64abc99f358145c3ddd658
/deps/quickfix/src/C++/ThreadedSocketConnection.cpp
7af5c4e504483e51a681b40202ed9cd5e8feeeb4
[ "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
5,467
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 "ThreadedSocketConnection.h" #include "ThreadedSocketAcceptor.h" #include "ThreadedSocketInitiator.h" #include "Session.h" #include "Utility.h" namespace FIX { ThreadedSocketConnection::ThreadedSocketConnection ( int s, Sessions sessions, Application& application, Log* pLog ) : m_socket( s ), m_application( application ), m_pLog( pLog ), m_sessions( sessions ), m_pSession( 0 ), m_disconnect( false ) { FD_ZERO( &m_fds ); FD_SET( m_socket, &m_fds ); } ThreadedSocketConnection::ThreadedSocketConnection ( const SessionID& sessionID, int s, const std::string& address, short port, Application& application, Log* pLog ) : m_socket( s ), m_address( address ), m_port( port ), m_application( application ), m_pLog( m_pLog ), m_pSession( Session::lookupSession( sessionID ) ), m_disconnect( false ) { FD_ZERO( &m_fds ); FD_SET( m_socket, &m_fds ); if ( m_pSession ) m_pSession->setResponder( this ); } ThreadedSocketConnection::~ThreadedSocketConnection() { if ( m_pSession ) { m_pSession->setResponder( 0 ); Session::unregisterSession( m_pSession->getSessionID() ); } } bool ThreadedSocketConnection::send( const std::string& msg ) { QF_STACK_PUSH(ThreadedSocketConnection::send) return socket_send( m_socket, msg.c_str(), msg.length() ) >= 0; QF_STACK_POP } bool ThreadedSocketConnection::connect() { QF_STACK_PUSH(ThreadedSocketConnection::connect) return socket_connect(getSocket(), m_address.c_str(), m_port) >= 0; QF_STACK_POP } void ThreadedSocketConnection::disconnect() { QF_STACK_PUSH(ThreadedSocketConnection::disconnect) m_disconnect = true; socket_close( m_socket ); QF_STACK_POP } bool ThreadedSocketConnection::read() { QF_STACK_PUSH(ThreadedSocketConnection::read) struct timeval timeout = { 1, 0 }; fd_set readset = m_fds; try { // Wait for input (1 second timeout) int result = select( 1 + m_socket, &readset, 0, 0, &timeout ); if( result > 0 ) // Something to read { // We can read without blocking int size = recv( m_socket, m_buffer, sizeof(m_buffer), 0 ); if ( size <= 0 ) { throw SocketRecvFailed( size ); } m_parser.addToStream( m_buffer, size ); } else if( result == 0 && m_pSession ) // Timeout { m_pSession->next(); } else if( result < 0 ) // Error { throw SocketRecvFailed( result ); } processStream(); return true; } catch ( SocketRecvFailed& e ) { if( m_disconnect ) return false; if( m_pSession ) { m_pSession->getLog()->onEvent( e.what() ); m_pSession->disconnect(); } else { disconnect(); } return false; } QF_STACK_POP } bool ThreadedSocketConnection::readMessage( std::string& msg ) throw( SocketRecvFailed ) { QF_STACK_PUSH(ThreadedSocketConnection::readMessage) try { return m_parser.readFixMessage( msg ); } catch ( MessageParseError& ) {} return true; QF_STACK_POP } void ThreadedSocketConnection::processStream() { QF_STACK_PUSH(ThreadedSocketConnection::processStream) std::string msg; while( readMessage(msg) ) { if ( !m_pSession ) { if ( !setSession( msg ) ) { disconnect(); continue; } } try { m_pSession->next( msg, UtcTimeStamp() ); } catch( InvalidMessage& ) { if( !m_pSession->isLoggedOn() ) { disconnect(); return; } } } QF_STACK_POP } bool ThreadedSocketConnection::setSession( const std::string& msg ) { QF_STACK_PUSH(ThreadedSocketConnection::setSession) m_pSession = Session::lookupSession( msg, true ); if ( !m_pSession ) { if( m_pLog ) { m_pLog->onEvent( "Session not found for incoming message: " + msg ); m_pLog->onIncoming( msg ); } return false; } SessionID sessionID = m_pSession->getSessionID(); m_pSession = 0; // see if the session frees up within 5 seconds for( int i = 1; i <= 5; i++ ) { if( !Session::isSessionRegistered( sessionID ) ) m_pSession = Session::registerSession( sessionID ); if( m_pSession ) break; process_sleep( 1 ); } if ( !m_pSession ) return false; if ( m_sessions.find(m_pSession->getSessionID()) == m_sessions.end() ) return false; m_pSession->setResponder( this ); return true; QF_STACK_POP } } // namespace FIX
[ [ [ 1, 219 ] ] ]
4d25b672ebdea70a2d0adcf67eb4d2c378338fcd
967868cbef4914f2bade9ef8f6c300eb5d14bc57
/platform/defines.hpp
a346cffb735ea853f748c9fdafd89f8b1485dd2b
[]
no_license
saminigod/baseclasses-001
159c80d40f69954797f1c695682074b469027ac6
381c27f72583e0401e59eb19260c70ee68f9a64c
refs/heads/master
2023-04-29T13:34:02.754963
2009-10-29T11:22:46
2009-10-29T11:22:46
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
5,939
hpp
/* © Vestris Inc., Geneva, Switzerland http://www.vestris.com, 1994-1999 All Rights Reserved ______________________________________________ written by Daniel Doubrovkine - [email protected] Revision history: 17.09.1999: OSF1 does not support usleep (or has it well hidden, didn't look for it, dB.) 17.09.1999: HPUX, AIX definitions for h_errno */ #ifndef BASE_DEFINES_HPP #define BASE_DEFINES_HPP #ifndef _REENTRANT #define _REENTRANT #endif #ifdef _UNIX /* reentrant definitions */ #ifdef _REENTRANT #define base_localtime(TIME, TMTIME) localtime_r(&TIME, &TMTIME) #define base_gmtime(TIME, TMTIME) gmtime_r(&TIME, &TMTIME) #endif /* gethostname and getpagesize for IRIX */ #if defined(_OS_IRIX) || defined(_OS_IRIX64) extern "C" { extern int getpagesize(void); } extern "C" { extern int gethostname(char *, size_t); } #endif /* errno - h_errno */ #ifndef HAVE_H_ERRNO extern int h_errno; #endif #define base_errno errno #define setpgrp ::setsid #define base_exit ::exit #define base_chdir(x) ::chdir((const char *) x) #define base_getpid ::getpid #define base_getcwd ::getcwd #define base_mkdir(x) ::mkdir((const char *) x, S_IRWXU) #define base_seek ::lseek #define base_open ::open #define base_close ::close #define base_unlink ::unlink #define base_set_new_handler ::set_new_handler #define base_stat ::stat #define struct_stat struct stat #define base_fileno fileno #define base_fdopen ::fdopen #define base_fclose ::fclose #define base_fread ::fread #define base_fwrite ::fwrite #define base_fgetc ::fgetc #define base_popen ::popen #define base_pclose ::pclose /* char manip */ #define base_strlen(x) ::strlen((const char *) (x)) #define base_strcspn ::strcspn #define base_strspn ::strspn #define base_strstr ::strstr #define base_strncpy ::strncpy #define base_strchr ::strchr #define base_strncmp ::strncmp #define base_snprintf snprintf #define base_vsnprintf vsnprintf /* ftime */ #define base_ftime ::ftime #define base_timeb timeb /* environment */ extern char ** environ; #define _environ environ /* pthread / pth */ #ifdef HAVE_PTH #define base_connect pth_connect #define base_accept pth_accept #define base_select pth_select #define base_poll pth_poll #define base_read pth_read #define base_write pth_write #define base_send(X,Y,Z,A) pth_write(X,Y,Z) #define base_recv(X,Y,Z,A) pth_read(X,Y,Z) #define base_sleep_ms(_X) pth_usleep(_X * 1000) #define base_sleep pth_sleep #else #define base_connect connect #define base_accept accept #define base_select select #define base_poll poll #define base_read read #define base_write write #define base_send(X,Y,Z,A) ::write(X,Y,Z) #define base_recv(X,Y,Z,A) ::read(X,Y,Z) #ifdef HAVE_USLEEP #define base_sleep_ms(_X) ::usleep(_X * 1000) #else #define base_sleep_ms(_X) ::sleep(_X / 1000) #endif #define base_sleep ::sleep #endif #define __cdecl #endif #ifdef _WIN32 /* reentrant */ #define base_localtime(TIME, TMTIME) memcpy(&TMTIME, localtime(&TIME), sizeof(TMTIME)) #define base_gmtime(TIME, TMTIME) memcpy(&TMTIME, gmtime(&TIME), sizeof(TMTIME)) /* other */ #define base_exit ::_exit #define base_send(X,Y,Z,A) ::send(X,Y,Z,A) #define base_recv(X,Y,Z,A) ::recv(X,Y,Z,A) #define base_sleep_ms(x) ::Sleep(x) #define base_sleep(x) ::Sleep(x * 1000) #define base_getpid ::_getpid #define base_chdir(x) ::_chdir((const char *) x) #define base_getcwd ::_getcwd #define base_mkdir(x) ::_mkdir((const char *) x) #define base_set_new_handler ::_set_new_handler #define base_errno errno /* char manip */ #define base_strlen(x) ::strlen((const char *) (x)) #define base_strcmpi ::_strcmpi #define base_strncmpi ::_strnicmp #define base_strcspn ::strcspn #define base_strspn ::strspn #define base_strstr ::strstr #define base_strncpy ::strncpy #define base_strchr ::strchr #define base_strncmp ::strncmp #define base_snprintf _snprintf #define base_vsnprintf _vsnprintf /* file-related */ #define off_t long #define ssize_t size_t #define mode_t unsigned int #define base_seek ::_lseek #define base_read ::_read #define base_write ::_write #define base_open ::_open #define base_close ::_close #define base_unlink ::_unlink #define base_ftime ::_ftime #define base_timeb _timeb #define base_stat ::_stat #define struct_stat struct _stat #define base_fileno _fileno #define base_fdopen _fdopen #define base_fclose fclose #define base_fread fread #define base_fwrite fwrite #define base_fgetc fgetc #define base_popen ::_popen #define base_pclose ::_pclose /* handle related */ #define O_APPEND _O_APPEND #define O_BINARY _O_BINARY #define O_CREAT _O_CREAT #define O_SHORT_LIVED _O_SHORT_LIVED #define O_TEMPORARY _O_TEMPORARY #define O_EXCL _O_EXCL #define O_RANDOM _O_RANDOM #define O_RDONLY _O_RDONLY #define O_RDWR _O_RDWR #define O_SEQUENTIAL _O_SEQUENTIAL #define O_TEXT _O_TEXT #define O_TRUNC _O_TRUNC #define O_WRONLY _O_WRONLY /* socketcomm */ #define base_connect ::connect #define base_accept ::accept #define base_select ::select #define base_poll ::poll #endif #ifndef MAXPATHLEN #define MAXPATHLEN _MAX_PATH #endif #ifndef MAXHOSTENT #define MAXHOSTENT 16384 #endif #ifndef _WIN32 #ifndef BYTE #define BYTE char #endif #endif #define KBYTE 1024 #define MBYTE 1048576L #define GBYTE 1073741824L #define BASE_MAX(X,Y) ((X)>(Y)?(X):(Y)) #define BASE_MIN(X,Y) ((X)<(Y)?(X):(Y)) #define BASE_DIM(X) (int) (sizeof(X) / sizeof(X[0])) /* URLTree of CSwapString/CString switch */ // #define __URL_TREE_SWAP /* TLI - Transport Layer Interface instead of sockets */ // #define __TLI_SUPPORTED #ifndef false #ifdef FALSE #define false FALSE #else #define false 0 #endif #endif #ifndef true #ifdef TRUE #define true TRUE #else #define true 1 #endif #endif #endif
[ [ [ 1, 225 ] ] ]
a24c8b7391c8ebac439f36f74084f44b0a9a1d38
9613f6e0e67d5955c3baca0665f3b1f2694171ad
/SAND/trunk/SAND DX 1/sand_phys.cpp
72b81ce6dd7ef40ca1df6410959379755ecd0eb7
[]
no_license
EraYaN/reSAND
a5f674dab6b26de178a705df06a31ae73d70da7c
21dc29e5822020f19433b7f550313972dec3fcf8
refs/heads/master
2016-08-04T18:57:28.858572
2010-02-18T17:23:20
2010-02-18T17:23:20
32,873,360
0
0
null
null
null
null
UTF-8
C++
false
false
1,148
cpp
#include "sand_phys.h" #include "main.h" SAND start_sands = {100,100,1}; SAND_TYPE Water = {0.0f,0.0f,255.0f,3,1.0f}; sand_phys::sand_phys() { sands.push_back(start_sands); } sand_phys::~sand_phys(void) { } int sand_phys::calculate(float xPos, float yPos, float &newXpos, float &newYpos, int sand_id) { int phasemax, phasemin; //dwarreligheid... switch(sand_types.at(sands.at(sand_id).type).phase) { case 0: phasemax = 2; phasemin = 0; break; case 1: phasemax = 5; phasemin = 2; break; case 2: phasemax = 10; phasemin = 3; break; default: phasemax = 1; phasemin = 0; } float yForce = (sand_types.at(sands.at(sand_id).type).weight*-9.81)+sands.at(sand_id).Y_Force; float xForce = (rand()%phasemax+phasemin)+sands.at(sand_id).X_Force; newXpos = xPos+xForce/10; newYpos = yPos+yForce/10; return 0; } void add_sands_to_vertex(SAND sand_dat){ CUSTOMVERTEX buffer_vertex = {sand_dat.X,sand_dat.Y,1.0f,1.0f,D3DCOLOR_XRGB(sand_types.at(sand_dat.type).R, sand_types.at(sand_dat.type).G, sand_types.at(sand_dat.type).B)}; SAND_vertices.push_back(buffer_vertex); }
[ [ [ 1, 53 ] ] ]
3f0919b2c10df3efd83db95aa77c54a54de43d93
a86ab590320fbbf2c3d8cac5cea9622bef28944b
/include/xmlUtils.hpp
dce2b69d88a092a76a2b7ebac0b319858dcab6c7
[]
no_license
wumingbo/itunes-habit
c6318344f8fa9ceded030a7b2bb7cbae36fb9032
79670b45ad253ab3f5d2c5c07547844ca49d283b
refs/heads/master
2021-01-22T15:21:37.165310
2010-06-30T06:15:48
2010-06-30T06:15:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,068
hpp
#pragma once #include <xercesc/util/XMLString.hpp> #include <xercesc/sax/ErrorHandler.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> #include <xercesc/dom/DOMNodeFilter.hpp> XERCES_CPP_NAMESPACE_USE class StrX { public: StrX(const XMLCh * const toTranscode) : l(XMLString::transcode(toTranscode)) { } ~StrX(void) { XMLString::release(&l); } inline const char * local(void) const { return l; } private: char * l; }; class XStr { public: XStr(const char * const toTranscode) : u(XMLString::transcode(toTranscode)) { } ~XStr(void) { XMLString::release(&u); } inline const XMLCh * unicode(void) const { return u; } private: XMLCh * u; }; #define XS(str) XStr(str).unicode() #define SX(str) StrX(str).local() class ErrorReporter : public ErrorHandler { public: ErrorReporter() : num_errors(0), num_warnings(0), num_fatals(0) { } ~ErrorReporter() { } // // Implementation of the error handler interface // void warning(const SAXParseException & c); void error(const SAXParseException & c); void fatalError(const SAXParseException & c); void def(const SAXParseException & c); void resetErrors(); inline bool errors_exist() const { return num_errors != 0 || num_fatals != 0; } inline bool warnings_exist() const { return num_warnings != 0; } int num_errors, num_warnings, num_fatals; }; class Filter : public DOMNodeFilter { public: Filter(unsigned long s = DOMNodeFilter::SHOW_ALL); virtual FilterAction acceptNode(const DOMNode *) const; virtual unsigned long getWhatToShow(void) const { return show; } virtual void setWhatToShow(unsigned long s) { show = s; } private: Filter(const Filter &); Filter & operator = (const Filter &); unsigned long show; };
[ "colin.diesh@37d2c1db-bb2f-0410-a901-09a4849b322f", "[email protected]" ]
[ [ [ 1, 17 ], [ 20, 20 ], [ 25, 26 ], [ 31, 46 ], [ 49, 49 ], [ 54, 54 ], [ 59, 86 ], [ 88, 103 ], [ 105, 105 ], [ 109, 111 ], [ 114, 114 ], [ 116, 117 ] ], [ [ 18, 19 ], [ 21, 24 ], [ 27, 30 ], [ 47, 48 ], [ 50, 53 ], [ 55, 58 ], [ 87, 87 ], [ 104, 104 ], [ 106, 108 ], [ 112, 113 ], [ 115, 115 ] ] ]
86d453118fc39285ea81983731b67bc72a9adbd4
be2e23022d2eadb59a3ac3932180a1d9c9dee9c2
/NpcServer/NpcKernel/SynManager.cpp
5526c44214cbe25169de611692f002b8419fdd06
[]
no_license
cronoszeu/revresyksgpr
78fa60d375718ef789042c452cca1c77c8fa098e
5a8f637e78f7d9e3e52acdd7abee63404de27e78
refs/heads/master
2020-04-16T17:33:10.793895
2010-06-16T12:52:45
2010-06-16T12:52:45
35,539,807
0
2
null
null
null
null
UTF-8
C++
false
false
2,153
cpp
#include "windows.h" #include "SynManager.h" #include "NpcWorld.h" #include <algorithm> bool CSyndicate::Create(IRecordset* pRes) { m_id = pRes->GetInt(SYNDATA_ID); m_idFealty = pRes->GetInt(SYNDATA_FEALTY); for(int i = 0; i < MAX_SYNENEMYSIZE; i++) { OBJID id = pRes->GetInt((SYNDATA)(SYNDATA_ALLY0 + i)); if(id != ID_NONE) m_setAlly.push_back(id); } for(int i = 0; i < MAX_SYNENEMYSIZE; i++) { OBJID id = pRes->GetInt((SYNDATA)(SYNDATA_ENEMY0 + i)); if(id != ID_NONE) m_setEnemy.push_back(id); } return true; } bool CSyndicate::IsFriendly(OBJID idSyn) { if(idSyn == ID_NONE) return false; CSyndicate* pTarget = SynManager()->QuerySyndicate(idSyn); CHECKF(pTarget); OBJID idTarget = pTarget->GetMasterSynID(); if(idTarget == GetMasterSynID()) return true; if(find(m_setAlly.begin(), m_setAlly.end(), idTarget) != m_setAlly.end()) return true; return false; } bool CSyndicate::IsHostile(OBJID idSyn) { if(idSyn == ID_NONE) return false; CSyndicate* pTarget = SynManager()->QuerySyndicate(idSyn); CHECKF(pTarget); OBJID idTarget = pTarget->GetMasterSynID(); if(find(m_setEnemy.begin(), m_setEnemy.end(), idTarget) != m_setEnemy.end()) return true; return false; } bool CSyndicate::IsNeutral(OBJID idSyn) { if(idSyn == ID_NONE) return true; if(!IsFriendly(idSyn) && !IsHostile(idSyn)) return true; return false; } CSynManager::CSynManager() { m_setSyn = CSynSet::CreateNew(true); } CSynManager::~CSynManager() { if(m_setSyn) m_setSyn->Release(); } bool CSynManager::Create() { CHECKF(m_setSyn); char szSQL[1024]; sprintf(szSQL, "SELECT * FROM %s WHERE del_flag=0", _TBL_SYNDICATE); IRecordset* pRes = NpcWorld()->GetDatabase()->CreateNewRecordset(szSQL); if(pRes) { for(int i = 0; i < pRes->RecordCount(); i++, pRes->MoveNext()) { CSyndicate* pSyn = CSyndicate::CreateNew(); if(pSyn) { if(pSyn->Create(pRes)) m_setSyn->AddObj(pSyn); else pSyn->ReleaseByOwner(); } } pRes->Release(); } return true; }
[ "rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1" ]
[ [ [ 1, 119 ] ] ]
c8fcd5a51cf89423bdaf75280f0a055800e0af9e
81e051c660949ac0e89d1e9cf286e1ade3eed16a
/quake3ce/code/pvr/pvr_snd.cpp
811c7c6295d586c6bfbe1f7a53dc65fd029f877b
[]
no_license
crioux/q3ce
e89c3b60279ea187a2ebcf78dbe1e9f747a31d73
5e724f55940ac43cb25440a65f9e9e12220c9ada
refs/heads/master
2020-06-04T10:29:48.281238
2008-11-16T15:00:38
2008-11-16T15:00:38
32,103,416
5
0
null
null
null
null
UTF-8
C++
false
false
7,553
cpp
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code 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. Quake III Arena source code 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 Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <sys/types.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <sys/shm.h> #include <sys/wait.h> #ifdef __linux__ // rb0101023 - guard this #include <linux/soundcard.h> #endif #ifdef __FreeBSD__ // rb0101023 - added #include <sys/soundcard.h> #endif #include <stdio.h> #include "../game/q_shared.h" #include "../client/snd_local.h" int audio_fd; int snd_inited=0; cvar_t *sndbits; cvar_t *sndspeed; cvar_t *sndchannels; cvar_t *snddevice; /* Some devices may work only with 48000 */ static int tryrates[] = { 22050, 11025, 44100, 48000, 8000 }; static qboolean use_custom_memset = qfalse; // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=371 void Snd_Memset (void* dest, const int val, const size_t count) { int *pDest; int i, iterate; if (!use_custom_memset) { Com_Memset(dest,val,count); return; } iterate = count / sizeof(int); pDest = (int*)dest; for(i=0; i<iterate; i++) { pDest[i] = val; } } qboolean SNDDMA_Init(void) { int rc; int fmt; int tmp; int i; // char *s; // bk001204 - unused struct audio_buf_info info; int caps; extern uid_t saved_euid; if (snd_inited) return 1; if (!snddevice) { sndbits = Cvar_Get("sndbits", "16", CVAR_ARCHIVE); sndspeed = Cvar_Get("sndspeed", "0", CVAR_ARCHIVE); sndchannels = Cvar_Get("sndchannels", "2", CVAR_ARCHIVE); snddevice = Cvar_Get("snddevice", "/dev/dsp", CVAR_ARCHIVE); } // open /dev/dsp, confirm capability to mmap, and get size of dma buffer if (!audio_fd) { seteuid(saved_euid); audio_fd = open(snddevice->string, O_RDWR); seteuid(getuid()); if (audio_fd < 0) { perror(snddevice->string); Com_Printf("Could not open %s\n", snddevice->string); return 0; } } if (ioctl(audio_fd, SNDCTL_DSP_GETCAPS, &caps) == -1) { perror(snddevice->string); Com_Printf("Sound driver too old\n"); close(audio_fd); return 0; } if (!(caps & DSP_CAP_TRIGGER) || !(caps & DSP_CAP_MMAP)) { Com_Printf("Sorry but your soundcard can't do this\n"); close(audio_fd); return 0; } /* SNDCTL_DSP_GETOSPACE moved to be called later */ // set sample bits & speed dma.samplebits = FIXED_TO_INT(sndbits->value); if (dma.samplebits != 16 && dma.samplebits != 8) { ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &fmt); if (fmt & AFMT_S16_LE) dma.samplebits = 16; else if (fmt & AFMT_U8) dma.samplebits = 8; } dma.speed = FIXED_TO_INT(sndspeed->value); if (!dma.speed) { for (i=0 ; i<sizeof(tryrates)/4 ; i++) if (!ioctl(audio_fd, SNDCTL_DSP_SPEED, &tryrates[i])) break; dma.speed = tryrates[i]; } dma.channels = FIXED_TO_INT(sndchannels->value); if (dma.channels < 1 || dma.channels > 2) dma.channels = 2; /* mmap() call moved forward */ tmp = 0; if (dma.channels == 2) tmp = 1; rc = ioctl(audio_fd, SNDCTL_DSP_STEREO, &tmp); if (rc < 0) { perror(snddevice->string); Com_Printf("Could not set %s to stereo=%d", snddevice->string, dma.channels); close(audio_fd); return 0; } if (tmp) dma.channels = 2; else dma.channels = 1; rc = ioctl(audio_fd, SNDCTL_DSP_SPEED, &dma.speed); if (rc < 0) { perror(snddevice->string); Com_Printf("Could not set %s speed to %d", snddevice->string, dma.speed); close(audio_fd); return 0; } if (dma.samplebits == 16) { rc = AFMT_S16_LE; rc = ioctl(audio_fd, SNDCTL_DSP_SETFMT, &rc); if (rc < 0) { perror(snddevice->string); Com_Printf("Could not support 16-bit data. Try 8-bit.\n"); close(audio_fd); return 0; } } else if (dma.samplebits == 8) { rc = AFMT_U8; rc = ioctl(audio_fd, SNDCTL_DSP_SETFMT, &rc); if (rc < 0) { perror(snddevice->string); Com_Printf("Could not support 8-bit data.\n"); close(audio_fd); return 0; } } else { perror(snddevice->string); Com_Printf("%d-bit sound not supported.", dma.samplebits); close(audio_fd); return 0; } if (ioctl(audio_fd, SNDCTL_DSP_GETOSPACE, &info)==-1) { perror("GETOSPACE"); Com_Printf("Um, can't do GETOSPACE?\n"); close(audio_fd); return 0; } dma.samples = info.fragstotal * info.fragsize / (dma.samplebits/8); dma.submission_chunk = 1; // memory map the dma buffer // TTimo 2001/10/08 added PROT_READ to the mmap // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=371 // checking Alsa bug, doesn't allow dma alloc with PROT_READ? if (!dma.buffer) dma.buffer = (unsigned char *) mmap(NULL, info.fragstotal * info.fragsize, PROT_WRITE|PROT_READ, MAP_FILE|MAP_SHARED, audio_fd, 0); if (dma.buffer == MAP_FAILED) { Com_Printf("Could not mmap dma buffer PROT_WRITE|PROT_READ\n"); Com_Printf("trying mmap PROT_WRITE (with associated better compatibility / less performance code)\n"); dma.buffer = (unsigned char *) mmap(NULL, info.fragstotal * info.fragsize, PROT_WRITE, MAP_FILE|MAP_SHARED, audio_fd, 0); // NOTE TTimo could add a variable to force using regular memset on systems that are known to be safe use_custom_memset = qtrue; } if (dma.buffer == MAP_FAILED) { perror(snddevice->string); Com_Printf("Could not mmap %s\n", snddevice->string); close(audio_fd); return 0; } // toggle the trigger & start her up tmp = 0; rc = ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &tmp); if (rc < 0) { perror(snddevice->string); Com_Printf("Could not toggle.\n"); close(audio_fd); return 0; } tmp = PCM_ENABLE_OUTPUT; rc = ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &tmp); if (rc < 0) { perror(snddevice->string); Com_Printf("Could not toggle.\n"); close(audio_fd); return 0; } snd_inited = 1; return 1; } int SNDDMA_GetDMAPos(void) { struct count_info count; if (!snd_inited) return 0; if (ioctl(audio_fd, SNDCTL_DSP_GETOPTR, &count) == -1) { perror(snddevice->string); Com_Printf("Uh, sound dead.\n"); close(audio_fd); snd_inited = 0; return 0; } return count.ptr / (dma.samplebits / 8); } void SNDDMA_Shutdown(void) { } /* ============== SNDDMA_Submit Send sound to device if buffer isn't really the dma buffer =============== */ void SNDDMA_Submit(void) { } void SNDDMA_BeginPainting (void) { }
[ "crioux@684fc592-8442-0410-8ea1-df6b371289ac" ]
[ [ [ 1, 293 ] ] ]
40ad1ccfb1c7bf8e87d9026f75b5e8e5dce760aa
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/v0-1/engine/dialog/include/Match.h
26f3b545764ddb77b2657657cef58f9ea7cdd365
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,546
h
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #ifndef __Rl_DialogMatch_H__ #define __Rl_DialogMatch_H__ #include "DialogPrerequisites.h" //-- Match.h #include <string> #include <vector> using namespace std; namespace rl { typedef enum { Context = 0, Pattern, That, Topic } component; class Nodemaster; class _RlDialogExport Match { public: Match(); ~Match(); void setPattern(const CeGuiString &pattern, component which); CeGuiString getPattern(component which); void addStar(const CeGuiString &star, component which); CeGuiString getStar(unsigned int index, component which); void setNode(Nodemaster *node); Nodemaster *getNode(); CeGuiString getPath(); private: //-- size derived from enum 'component' CeGuiString patterns[4]; vector<CeGuiString> stars[4]; Nodemaster *node; }; } #endif
[ "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 57 ] ] ]
12bc561bab288e0c7c9b3e252188f82b3e9cc173
bf7d05c055c5686e4ded30f9705a28a396520d48
/Core/CoreAttribute.h
2828a3e4b9d8a49f554cc4bf1633cd8aaa2b864d
[]
no_license
ghemingway/mgalib
f32438d5abdbeb5739c298e401a0513f91c8d6d0
c8cf8507a7fe73efe1da19abcdb77b52e75e2de0
refs/heads/master
2020-12-24T15:40:33.538434
2011-02-04T16:38:09
2011-02-04T16:38:09
32,185,568
0
1
null
null
null
null
UTF-8
C++
false
false
12,489
h
#ifndef __CORE_ATTRIBUTE_H__ #define __CORE_ATTRIBUTE_H__ /*** Included Header Files ***/ #include "CoreMetaAttribute.h" #include "CoreStorage.h" /*** Namespace Declaration ***/ namespace MGA { /*** Class Predefinitions ***/ class CoreObjectBase; // --------------------------- CoreAttributeBase --------------------------- // class CoreAttributeBase { private: CoreAttributeBase(); CoreAttributeBase(const CoreAttributeBase &); protected: CoreObjectBase *_parent; //!< Parent CoreObject CoreMetaAttribute *_metaAttribute; //!< Associated CoreMetaAttribute bool _isDirty; //!< Dirty flag uint32_t _refCount; //!< Possibly unneeded reference counter friend class CoreObjectBase; static const Result_t Create(CoreObjectBase *parent, CoreMetaAttribute *metaAttribute) throw(); ICoreStorage* SetStorageObject(void) const; //!< Force the storage to point at parent CoreObject void RegisterTransactionItem(void); //!< Register that this attribute has changed void MarkDirty(void) throw(); //!< Mark parent as dirty const Result_t InTransaction(bool &flag) const throw(); //!< Are we in a transaction const Result_t InWriteTransaction(bool &flag) const throw(); //!< Are we in a write transaction const Result_t ResolveBackpointer(const AttrID_t &attrID, const Uuid &newValue, const Uuid &oldValue) throw(); //!< CoreAttributeBase(CoreObjectBase *parent, CoreMetaAttribute *metaAttribute); //!< public: virtual ~CoreAttributeBase(); inline CoreMetaAttribute* MetaAttribute(void) const throw() { return this->_metaAttribute; } inline const Result_t AttributeID(AttrID_t &attrID) const throw() { return this->_metaAttribute->GetAttributeID(attrID); } inline bool IsDirty(void) const throw() { return this->_isDirty; } inline const Result_t GetValueType(ValueType &valueType) const throw(){ return this->_metaAttribute->GetValueType(valueType); } virtual const Result_t CommitTransaction(void) throw()=0; //!< virtual const Result_t AbortTransaction(void) throw()=0; //!< }; // --------------------------- CoreAttributeTemplateBase --------------------------- // template<class T> class CoreAttributeTemplateBase : public CoreAttributeBase { protected: friend class CoreAttributeBase; std::list<T> _values; //!< public: CoreAttributeTemplateBase(CoreObjectBase* parent, CoreMetaAttribute* coreMetaAttribute) : ::CoreAttributeBase(parent, coreMetaAttribute), _values() { } inline const Result_t SetValue(const T &value) throw() { // Make sure we are in a write transaction bool flag; Result_t result = this->InWriteTransaction(flag); ASSERT( result == S_OK ); if (!flag) return E_READONLY; // First, make sure the storage value has been loaded if (this->_values.empty()) { T tmpValue; result = this->GetValue(tmpValue); ASSERT( result == S_OK ); } // Is the value actually changing? if (value == this->_values.back()) return S_OK; // Set the value this->_values.push_back(value); // Mark the attribute as dirty this->MarkDirty(); // Add attribute to the project transaction change list this->RegisterTransactionItem(); return S_OK; } inline const Result_t GetValue(T &value) throw() { // Make sure we are in a transaction bool flag; Result_t result = this->InWriteTransaction(flag); ASSERT( result == S_OK ); if (!flag) return E_TRANSACTION; // Have we not read this attribute previously if (this->_values.empty()) { // Set the storage to the parent object ICoreStorage* storage = this->SetStorageObject(); // Read the value from storage AttrID_t attrID = ATTRID_NONE; result = this->_metaAttribute->GetAttributeID(attrID); ASSERT( result == S_OK ); Result_t result = storage->GetAttributeValue(attrID, value); if (result != S_OK) return result; // Save the value this->_values.push_back(value); } // Otherwise, just get the most recent value else value = this->_values.back(); return S_OK; } inline const Result_t GetLoadedValue(T &value) throw() { ASSERT(false); return E_INVALID_USAGE; } inline const Result_t GetPreviousValue(T &value) throw() { ASSERT(false); return E_INVALID_USAGE; } virtual const Result_t CommitTransaction(void) throw() { ASSERT( !this->_values.empty() ); ASSERT( this->_isDirty ); // Are there changes, if not we are good if (this->_values.size() == 1) return S_OK; // Set the storage to the parent object ICoreStorage* storage = this->SetStorageObject(); ASSERT( storage != NULL ); // Write the value into storage AttrID_t attrID = ATTRID_NONE; Result_t result = this->_metaAttribute->GetAttributeID(attrID); ASSERT( result == S_OK ); T value = this->_values.back(); result = storage->SetAttributeValue(attrID, value); if (result != S_OK) return result; // Collapse the value list to one this->_values.clear(); this->_values.push_back(value); return S_OK; } virtual const Result_t AbortTransaction(void) throw() { // There must be more than one value here (loaded + change) ASSERT( this->_values.size() > 1 ); ASSERT( this->_isDirty ); // Just remove the back value this->_values.pop_back(); return S_OK; } }; // Specialization of the SetValue method for Uuid (Pointer and LongPointer) template<> inline const Result_t CoreAttributeTemplateBase<Uuid>::SetValue(const Uuid &value) throw() { // Make sure we are in a write transaction bool flag; Result_t result = this->InWriteTransaction(flag); ASSERT( result == S_OK ); if (!flag) return E_READONLY; // First, make sure the storage value has been loaded if (this->_values.empty()) { Uuid tmpValue = Uuid::Null(); result = this->GetValue(tmpValue); ASSERT( result == S_OK ); } // Is the value actually changing? if (value == this->_values.back()) return S_OK; // Now, are we dealing with a pointer or longPointer ValueType valueType = ValueType::None(); result = this->_metaAttribute->GetValueType(valueType); ASSERT( result == S_OK ); if (valueType != ValueType::LongPointer() && valueType != ValueType::Pointer()) return E_ATTVALTYPE; // Pointers, those are special because we also have to change the backpointer collection if (valueType == ValueType::Pointer()) { AttrID_t attrID = ATTRID_NONE; result = this->_metaAttribute->GetAttributeID(attrID); ASSERT( result == S_OK ); // Get the current value Uuid oldValue = this->_values.back(); // Resolve all backpointer issues result = this->ResolveBackpointer(attrID, value, oldValue); if (result != S_OK) return result; } // Set the value this->_values.push_back(value); // Mark the attribute as dirty this->MarkDirty(); // Add attribute to the project transaction change list this->RegisterTransactionItem(); // Or we have an error condition return S_OK; } // Specialization of the SetValue method for std::list<Uuid> (Collection) template<> inline const Result_t CoreAttributeTemplateBase<std::list<Uuid> >::SetValue(const std::list<Uuid> &value) throw() { // Just take the new value - no questions asked this->_values.clear(); this->_values.push_back(value); return S_OK; } // Specialization of the entire CoreAttributeTemplateBase class for std::pair<std::string,std::string> (Dictionary) typedef std::pair<std::string,std::string> DictionaryEntry; template<> class CoreAttributeTemplateBase<DictionaryEntry> : public CoreAttributeBase { protected: friend class CoreAttributeBase; bool _isLoaded; DictionaryMap _dictionary; std::list<std::pair<DictionaryEntry,std::string> > _values; inline const Result_t LoadValue(void) { // Have we not read this attribute previously if (!this->_isLoaded) { // Set the storage to the parent object ICoreStorage* storage = this->SetStorageObject(); // Read the value from storage AttrID_t attrID = ATTRID_NONE; Result_t result = this->_metaAttribute->GetAttributeID(attrID); ASSERT( result == S_OK ); ASSERT( attrID != ATTRID_NONE ); result = storage->GetAttributeValue(attrID, this->_dictionary); if (result != S_OK) return result; // Mark as loaded this->_isLoaded = true; } return S_OK; } public: CoreAttributeTemplateBase<DictionaryEntry>(CoreObjectBase* parent, CoreMetaAttribute* coreMetaAttribute) : ::CoreAttributeBase(parent, coreMetaAttribute), _isLoaded(false), _dictionary(), _values() { } inline const Result_t SetValue(const DictionaryEntry &value) throw() { // Make sure we are in a write transaction bool flag; Result_t result = this->InWriteTransaction(flag); ASSERT( result == S_OK ); if (!flag) return E_READONLY; // Make sure we are loaded result = this->LoadValue(); ASSERT( result == S_OK ); // Does this key alread exist std::string currentValue = ""; DictionaryMapIter mapIter = this->_dictionary.find(value.first); // Key exists if (mapIter != this->_dictionary.end()) { // Get the current value currentValue = mapIter->second; // Update the map entry value mapIter->second = value.second; } // Key does not exist else { // Insert the value into the dictionary this->_dictionary.insert(value); } // Record the change into the list of values this->_values.push_back(std::make_pair(value,currentValue)); // Mark the attribute as dirty this->MarkDirty(); // Add attribute to the project transaction change list this->RegisterTransactionItem(); return S_OK; } inline const Result_t GetValue(DictionaryEntry &value) throw() { // Make sure we are in a transaction bool flag; Result_t result = this->InWriteTransaction(flag); ASSERT( result == S_OK ); if (!flag) return E_TRANSACTION; // Make sure we are loaded ASSERT( this->LoadValue() == S_OK ); // Now, get the value from the dictionary DictionaryMapIter mapIter = this->_dictionary.find(value.first); if (mapIter == this->_dictionary.end()) value.second = ""; else value.second = mapIter->second; return S_OK; } inline const Result_t GetLoadedValue(DictionaryEntry &value) throw() { ASSERT(false); return E_INVALID_USAGE; } inline const Result_t GetPreviousValue(DictionaryEntry &value) throw() { ASSERT(false); return E_INVALID_USAGE; } virtual const Result_t CommitTransaction(void) throw() { ASSERT( !this->_values.empty() ); ASSERT( this->_isDirty ); ASSERT( this->_isLoaded ); // Set the storage to the parent object ICoreStorage* storage = this->SetStorageObject(); ASSERT( storage != NULL ); // Write the value into storage AttrID_t attrID = ATTRID_NONE; Result_t result = this->_metaAttribute->GetAttributeID(attrID); ASSERT( result == S_OK ); result = storage->SetAttributeValue(attrID, this->_dictionary); if (result != S_OK) return result; // Clear the intermediate values list this->_values.clear(); return S_OK; } virtual const Result_t AbortTransaction(void) throw() { // There must be more than one value here (loaded + change) ASSERT( !this->_values.empty() ); ASSERT( this->_isDirty ); ASSERT( this->_isLoaded ); // Find the correct dictionary entry std::pair<DictionaryEntry,std::string> value = this->_values.back(); DictionaryMapIter mapIter = this->_dictionary.find(value.first.first); ASSERT( mapIter != this->_dictionary.end() ); // Change the value back to before the change mapIter->second = value.second; // Remove this entry from the list of changes this->_values.pop_back(); return S_OK; } }; /*** Simple Attribute Type Definitions ***/ typedef CoreAttributeTemplateBase<int32_t> CoreAttributeLong; typedef CoreAttributeTemplateBase<double> CoreAttributeReal; typedef CoreAttributeTemplateBase<std::string> CoreAttributeString; typedef CoreAttributeTemplateBase<Uuid> CoreAttributeLongPointer; typedef CoreAttributeTemplateBase< std::list<Uuid> > CoreAttributeCollection; typedef CoreAttributeTemplateBase<Uuid> CoreAttributePointer; typedef CoreAttributeTemplateBase<DictionaryEntry> CoreAttributeDictionary; /*** End of MGA Namespace ***/ } #endif // __CORE_ATTRIBUTE_H__
[ "graham.hemingway@8932de9b-a0df-7518-fb39-9aee4a96b462" ]
[ [ [ 1, 379 ] ] ]
9f68edb36eb3c16275e5db5c6ea830ee6db6907e
7b7a3f9e0cac33661b19bdfcb99283f64a455a13
/Engine/dll/Core/flx_logger.h
238e1b8a160452cf11ccf55750bb58ddabbbd312
[]
no_license
grimtraveller/fluxengine
62bc0169d90bfe656d70e68615186bd60ab561b0
8c967eca99c2ce92ca4186a9ca00c2a9b70033cd
refs/heads/master
2021-01-10T10:58:56.217357
2009-09-01T15:07:05
2009-09-01T15:07:05
55,775,414
0
0
null
null
null
null
UTF-8
C++
false
false
1,056
h
/*--------------------------------------------------------------------------- This source file is part of the FluxEngine. Copyright (c) 2008 - 2009 Marvin K. (starvinmarvin) This program is free software. ---------------------------------------------------------------------------*/ #ifndef Logger_H #define Logger_H #include "flx_core.h" #include "flx_singleton.h" #include <iostream> #include <fstream> #include <time.h> enum LOGENTRY_TYPE { LOG_DEFAULT = 0, LOG_ERROR, LOG_WARNING }; static std::string LOGENTRY_TYPE_STR[3] = { "", "Error: ", "Warning :" }; class ENGINE_API Logger : public Singleton<Logger> { public: Logger(); virtual ~Logger(); void Write(LOGENTRY_TYPE log_entry_type, const char* szMessage, ...); LOGENTRY_TYPE GetErrorCode(); char* GetErrorMessage(); void ShowLogMessage(); protected: private: char m_szFilename[260]; char m_szLogMsg[1024]; LOGENTRY_TYPE m_log_entry_id; bool m_bON; }; #define FLX_LOGGER Logger::getInstance() #endif
[ "marvin.kicha@e13029a8-578f-11de-8abc-d1c337b90d21" ]
[ [ [ 1, 56 ] ] ]
e8b6797fec12f6c7b43cc06f4bdcf7dcb88d999d
c6f4fe2766815616b37beccf07db82c0da27e6c1
/CameraCollisionResponse.cpp
2b36f6449fd5a313b604d5c1e83fa0919b7eabbb
[]
no_license
fragoulis/gpm-sem1-spacegame
c600f300046c054f7ab3cbf7193ccaad1503ca09
85bdfb5b62e2964588f41d03a295b2431ff9689f
refs/heads/master
2023-06-09T03:43:53.175249
2007-12-13T03:03:30
2007-12-13T03:03:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
391
cpp
#include "SpaceshipCollisionResponse.h" #include "VitalsHealth.h" #include "Object.h" using tlib::Object; using tlib::OCVitalsHealth; void SpaceshipCollisionResponse::respond( const Vector3f &vCollVector ) const { m_oOwner->setPos( m_oOwner->getPos() + vCollVector ); OCVitalsHealth *cVitals = (OCVitalsHealth*)getOwner()->getComponent("vitals"); cVitals->hit( 1 ); }
[ "john.fragkoulis@201bd241-053d-0410-948a-418211174e54" ]
[ [ [ 1, 12 ] ] ]
2dd04f1deb71b82944d2916cc243e5c18c48ae45
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/brookbox/wm2/WmlTriangle2.h
6edbb61b3fed4277e7538041abb39db2ede42c12
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
1,429
h
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #ifndef WMLTRIANGLE2_H #define WMLTRIANGLE2_H // Two different representations of the triangle are allowed. If one form is // used, the other is *not* automatically set. #include "WmlVector2.h" namespace Wml { template <class Real> class WML_ITEM Triangle2 { public: Triangle2 (); // Triangle points are tri(s,t) = b+s*e0+t*e1 where 0 <= s <= 1, // 0 <= t <= 1, and 0 <= s+t <= 1. Vector2<Real>& Origin (); const Vector2<Real>& Origin () const; Vector2<Real>& Edge0 (); const Vector2<Real>& Edge0 () const; Vector2<Real>& Edge1 (); const Vector2<Real>& Edge1 () const; // Triangle points are V0, V1, V2. Vector2<Real>& Vertex (int i); const Vector2<Real>& Vertex (int i) const; protected: // parametric form Vector2<Real> m_kOrigin; Vector2<Real> m_kEdge0; Vector2<Real> m_kEdge1; // vertex form Vector2<Real> m_akV[3]; }; typedef Triangle2<float> Triangle2f; typedef Triangle2<double> Triangle2d; } #endif
[ [ [ 1, 56 ] ] ]
0e653cda442d0131a9a217a916119978291a73d4
f241b6224086eaba2de42d674e2f189a66419a63
/old/cs4280/GroupWork/Game/Game/texture.cpp
cda51fea1bbcc4a19a9e16b7c2bc55e86c7bde27
[]
no_license
davidwiggy/Joshs-School
17c78dc953ffdc5db5fc0524248f1638b64a082c
87937141406847adcff18741882f53f1a5c44007
refs/heads/master
2020-04-08T01:25:17.915887
2011-09-24T03:51:44
2011-09-24T03:51:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,996
cpp
#include "texture.h" // LoadBitmapFile // desc: Returns a pointer to the bitmap image of the bitmap specified // by filename. Also returns the bitmap header information. // No support for 8-bit bitmaps. unsigned char *CTexture::LoadBitmapFile(char *filename, BITMAPINFOHEADER *bitmapInfoHeader) { FILE *filePtr; // the file pointer BITMAPFILEHEADER bitmapFileHeader; // bitmap file header unsigned char *bitmapImage; // bitmap image data int imageIdx = 0; // image index counter unsigned char tempRGB; // swap variable // open filename in "read binary" mode //filePtr = fopen(filename, "rb"); fopen_s(&filePtr, filename, "rb"); if (filePtr == NULL) return NULL; // read the bitmap file header fread(&bitmapFileHeader, sizeof(BITMAPFILEHEADER), 1, filePtr); // verify that this is a bitmap by checking for the universal bitmap id if (bitmapFileHeader.bfType != BITMAP_ID) { fclose(filePtr); return NULL; } // read the bitmap information header fread(bitmapInfoHeader, sizeof(BITMAPINFOHEADER), 1, filePtr); // move file pointer to beginning of bitmap data fseek(filePtr, bitmapFileHeader.bfOffBits, SEEK_SET); // allocate enough memory for the bitmap image data bitmapImage = (unsigned char*)malloc(bitmapInfoHeader->biSizeImage); // verify memory allocation if (!bitmapImage) { free(bitmapImage); fclose(filePtr); return NULL; } // read in the bitmap image data fread(bitmapImage, 1, bitmapInfoHeader->biSizeImage, filePtr); // make sure bitmap image data was read if (bitmapImage == NULL) { fclose(filePtr); return NULL; } // swap the R and B values to get RGB since the bitmap color format is in BGR for (imageIdx = 0; imageIdx < (int)bitmapInfoHeader->biSizeImage; imageIdx+=3) { tempRGB = bitmapImage[imageIdx]; bitmapImage[imageIdx] = bitmapImage[imageIdx + 2]; bitmapImage[imageIdx + 2] = tempRGB; } // close the file and return the bitmap image data fclose(filePtr); return bitmapImage; } /***************************************************************************** LoadBitmapFileWithAlpha Loads a bitmap file normally, and then adds an alpha component to use for blending *****************************************************************************/ unsigned char *CTexture::LoadBitmapFileWithAlpha(char *filename, BITMAPINFOHEADER *bitmapInfoHeader) { unsigned char *bitmapImage = LoadBitmapFile(filename, bitmapInfoHeader); unsigned char *bitmapWithAlpha = (unsigned char *)malloc(bitmapInfoHeader->biSizeImage * 4 / 3); // loop through the bitmap data for (int src = 0, dst = 0; src < (int)bitmapInfoHeader->biSizeImage; src +=3, dst +=4) { // if the pixel is black, set the alpha to 0. Otherwise, set it to 255. if (bitmapImage[src] == 0 && bitmapImage[src+1] == 0 && bitmapImage[src+2] == 0) bitmapWithAlpha[dst+3] = 0; else bitmapWithAlpha[dst+3] = 0xFF; // copy pixel data over bitmapWithAlpha[dst] = bitmapImage[src]; bitmapWithAlpha[dst+1] = bitmapImage[src+1]; bitmapWithAlpha[dst+2] = bitmapImage[src+2]; } free(bitmapImage); return bitmapWithAlpha; } // end LoadBitmapFileWithAlpha() // LoadPCXFile() // desc: loads a PCX file into memory unsigned char *CTexture::LoadPCXFile(char *filename, PCXHEADER *pcxHeader) { int idx = 0; // counter index int c; // used to retrieve a char from the file int i; // counter index int numRepeat; FILE *filePtr; // file handle int width; // pcx width int height; // pcx height unsigned char *pixelData; // pcx image data unsigned char *paletteData; // pcx palette data // open PCX file //filePtr = fopen(filename, "rb"); fopen_s(&filePtr, filename, "rb"); if (filePtr == NULL) return NULL; // retrieve first character; should be equal to 10 c = getc(filePtr); if (c != 10) { fclose(filePtr); return NULL; } // retrieve next character; should be equal to 5 c = getc(filePtr); if (c != 5) { fclose(filePtr); return NULL; } // reposition file pointer to beginning of file rewind(filePtr); // read 4 characters of data to skip fgetc(filePtr); fgetc(filePtr); fgetc(filePtr); fgetc(filePtr); // retrieve leftmost x value of PCX pcxHeader->xMin = fgetc(filePtr); // loword pcxHeader->xMin |= fgetc(filePtr) << 8; // hiword // retrieve bottom-most y value of PCX pcxHeader->yMin = fgetc(filePtr); // loword pcxHeader->yMin |= fgetc(filePtr) << 8; // hiword // retrieve rightmost x value of PCX pcxHeader->xMax = fgetc(filePtr); // loword pcxHeader->xMax |= fgetc(filePtr) << 8; // hiword // retrieve topmost y value of PCX pcxHeader->yMax = fgetc(filePtr); // loword pcxHeader->yMax |= fgetc(filePtr) << 8; // hiword // calculate the width and height of the PCX width = pcxHeader->xMax - pcxHeader->xMin + 1; height = pcxHeader->yMax - pcxHeader->yMin + 1; // allocate memory for PCX image data pixelData = (unsigned char*)malloc(width*height); // set file pointer to 128th byte of file, where the PCX image data starts fseek(filePtr, 128, SEEK_SET); // decode the pixel data and store while (idx < (width*height)) { c = getc(filePtr); if (c > 0xbf) { numRepeat = 0x3f & c; c = getc(filePtr); for (i = 0; i < numRepeat; i++) { pixelData[idx++] = c; } } else pixelData[idx++] = c; fflush(stdout); } // allocate memory for the PCX image palette paletteData = (unsigned char*)malloc(768); // palette is the last 769 bytes of the PCX file fseek(filePtr, -769, SEEK_END); // verify palette; first character should be 12 c = getc(filePtr); if (c != 12) { fclose(filePtr); return NULL; } // read and store all of palette for (i = 0; i < 768; i++) { c = getc(filePtr); paletteData[i] = c; } // close file and store palette in header fclose(filePtr); pcxHeader->palette = paletteData; // return the pixel image data return pixelData; } // LoadPCXTexture() // desc: loads a PCX image file as a texture void CTexture::LoadPCXTexture(char *filename) { PCXHEADER texInfo; // header of texture // texture_t *thisTexture; // the texture unsigned char *unscaledData;// used to calculate pcx int i; // index counter int j; // index counter int w; // width of texture int h; // height of texture // load the PCX file into the texture struct data = LoadPCXFile(filename, &texInfo); if (data == NULL) { free(data); // return NULL; } // store the texture information palette = texInfo.palette; width = texInfo.xMax - texInfo.xMin + 1; height = texInfo.yMax - texInfo.yMin + 1; textureType = PCX; w = width; h = height; // allocate memory for the unscaled data unscaledData = (unsigned char*)malloc(w*h*4); // store the unscaled data via the palette for (j = 0; j < h; j++) { for (i = 0; i < w; i++) { unscaledData[4*(j*w+i)+0] = (unsigned char)palette[3*data[j*w+i]+0]; unscaledData[4*(j*w+i)+1] = (unsigned char)palette[3*data[j*w+i]+1]; unscaledData[4*(j*w+i)+2] = (unsigned char)palette[3*data[j*w+i]+2]; unscaledData[4*(j*w+i)+3] = (unsigned char)255; } } // find width and height's nearest greater power of 2 // find width's i = 0; while (w) { w /= 2; i++; } scaledHeight = (long)pow(2.0, i-1); // find height's i = 0; while (h) { h /= 2; i++; } scaledWidth = (long)pow(2.0, i-1); // clear the texture data if (data != NULL) { free(data); data = NULL; } // reallocate memory for the texture data data = (unsigned char*)malloc(scaledWidth*scaledHeight*4); // use the GL utility library to scale the texture to the unscaled dimensions gluScaleImage(GL_RGBA, this->width, this->height, GL_UNSIGNED_BYTE, unscaledData, scaledWidth, scaledHeight, GL_UNSIGNED_BYTE, data); free(unscaledData); // return thisTexture; } // LoadBMPTexture() // desc: loads a texture of the BMP format void CTexture::LoadBMPTexture(char *filename) { BITMAPINFOHEADER texInfo; // BMP header // store BMP data in texture data = LoadBitmapFileWithAlpha(filename, &texInfo); if (data == NULL) { free(data); } // store texture information width = texInfo.biWidth; height = texInfo.biHeight; palette = NULL; scaledHeight = 0; scaledWidth = 0; textureType = BMP; } // LoadTexture() // desc: loads a texture given the filename void CTexture::LoadTexture(char *filename) { char *extStr; // get extension from filename extStr = strchr(filename, '.'); extStr++; // set the texture type based on extension of filename if ((_strcmpi(extStr, "BMP") == 0) || (_strcmpi(extStr, "bmp") == 0)) LoadBMPTexture(filename); else if ((_strcmpi(extStr, "PCX") == 0) || (_strcmpi(extStr, "pcx") == 0) ) LoadPCXTexture(filename); else if ((_strcmpi(extStr, "TGA") == 0) || (_strcmpi(extStr, "tga") == 0) ) LoadTGATexture(filename); } // LoadTGAFile() // desc: loads a TGA file defined by filename unsigned char *CTexture::LoadTGAFile(char *filename, TGAHEADER *tgaHeader) { FILE *filePtr; unsigned char ucharBad; // garbage data short int sintBad; // garbage data long imageSize; // size of TGA image int colorMode; // 4 for RGBA, 3 for RGB long imageIdx; // counter variable unsigned char colorSwap; // swap variable unsigned char *imageData; // the TGA data // open the TGA file //filePtr = fopen(filename, "rb"); fopen_s(&filePtr, filename, "rb"); if (!filePtr) return NULL; // read first two bytes of garbage fread(&ucharBad, sizeof(unsigned char), 1, filePtr); fread(&ucharBad, sizeof(unsigned char), 1, filePtr); // read in the image type fread(&tgaHeader->imageTypeCode, sizeof(unsigned char), 1, filePtr); // for our purposes, the image type should be either a 2 or a 3 if ((tgaHeader->imageTypeCode != 2) && (tgaHeader->imageTypeCode != 3)) { fclose(filePtr); return NULL; } // read 13 bytes of garbage data fread(&sintBad, sizeof(short int), 1, filePtr); fread(&sintBad, sizeof(short int), 1, filePtr); fread(&ucharBad, sizeof(unsigned char), 1, filePtr); fread(&sintBad, sizeof(short int), 1, filePtr); fread(&sintBad, sizeof(short int), 1, filePtr); // read image dimensions fread(&tgaHeader->imageWidth, sizeof(short int), 1, filePtr); fread(&tgaHeader->imageHeight, sizeof(short int), 1, filePtr); // read bit depth fread(&tgaHeader->bitCount, sizeof(unsigned char), 1, filePtr); // read garbage fread(&ucharBad, sizeof(unsigned char), 1, filePtr); // colormode -> 3 = BGR, 4 = BGRA colorMode = tgaHeader->bitCount / 8; imageSize = tgaHeader->imageWidth * tgaHeader->imageHeight * colorMode; // allocate memory for image data imageData = (unsigned char*)malloc(sizeof(unsigned char)*imageSize); // read image data fread(imageData, sizeof(unsigned char), imageSize, filePtr); // change BGR to RGB so OpenGL can use the data for (imageIdx = 0; imageIdx < imageSize; imageIdx += colorMode) { colorSwap = imageData[imageIdx]; imageData[imageIdx] = imageData[imageIdx+2]; imageData[imageIdx + 2] = colorSwap; } // close the file fclose(filePtr); return imageData; } // LoadTGATexture() // desc: loads a TGA as a texture void CTexture::LoadTGATexture(char *filename) { TGAHEADER tga; // BMP header // store BMP data in texture data = LoadTGAFile(filename, &tga); if (data == NULL) { free(data); } // store texture information width = tga.imageWidth; height = tga.imageHeight; palette = NULL; scaledHeight = 0; scaledWidth = 0; tgaImageCode = tga.imageTypeCode; bitDepth = tga.bitCount; textureType = TGA; }
[ "arnie@67c49fff-0526-0410-8e7c-b4c1397322bd" ]
[ [ [ 1, 442 ] ] ]
ace3e3505072073726cbb4889a01f32aac727760
51e1cf5dc3b99e8eecffcf5790ada07b2f03f39c
/FileAssistant++/Source/CUSBManager.cpp
21152ebe932b53f25584e7668384cf83a8ffc4ea
[]
no_license
jdek/jim-pspware
c3e043b59a69cf5c28daf62dc9d8dca5daf87589
fd779e1148caac2da4c590844db7235357b47f7e
refs/heads/master
2021-05-31T06:45:03.953631
2007-06-25T22:45:26
2007-06-25T22:45:26
56,973,047
2
1
null
null
null
null
UTF-8
C++
false
false
5,205
cpp
/*********************************************************************************** Module : CUSBManager.cpp Description : Last Modified $Date: $ $Revision: $ Copyright (C) 01 August 2005 T Swann ***********************************************************************************/ //********************************************************************************** // Include Files //********************************************************************************** #include "CTypes.h" #include <pspusb.h> #include <pspusbstor.h> #include "CUSBManager.h" #include "CFrameWork.h" //********************************************************************************** // Local Macros //********************************************************************************** //********************************************************************************** // Local Constants //********************************************************************************** //********************************************************************************** // Static Prototypes //********************************************************************************** //********************************************************************************** // Global Variables //********************************************************************************** //********************************************************************************** // Static Variables //********************************************************************************** //********************************************************************************** // Class Definition //********************************************************************************** //************************************************************************************* // //************************************************************************************* bool CUSBManager::Open() { // // Start necessary drivers // CFrameWork::LoadAndStartModule( "flash0:/kd/semawm.prx", CFrameWork::KERNEL_PARTITION ); CFrameWork::LoadAndStartModule( "flash0:/kd/usbstor.prx", CFrameWork::KERNEL_PARTITION ); CFrameWork::LoadAndStartModule( "flash0:/kd/usbstormgr.prx", CFrameWork::KERNEL_PARTITION ); CFrameWork::LoadAndStartModule( "flash0:/kd/usbstorms.prx", CFrameWork::KERNEL_PARTITION ); CFrameWork::LoadAndStartModule( "flash0:/kd/usbstorboot.prx", CFrameWork::KERNEL_PARTITION ); // // Setup USB drivers // if ( sceUsbStart( PSP_USBBUS_DRIVERNAME, 0, 0 ) != 0 ) { ASSERT( 0, "Error starting USB Bus driver\n" ); return false; } if ( sceUsbStart( PSP_USBSTOR_DRIVERNAME, 0, 0 ) != 0 ) { ASSERT( 0, "Error starting USB Mass Storage driver\n " ); return false; } if ( sceUsbstorBootSetCapacity( 0x800000 ) != 0 ) { ASSERT( 0, "Error setting capacity with USB Mass Storage driver\n" ); return false; } return true; } //************************************************************************************* // //************************************************************************************* void CUSBManager::Close() { if ( IsActive() == true ) { if ( Deactivate() == false ) { ASSERT( 0, "Error closing USB connection" ); } } if ( sceUsbStop( PSP_USBSTOR_DRIVERNAME, 0, 0 ) != 0 ) { ASSERT( 0, "Error stopping USB Mass Storage driver\n" ); } if ( sceUsbStop( PSP_USBBUS_DRIVERNAME, 0, 0 ) != 0 ) { ASSERT( 0, "Error stopping USB BUS driver\n" ); } } //************************************************************************************* // //************************************************************************************* bool CUSBManager::Activate() { if ( sceUsbGetState() & PSP_USB_ACTIVATED ) { return false; } return ( sceUsbActivate( 0x1c8 ) == 0 ); } //************************************************************************************* // //************************************************************************************* bool CUSBManager::Deactivate() { if ( sceUsbGetState() & PSP_USB_ACTIVATED ) { return ( sceUsbDeactivate() == 0 ); } return false; } //************************************************************************************* // //************************************************************************************* bool CUSBManager::IsActive() { return ( sceUsbGetState() & PSP_USB_ACTIVATED ); } //********************************************************************************** // //********************************************************************************** bool CUSBManager::CableConnected() { return ( sceUsbGetState() & PSP_USB_CABLE_CONNECTED ); } //********************************************************************************** // //********************************************************************************** bool CUSBManager::ConnectionEstablished() { return ( sceUsbGetState() & PSP_USB_CONNECTION_ESTABLISHED ); } //******************************* END OF FILE ************************************
[ "71m@ff2c0c17-07fa-0310-a4bd-d48831021cb5" ]
[ [ [ 1, 163 ] ] ]
93416ec1875325ccf73e052877f5aa540ecdac69
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/Tools/FontViewer/FontView.h
067a1fb9b2180ad68d27e1cb913e0f5e98330638
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
411
h
/*! @file @author Albert Semenov @date 09/2008 */ #ifndef __FONT_VIEW_H__ #define __FONT_VIEW_H__ #include <MyGUI.h> #include "BaseLayout/BaseLayout.h" namespace demo { class FontView : public wraps::BaseLayout { public: FontView(); void setFontName(const std::string& _value); private: MyGUI::Edit* mEditView; }; } // namespace demo #endif // __FONT_VIEW_H__
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 28 ] ] ]
7856a2193c956335302d46dbef84192934e4d801
d6a28d9d845a20463704afe8ebe644a241dc1a46
/source/Irrlicht/CGUIEnvironment.h
16ca8ea6fce310ff02ec46d4eec0c1baf012893e
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive", "Zlib" ]
permissive
marky0720/irrlicht-android
6932058563bf4150cd7090d1dc09466132df5448
86512d871eeb55dfaae2d2bf327299348cc5202c
refs/heads/master
2021-04-30T08:19:25.297407
2010-10-08T08:27:33
2010-10-08T08:27:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,233
h
// Copyright (C) 2002-2009 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef __C_GUI_ENVIRONMENT_H_INCLUDED__ #define __C_GUI_ENVIRONMENT_H_INCLUDED__ #include "IrrCompileConfig.h" #ifdef _IRR_COMPILE_WITH_GUI_ #include "IGUIEnvironment.h" #include "IGUIElement.h" #include "irrArray.h" #include "IFileSystem.h" #include "IOSOperator.h" namespace irr { namespace io { class IXMLWriter; } namespace gui { class CGUIEnvironment : public IGUIEnvironment, public IGUIElement { public: //! constructor CGUIEnvironment(io::IFileSystem* fs, video::IVideoDriver* driver, IOSOperator* op); //! destructor virtual ~CGUIEnvironment(); //! draws all gui elements virtual void drawAll(); //! returns the current video driver virtual video::IVideoDriver* getVideoDriver() const; //! returns pointer to the filesystem virtual io::IFileSystem* getFileSystem() const; //! returns a pointer to the OS operator virtual IOSOperator* getOSOperator() const; //! posts an input event to the environment virtual bool postEventFromUser(const SEvent& event); //! This sets a new event receiver for gui events. Usually you do not have to //! use this method, it is used by the internal engine. virtual void setUserEventReceiver(IEventReceiver* evr); //! removes all elements from the environment virtual void clear(); //! called if an event happened. virtual bool OnEvent(const SEvent& event); //! returns the current gui skin virtual IGUISkin* getSkin() const; //! Sets a new GUI Skin virtual void setSkin(IGUISkin* skin); //! Creates a new GUI Skin based on a template. /** \return Returns a pointer to the created skin. If you no longer need the skin, you should call IGUISkin::drop(). See IReferenceCounted::drop() for more information. */ virtual IGUISkin* createSkin(EGUI_SKIN_TYPE type); //! Creates the image list from the given texture. virtual IGUIImageList* createImageList( video::ITexture* texture, core::dimension2d<s32> imageSize, bool useAlphaChannel ); //! returns the font virtual IGUIFont* getFont(const io::path& filename); //! add an externally loaded font virtual IGUIFont* addFont(const io::path& name, IGUIFont* font); //! returns default font virtual IGUIFont* getBuiltInFont() const; //! returns the sprite bank virtual IGUISpriteBank* getSpriteBank(const io::path& filename); //! returns the sprite bank virtual IGUISpriteBank* addEmptySpriteBank(const io::path& name); //! adds an button. The returned pointer must not be dropped. virtual IGUIButton* addButton(const core::rect<s32>& rectangle, IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0,const wchar_t* tooltiptext = 0); //! adds a window. The returned pointer must not be dropped. virtual IGUIWindow* addWindow(const core::rect<s32>& rectangle, bool modal = false, const wchar_t* text=0, IGUIElement* parent=0, s32 id=-1); //! adds a modal screen. The returned pointer must not be dropped. virtual IGUIElement* addModalScreen(IGUIElement* parent); //! Adds a message box. virtual IGUIWindow* addMessageBox(const wchar_t* caption, const wchar_t* text=0, bool modal = true, s32 flag = EMBF_OK, IGUIElement* parent=0, s32 id=-1, video::ITexture* image=0); //! adds a scrollbar. The returned pointer must not be dropped. virtual IGUIScrollBar* addScrollBar(bool horizontal, const core::rect<s32>& rectangle, IGUIElement* parent=0, s32 id=-1); //! Adds an image element. virtual IGUIImage* addImage(video::ITexture* image, core::position2d<s32> pos, bool useAlphaChannel=true, IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0); //! adds an image. The returned pointer must not be dropped. virtual IGUIImage* addImage(const core::rect<s32>& rectangle, IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0); //! adds a checkbox virtual IGUICheckBox* addCheckBox(bool checked, const core::rect<s32>& rectangle, IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0); //! adds a list box virtual IGUIListBox* addListBox(const core::rect<s32>& rectangle, IGUIElement* parent=0, s32 id=-1, bool drawBackground=false); //! adds a tree view virtual IGUITreeView* addTreeView(const core::rect<s32>& rectangle, IGUIElement* parent=0, s32 id=-1, bool drawBackground=false, bool scrollBarVertical = true, bool scrollBarHorizontal = false); //! adds an mesh viewer. The returned pointer must not be dropped. virtual IGUIMeshViewer* addMeshViewer(const core::rect<s32>& rectangle, IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0); //! Adds a file open dialog. virtual IGUIFileOpenDialog* addFileOpenDialog(const wchar_t* title = 0, bool modal=true, IGUIElement* parent=0, s32 id=-1); //! Adds a color select dialog. virtual IGUIColorSelectDialog* addColorSelectDialog(const wchar_t* title = 0, bool modal=true, IGUIElement* parent=0, s32 id=-1); //! adds a static text. The returned pointer must not be dropped. virtual IGUIStaticText* addStaticText(const wchar_t* text, const core::rect<s32>& rectangle, bool border=false, bool wordWrap=true, IGUIElement* parent=0, s32 id=-1, bool drawBackground = false); //! Adds an edit box. The returned pointer must not be dropped. virtual IGUIEditBox* addEditBox(const wchar_t* text, const core::rect<s32>& rectangle, bool border=false, IGUIElement* parent=0, s32 id=-1); //! Adds a spin box to the environment virtual IGUISpinBox* addSpinBox(const wchar_t* text, const core::rect<s32>& rectangle, bool border=false,IGUIElement* parent=0, s32 id=-1); //! Adds a tab control to the environment. virtual IGUITabControl* addTabControl(const core::rect<s32>& rectangle, IGUIElement* parent=0, bool fillbackground=false, bool border=true, s32 id=-1); //! Adds tab to the environment. virtual IGUITab* addTab(const core::rect<s32>& rectangle, IGUIElement* parent=0, s32 id=-1); //! Adds a context menu to the environment. virtual IGUIContextMenu* addContextMenu(const core::rect<s32>& rectangle, IGUIElement* parent=0, s32 id=-1); //! Adds a menu to the environment. virtual IGUIContextMenu* addMenu(IGUIElement* parent=0, s32 id=-1); //! Adds a toolbar to the environment. It is like a menu is always placed on top //! in its parent, and contains buttons. virtual IGUIToolBar* addToolBar(IGUIElement* parent=0, s32 id=-1); //! Adds a combo box to the environment. virtual IGUIComboBox* addComboBox(const core::rect<s32>& rectangle, IGUIElement* parent=0, s32 id=-1); //! Adds a table element. virtual IGUITable* addTable(const core::rect<s32>& rectangle, IGUIElement* parent=0, s32 id=-1, bool drawBackground=false); //! sets the focus to an element virtual bool setFocus(IGUIElement* element); //! removes the focus from an element virtual bool removeFocus(IGUIElement* element); //! Returns if the element has focus virtual bool hasFocus(IGUIElement* element) const; //! Returns the element with the focus virtual IGUIElement* getFocus() const; //! Adds an element for fading in or out. virtual IGUIInOutFader* addInOutFader(const core::rect<s32>* rectangle=0, IGUIElement* parent=0, s32 id=-1); //! Returns the root gui element. virtual IGUIElement* getRootGUIElement(); virtual void OnPostRender( u32 time ); //! Returns the default element factory which can create all built in elements virtual IGUIElementFactory* getDefaultGUIElementFactory() const; //! Adds an element factory to the gui environment. /** Use this to extend the gui environment with new element types which it should be able to create automaticly, for example when loading data from xml files. */ virtual void registerGUIElementFactory(IGUIElementFactory* factoryToAdd); //! Returns amount of registered scene node factories. virtual u32 getRegisteredGUIElementFactoryCount() const; //! Returns a scene node factory by index virtual IGUIElementFactory* getGUIElementFactory(u32 index) const; //! Adds a GUI Element by its name virtual IGUIElement* addGUIElement(const c8* elementName, IGUIElement* parent=0); //! Saves the current gui into a file. /** \param filename: Name of the file. \param start: The element to start saving from. if not specified, the root element will be used */ virtual bool saveGUI( const io::path& filename, IGUIElement* start=0); //! Saves the current gui into a file. /** \param file: The file to save the GUI to. \param start: The element to start saving from. if not specified, the root element will be used */ virtual bool saveGUI(io::IWriteFile* file, IGUIElement* start=0); //! Loads the gui. Note that the current gui is not cleared before. /** \param filename: Name of the file. \param parent: The parent of all loaded GUI elements, if not specified, the root element will be used */ virtual bool loadGUI(const io::path& filename, IGUIElement* parent=0); //! Loads the gui. Note that the current gui is not cleared before. /** \param file: IReadFile to load the GUI from \param parent: The parent of all loaded GUI elements, if not specified, the root element will be used */ virtual bool loadGUI(io::IReadFile* file, IGUIElement* parent=0); //! Writes attributes of the environment virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const; //! Reads attributes of the environment. virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0); //! writes an element virtual void writeGUIElement(io::IXMLWriter* writer, IGUIElement* node); //! reads an element virtual void readGUIElement(io::IXMLReader* reader, IGUIElement* node); private: IGUIElement* getNextElement(bool reverse=false, bool group=false); void updateHoveredElement(core::position2d<s32> mousePos); void loadBuiltInFont(); struct SFont { io::SNamedPath NamedPath; IGUIFont* Font; bool operator < (const SFont& other) const { return (NamedPath < other.NamedPath); } }; struct SSpriteBank { io::SNamedPath NamedPath; IGUISpriteBank* Bank; bool operator < (const SSpriteBank& other) const { return (NamedPath < other.NamedPath); } }; struct SToolTip { IGUIStaticText* Element; u32 LastTime; u32 EnterTime; u32 LaunchTime; u32 RelaunchTime; }; SToolTip ToolTip; core::array<IGUIElementFactory*> GUIElementFactoryList; core::array<SFont> Fonts; core::array<SSpriteBank> Banks; video::IVideoDriver* Driver; IGUIElement* Hovered; IGUIElement* HoveredNoSubelement; // subelements replaced by their parent, so you only have 'real' elements here IGUIElement* Focus; core::position2d<s32> LastHoveredMousePos; IGUISkin* CurrentSkin; io::IFileSystem* FileSystem; IEventReceiver* UserReceiver; IOSOperator* Operator; }; } // end namespace gui } // end namespace irr #endif // _IRR_COMPILE_WITH_GUI_ #endif // __C_GUI_ENVIRONMENT_H_INCLUDED__
[ "hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475", "bitplane@dfc29bdd-3216-0410-991c-e03cc46cb475", "irrlicht@dfc29bdd-3216-0410-991c-e03cc46cb475", "engineer_apple@dfc29bdd-3216-0410-991c-e03cc46cb475", "cutealien@dfc29bdd-3216-0410-991c-e03cc46cb475" ]
[ [ [ 1, 1 ], [ 5, 6 ], [ 40, 40 ], [ 43, 43 ], [ 46, 46 ], [ 49, 49 ], [ 59, 59 ], [ 62, 62 ], [ 74, 75 ], [ 78, 78 ], [ 80, 84 ], [ 87, 87 ], [ 90, 90 ], [ 96, 96 ], [ 110, 110 ], [ 115, 115 ], [ 135, 136 ], [ 144, 144 ], [ 148, 148 ], [ 155, 155 ], [ 175, 175 ], [ 185, 185 ], [ 188, 188 ], [ 193, 193 ], [ 199, 199 ], [ 207, 207 ], [ 210, 210 ], [ 217, 219 ], [ 223, 223 ], [ 229, 229 ], [ 231, 231 ], [ 235, 235 ], [ 237, 237 ], [ 240, 240 ], [ 249, 249 ], [ 255, 258 ], [ 283, 283 ], [ 285, 285 ], [ 287, 287 ], [ 290, 290 ], [ 298, 298 ], [ 312, 312 ] ], [ [ 2, 4 ], [ 7, 39 ], [ 41, 42 ], [ 44, 45 ], [ 47, 48 ], [ 50, 58 ], [ 60, 61 ], [ 63, 69 ], [ 71, 72 ], [ 77, 77 ], [ 85, 86 ], [ 88, 89 ], [ 91, 95 ], [ 97, 103 ], [ 105, 106 ], [ 109, 109 ], [ 111, 114 ], [ 116, 124 ], [ 130, 134 ], [ 137, 143 ], [ 145, 147 ], [ 150, 154 ], [ 156, 174 ], [ 176, 184 ], [ 186, 187 ], [ 189, 192 ], [ 194, 198 ], [ 200, 206 ], [ 208, 209 ], [ 211, 216 ], [ 220, 222 ], [ 224, 228 ], [ 230, 230 ], [ 232, 234 ], [ 236, 236 ], [ 238, 239 ], [ 241, 248 ], [ 250, 254 ], [ 259, 260 ], [ 262, 265 ], [ 267, 271 ], [ 273, 276 ], [ 278, 282 ], [ 284, 284 ], [ 286, 286 ], [ 288, 289 ], [ 291, 297 ], [ 299, 311 ], [ 313, 314 ] ], [ [ 70, 70 ] ], [ [ 73, 73 ], [ 76, 76 ], [ 79, 79 ], [ 107, 108 ], [ 125, 129 ], [ 149, 149 ] ], [ [ 104, 104 ], [ 261, 261 ], [ 266, 266 ], [ 272, 272 ], [ 277, 277 ] ] ]
9c4250d22daf21d273c5f25d433994487f094102
8e4d21a99d0ce5413eab7a083544aff9f944b26f
/src/NthContourProcess.cpp
b24301c009f1a9da2ba284ef4991a55a62eb267a
[]
no_license
wangjunbao/nontouchsdk
957612b238b8b221b4284efb377db220bd41186a
81ab8519ea1af45dbb7ff66c6784961f14f9930c
refs/heads/master
2021-01-23T13:57:20.020732
2010-10-31T12:03:49
2010-10-31T12:03:49
34,656,556
0
0
null
null
null
null
UTF-8
C++
false
false
316
cpp
/* * NthContourProcess.cpp * CopyRight @South China Institute of Software Engineering,.GZU * Author: * 2010/10/20 */ #ifndef DLL_FILE #define DLL_FILE #endif #include "NthContourProcess.h" NthContourProcess::NthContourProcess(void) { } NthContourProcess::~NthContourProcess(void) { }
[ "tinya0913@6b3f5b0f-ac10-96f7-b72e-cc4b20d3e213" ]
[ [ [ 1, 21 ] ] ]
f0617ad3d23e747293fe7e66da44c3d137520a79
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/Bowling/trunk/Source/LethalBowling/Drawer.cpp
c3fc5a0a3640062ea2986039bb8d5d7af4367446
[]
no_license
argapratama/kucgbowling
20dbaefe1596358156691e81ccceb9151b15efb0
65e40b6f33c5511bddf0fa350c1eefc647ace48a
refs/heads/master
2018-01-08T15:27:44.784437
2011-06-19T15:23:39
2011-06-19T15:23:39
36,738,655
0
0
null
null
null
null
UTF-8
C++
false
false
463
cpp
#include "Drawer.h" #include <gl/GL.h> namespace Virgin { Drawer::Drawer(void) : translateX_(0.0) , translateY_(0.0) , translateZ_(0.0) { } Drawer::~Drawer(void) { } void Drawer::TranslateTo(float x, float y, float z) { translateX_ = x; translateY_ = y; translateZ_ = z; } void Drawer::TranslateMore(float x, float y, float z) { TranslateTo(translateX_ + x, translateY_ + y, translateZ_ + z); } }
[ [ [ 1, 31 ] ] ]
40f2095384d381156bbe17b6dfff2fe7bab3f62b
eeb949f6fe65b1177ac7426a937ef96b0d4d1e22
/srcanamdw/appdep/src/appdep.cpp
a90a486ffe5b7ec189bbb03ec181f74d851b9cd9
[]
no_license
SymbianSource/oss.FCL.sftools.ana.staticanamdw
bd2d6b6208f473aa03e2a23c1f7d8679c235c11d
f2f134dfc41d34af79e682c1d78a6c45a14206b0
refs/heads/master
2020-12-24T12:28:54.126034
2010-02-18T06:59:02
2010-02-18T06:59:02
72,998,870
0
0
null
null
null
null
UTF-8
C++
false
false
8,910
cpp
/* * Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Main entry of Appdep * */ #include "appdep.hpp" // init globals bool _cl_use_gcc = false; bool _cl_use_gcce = false; bool _cl_use_rvct = false; bool _cl_generate_clean_cache = false; bool _cl_update_cache = false; bool _cl_use_libs = false; bool _cl_show_ordinals = false; bool _cl_use_udeb = false; bool _cl_print_debug = false; bool _some_cache_needs_update = false; string _cl_toolsdir = ""; string _cl_cachedir = ""; string _cl_releasedir = ""; string _cl_targets = ""; string _cl_cfiltloc = ""; string _cl_outputfile = ""; string _cl_configfile = ""; string _cl_sisfiles = ""; string _cl_usestaticdepstxt = ""; string _cl_properties = ""; string _cl_staticdeps = ""; string _cl_dependson = ""; string _cl_showfunctions = ""; string _cl_usesfunction = ""; string _gcc_nm_location = ""; string _gcce_nm_location = ""; string _gcce_readelf_location = ""; string _gcce_cfilt_location = ""; string _rvct_armar_location = ""; string _rvct_fromelf_location = ""; string _rvct_cfilt_location = ""; string _petran_location = ""; string _dumpsis_location = ""; string _tempfile_location = ""; string _target_mode = ""; vector<target> _targets; vector<binary_info> _all_binary_infos; vector<import_library_info> _all_import_library_infos; vector<import_library_info> _changed_import_libraries; vector<string> _sisfiles; unsigned int _current_progress = 0; unsigned int _current_progress_percentage = 0; unsigned int _max_progress = 0; ofstream _outputf; int _CRT_glob = 0; // globbing not supported // ---------------------------------------------------------------------------------------------------------- int main(int argc, char* argv[]) { // parse command line arguments ParseCommandLineParameters(argc, argv); // read from StaticDependencies.txt if in use if (!_cl_usestaticdepstxt.empty()) { GetDataFromStaticDependenciesTxt(); } // otherwise do normal cache operations else { // first do some checks DoInitialChecksAndPreparations(); ParseTargets(); // checks for sis files if in use if (!_cl_sisfiles.empty()) DoInitialChecksAndPreparationsForSisFiles(); // try to read data from caches if (!_cl_generate_clean_cache) { for (unsigned int i=0; i<_targets.size(); i++) // loop each target { if (_targets.at(i).cache_files_valid) { ReadDataFromSymbolTablesCache(_targets.at(i)); if (_targets.at(i).cache_files_valid) ReadDataFromDependenciesCache(_targets.at(i)); else _some_cache_needs_update = true; } else { _some_cache_needs_update = true; } } } } // check if cache needs generation or update if (_cl_generate_clean_cache || _cl_update_cache || _some_cache_needs_update) { // before starting generating cache, we need more checks that user given params are correct DoCacheGenerationChecksAndPreparations(); if (_cl_generate_clean_cache) cerr << "Generating cache files at " << _cl_cachedir << " "; else cerr << "Updating cache files at " << _cl_cachedir << " "; // get lists of files from the directories FindImportLibrariesAndBinariesFromReleases(); // init progress values if (_max_progress == 0) _max_progress = 1; if (_cl_print_debug) cerr << endl; else ShowProgressInfo(_current_progress_percentage, _current_progress, _max_progress, true); // get import libaries of each target and then write that data to the caches for (unsigned int i=0; i<_targets.size(); i++) // loop each target { GetDataFromImportTables(_targets.at(i)); // write data only if current file is not valid if (!_targets.at(i).cache_files_valid) { WriteDataToSymbolTableCacheFile(_targets.at(i)); } // append all data to common vector for (unsigned int j=0; j<_targets.at(i).import_libraries.size(); j++) // loop all binaries in one target { _all_import_library_infos.push_back(_targets.at(i).import_libraries.at(j)); } // clear the original vector to save RAM since it is not needed anymore _targets.at(i).import_libraries.clear(); } // get dependency data and write it to the cache files for (unsigned int i=0; i<_targets.size(); i++) // loop each target { GetDataFromBinaries(_targets.at(i)); if (!_targets.at(i).cache_files_valid) // only write cache if it needs updating { WriteDataToDependenciesCacheFile(_targets.at(i)); } } cerr << endl; } // if sis files in use and not done any previous operations, some things must be done else if (!_cl_sisfiles.empty()) { // check Petran can be found SetAndCheckPetranPath(); for (unsigned int i=0; i<_targets.size(); i++) // loop each target { // append all data to common vector for (unsigned int j=0; j<_targets.at(i).import_libraries.size(); j++) // loop all import libraries in one target { // get a binary info data _all_import_library_infos.push_back(_targets.at(i).import_libraries.at(j)); } // clear the original vector to save RAM since it is not needed anymore _targets.at(i).import_libraries.clear(); } } // include sis files to analysis if in use if (!_cl_sisfiles.empty()) AnalyseSisFiles(); // do the analysis if (_cl_properties.empty() && _cl_staticdeps.empty() && _cl_dependson.empty() && _cl_showfunctions.empty() && _cl_usesfunction.empty()) { cerr << "Nothing to do." << endl; } else { // copy binary_info vectors to a single one if (_cl_usestaticdepstxt.empty()) { for (unsigned int i=0; i<_targets.size(); i++) // loop all targets { for (unsigned int j=0; j<_targets.at(i).binaries.size(); j++) // loop all binaries in one target { // get a binary info data _all_binary_infos.push_back(_targets.at(i).binaries.at(j)); } // clear the original vector to save RAM _targets.at(i).binaries.clear(); } } if (!_cl_properties.empty()) { // show properties of the binary file DisplayProperties(_cl_properties); } if (!_cl_staticdeps.empty()) { // determine all static dependencies of selected component DisplayStaticDependencies(_cl_staticdeps); } if (!_cl_dependson.empty()) { // list all components that depends on selected component DisplayDependents(_cl_dependson); } if (!_cl_showfunctions.empty()) { // determine all functions that are included / supported in selected component DisplayFunctions(_cl_showfunctions); } if (!_cl_usesfunction.empty()) { // list all components that are using selected function DisplayUsesFunction(_cl_usesfunction); } } // close output file if (_outputf.is_open()) { _outputf.close(); } // delete the temporary file if (!_tempfile_location.empty()) RemoveFile(_tempfile_location); return EXIT_NORMAL; } // ----------------------------------------------------------------------------------------------------------
[ "none@none" ]
[ [ [ 1, 278 ] ] ]
d90c913480ef89a821fa8870ef78e60a264f1312
800b5ac63b77e8db5ae4d5ad29bc3e1b2ba8ad44
/battletamagotchi/src/gambi.cpp
d92e39664b9bc4c474a843de07a2d4ae0caafb04
[]
no_license
Juanma-lach/battletamagotchi
acf248e89a081b1bdcfb215ff7a635e166a61dd2
b73c0013e243fdf5a4ff12faedcafabe57f5da6d
refs/heads/master
2021-01-10T15:54:05.781544
2008-11-09T04:00:10
2008-11-09T04:00:10
44,135,556
0
0
null
null
null
null
UTF-8
C++
false
false
351
cpp
#include <e32base.h> // for Symbian classes. #include "base/gambi.h" static TInt stack_counter = 0; void stack_push(void* ptr){ CleanupStack::PushL(ptr); stack_counter++; } void stack_pop(void* ptr){ CleanupStack::Pop(ptr); stack_counter--; } void stack_clean(void){ CleanupStack::PopAndDestroy(stack_counter); }
[ "desadoc@f8173780-9f05-11dd-9dc9-65bc890fb60a" ]
[ [ [ 1, 23 ] ] ]
d7bd2208de0e389ddc145d7844ac28522d91f2fa
e9944cc3f8c362cd0314a2d7a01291ed21de19ee
/ xcommon/HWPenIme/immex.cpp
89ee0e4f4a21fe9c7a288cf483a3ce4ace73416b
[]
no_license
wermanhme1990/xcommon
49d7185a28316d46992ad9311ae9cdfe220cb586
c9b1567da1f11e7a606c6ed638a9fde1f6ece577
refs/heads/master
2016-09-06T12:43:43.593776
2008-12-05T04:24:11
2008-12-05T04:24:11
39,864,906
2
0
null
null
null
null
GB18030
C++
false
false
123
cpp
//实现输入法中不常用的接口,一般只有定义,不具体实现 #include "stdafx.h" #include "HWPenIme.h"
[ [ [ 1, 3 ] ] ]
6f88729e16bc8e2a14ffa38bb2d92d95bdc09c79
d8f64a24453c6f077426ea58aaa7313aafafc75c
/Logger.cpp
0c3b5e376c23c288ce1d72e16743db2f55930165
[]
no_license
dotted/wfto
5b98591645f3ddd72cad33736da5def09484a339
6eebb66384e6eb519401bdd649ae986d94bcaf27
refs/heads/master
2021-01-20T06:25:20.468978
2010-11-04T21:01:51
2010-11-04T21:01:51
32,183,921
1
0
null
null
null
null
UTF-8
C++
false
false
2,480
cpp
#include <windows.h> #include <gl\gl.h> #include <stdio.h> #include <fstream> #include "Logger.h" using namespace std; namespace utils { GLint CLogger::indices = 0; CLogger::CLogger() { } CLogger::~CLogger() { } DWORD st[100]; GLvoid CLogger::setEntryStart() { st[getNextFreeIndex()]=timeGetTime(); } GLint CLogger::getNextFreeIndex() { return indices++; } GLint CLogger::getLastIndex() { return --indices; } GLvoid CLogger::setEntryEnd(const char *text, ...) { GLint ref = getLastIndex(); static bool first_line=true; if (first_line) { SYSTEMTIME systime; GetSystemTime(&systime); char date[100]; sprintf(date,"%d.%d.%d - %d:%d:%d",systime.wDay,systime.wMonth,systime.wYear,systime.wHour,systime.wMinute,systime.wSecond); FILE *log_file=fopen("logger.log","wc"); if (!log_file) { return; } first_line=false; char string[100]; sprintf(string,"New entry: %s\n------------------------------\n",date); fwrite(string,1,strlen(string),log_file); fclose(log_file); } char string[256]; va_list ap; if (text == NULL) { return; } va_start(ap,text); GLint string_length=vsprintf(string,text,ap); va_end(ap); FILE *log_file=fopen("logger.log","a"); if (!log_file) { return; } if (ref==-1) { string[string_length]='\n'; } if (ref!=-1) { char line[256]; for (int i=0; i<256; i++) { line[i] = ' '; } for (int i=0; i<string_length; i++) { line[i] = string[i]; } string_length=sprintf(string,"Time taken: %d ms\n",timeGetTime()-st[ref]); memcpy(line+64,string,string_length); fwrite(line,1,string_length+64,log_file); } fclose(log_file); } GLvoid CLogger::addEntry(const char *text, ...) { char string[256]; va_list ap; if (text == NULL) { return; } va_start(ap,text); GLint string_length=vsprintf(string,text,ap); va_end(ap); FILE *log_file=fopen("logger.log","a"); if (!log_file) { return; } fwrite(string,1,string_length,log_file); fclose(log_file); } GLvoid CLogger::getLog(vector<string> &log) { ifstream iFile; iFile.open("logger.log",ios_base::in); char line[512]; while (iFile.good()) { iFile.getline(line,512,'\n'); log.push_back(string(line)); } iFile.close(); } };
[ [ [ 1, 153 ] ] ]
931978f5fcdc1ef4e7ff00d2ac13e95b21fc6afb
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/iostreams/test/write_output_seq_test.hpp
8d0f0ac9c98ab690ac51a25d23b0c7f89f8d21e9
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
2,711
hpp
// (C) Copyright Jonathan Turkanis 2004 // 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.) // See http://www.boost.org/libs/iostreams for documentation. #ifndef BOOST_IOSTREAMS_TEST_WRITE_OUTPUT_SEQUENCE_HPP_INCLUDED #define BOOST_IOSTREAMS_TEST_WRITE_OUTPUT_SEQUENCE_HPP_INCLUDED #include <fstream> #include <vector> #include <boost/iostreams/filtering_stream.hpp> #include <boost/range/iterator_range.hpp> #include <boost/test/test_tools.hpp> #include "detail/sequence.hpp" #include "detail/temp_file.hpp" #include "detail/verification.hpp" void write_output_sequence_test() { using namespace std; using namespace boost; using namespace boost::iostreams; using namespace boost::iostreams::test; test_file test; { vector<char> first(data_reps * data_length(), '?'); filtering_ostream out(make_iterator_range(first), 0); write_data_in_chars(out); ifstream second(test.name().c_str()); BOOST_CHECK_MESSAGE( compare_container_and_stream(first, second), "failed writing to filtering_ostream based on a sequence " "in chars with no buffer" ); } { vector<char> first(data_reps * data_length(), '?'); filtering_ostream out(make_iterator_range(first), 0); write_data_in_chunks(out); ifstream second(test.name().c_str()); BOOST_CHECK_MESSAGE( compare_container_and_stream(first, second), "failed writing to filtering_ostream based on a sequence " "in chunks with no buffer" ); } { vector<char> first(data_reps * data_length(), '?'); filtering_ostream out(make_iterator_range(first)); write_data_in_chars(out); ifstream second(test.name().c_str()); BOOST_CHECK_MESSAGE( compare_container_and_stream(first, second), "failed writing to filtering_ostream based on a sequence " "in chars with large buffer" ); } { vector<char> first(data_reps * data_length(), '?'); filtering_ostream out(make_iterator_range(first)); write_data_in_chunks(out); ifstream second(test.name().c_str()); BOOST_CHECK_MESSAGE( compare_container_and_stream(first, second), "failed writing to filtering_ostream based on a sequence " "in chunks with large buffer" ); } } #endif // #ifndef BOOST_IOSTREAMS_TEST_WRITE_OUTPUT_SEQUENCE_HPP_INCLUDED
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 77 ] ] ]
d6079ebaa5897e22db417bdc6249be63ee9f3fff
13f30850677b4b805aeddbad39cd9369d7234929
/ astrocytes --username [email protected]/CT_tutorial/stereo.cpp
1b0ca13c80963f0b47eee430f7e300d24d0706ff
[]
no_license
hksonngan/astrocytes
2548c73bbe45ea4db133e465fa8a90d29dc60f64
e14544d21a077cdbc05356b05148cc408c255e04
refs/heads/master
2021-01-10T10:04:14.265392
2011-11-09T07:42:06
2011-11-09T07:42:06
46,898,541
0
0
null
null
null
null
UTF-8
C++
false
false
1,515
cpp
#include "Shader.h" void SetAnag(ShaderProgram*ps,int s, bool left) { vec3 anag[3]; switch(s) { case 0: // no stereo anag[0].set(1,0,0); anag[1].set(0,1,0); anag[2].set(0,0,1); break; case 1: // True anaglyh if(left) { anag[0].set(0.299,0.587,0.114); anag[1].set(0,0,0); anag[2].set(0,0,0); }else { anag[0].set(0,0,0); anag[1].set(0,0,0); anag[2].set(0.299,0.587,0.114); } break; case 2: // Gray anaglyh if(left) { anag[0].set(0.299,0.587,0.114); anag[1].set(0,0,0); anag[2].set(0,0,0); }else { anag[0].set(0,0,0); anag[1].set(0.299,0.587,0.114); anag[2].set(0.299,0.587,0.114); } break; case 3: // Color anaglyh if(left) { anag[0].set(1,0,0); anag[1].set(0,0,0); anag[2].set(0,0,0); }else { anag[0].set(0,0,0); anag[1].set(0,1,0); anag[2].set(0,0,1); } break; case 4: // Half-Color anaglyh if(left) { anag[0].set(0.299,0.587,0.114); anag[1].set(0,0,0); anag[2].set(0,0,0); }else { anag[0].set(0,0,0); anag[1].set(0,1,0); anag[2].set(0,0,1); } break; case 5: // Optimized anaglyh if(left) { anag[0].set(0,0.7,0.3); anag[1].set(0,0,0); anag[2].set(0,0,0); }else { anag[0].set(0,0,0); anag[1].set(0,1,0); anag[2].set(0,0,1); } break; }; // ps->Use(); ps->SetVar("RFrom",anag[0]); ps->SetVar("GFrom",anag[1]); ps->SetVar("BFrom",anag[2]); // ps->UnUse(); }
[ [ [ 1, 86 ] ] ]
a670926ff6690620efbb51be2ad04a6db017c6e2
2c20a15d007954eea3edb9081fe4ce2faa0301dc
/trunk/libk2/source/addr.cpp
8ce6099efd694401df30022a9dc9bda8327f76b7
[ "BSD-2-Clause" ]
permissive
BackupTheBerlios/libk2-svn
fa5a34ba718ef531b6cd782ca6dbcee85961b4bc
a9c0a26043bf99349373742c181783aa2e1a2871
refs/heads/master
2016-09-06T05:33:13.985171
2005-02-06T16:59:58
2005-02-06T16:59:58
40,746,872
0
0
null
null
null
null
UTF-8
C++
false
false
11,252
cpp
/* * Copyright (c) 2003, 2004, 2005, * Kenneth Chang-Hsing Ho <[email protected]> All rights reterved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of k2, libk2, copyright owners 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 OWNERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * APARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNERS 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. */ #ifndef K2_IPV4_ADDR_H # include <k2/ipv4_addr.h> #endif #ifndef K2_IPV6_ADDR_H # include <k2/ipv6_addr.h> #endif #ifndef K2_ASSERT_H # include <k2/assert.h> #endif #if !defined(WIN32) // !kh! need to get rid of unused headers # include <sys/socket.h> # include <netinet/in.h> # include <arpa/inet.h> # include <sys/types.h> # include <sys/time.h> # include <unistd.h> # include <netdb.h> # include <fcntl.h> #else # include <winsock2.h> # include <ws2tcpip.h> typedef int socklen_t; #endif //static const k2::ipv4::interface_addr::loopback_tag k2::ipv4::interface_addr::loopback; //static const k2::ipv4::interface_addr::any_tag k2::ipv4::interface_addr::any; k2::ipv4::interface_addr::interface_addr () { std::fill(m_data, m_data + interface_addr::size, 0); } k2::ipv4::interface_addr::interface_addr (loopback_tag) { static uint8_t loopback_data[] = {127, 0, 0, 1}; std::copy(loopback_data, loopback_data + sizeof(loopback_data), m_data); } k2::ipv4::interface_addr::interface_addr (any_tag) { std::fill(m_data, m_data + interface_addr::size, 0); } k2::ipv4::interface_addr::interface_addr (const in_addr& bsd_if_addr) { const uint8_t* src = reinterpret_cast<const uint8_t*>(&bsd_if_addr.s_addr); std::copy(src, src + interface_addr::size, m_data); } k2::ipv4::interface_addr::operator const in_addr () const { in_addr ret; uint8_t* dst = reinterpret_cast<uint8_t*>(&ret.s_addr); std::copy(m_data, m_data + interface_addr::size, dst); return ret; } k2::ipv4::interface_addr::interface_addr (const uint8_t* data) { std::copy( data, data + interface_addr::size, m_data); } const k2::uint8_t* k2::ipv4::interface_addr::data () const { return m_data; } k2::uint32_t k2::ipv4::interface_addr::hash () const { return *reinterpret_cast<const uint32_t*>(m_data); } int k2::ipv4::interface_addr::compare (const interface_addr& rhs) const { return std::lexicographical_compare( m_data, m_data + interface_addr::size, rhs.data(), rhs.data() + interface_addr::size); } k2::ipv4::transport_addr::transport_addr () : m_if_addr() , m_port(0) { } k2::ipv4::transport_addr::transport_addr (const interface_addr& if_addr, host16_t port) : m_if_addr(if_addr) , m_port(port) { } k2::ipv4::transport_addr::transport_addr (const sockaddr_in& bsd_tp_addr) : m_if_addr(bsd_tp_addr.sin_addr), m_port(net_conv(bsd_tp_addr.sin_port)) { } k2::ipv4::transport_addr::operator const sockaddr_in () const { sockaddr_in ret; ret.sin_family = AF_INET; ret.sin_addr = in_addr(m_if_addr); ret.sin_port = net_conv(m_port); return ret; } const k2::ipv4::interface_addr& k2::ipv4::transport_addr::if_addr () const { return m_if_addr; } k2::host16_t k2::ipv4::transport_addr::port () const { return m_port; } k2::ipv4::interface_addr& k2::ipv4::transport_addr::if_addr () { return m_if_addr; } k2::host16_t& k2::ipv4::transport_addr::port () { return m_port; } k2::uint32_t k2::ipv4::transport_addr::hash () const { uint8_t hash_buf[interface_addr::size]; std::copy( m_if_addr.data(), m_if_addr.data() + interface_addr::size, hash_buf); hash_buf[0] ^= uint8_t(m_port >> 8); hash_buf[interface_addr::size - 1] ^= uint8_t((m_port << 8) >> 8); return *reinterpret_cast<const uint32_t*>(hash_buf); } int k2::ipv4::transport_addr::compare (const transport_addr& rhs) const { if(m_if_addr.compare(rhs.if_addr()) > 0) return 1; if(m_if_addr.compare(rhs.if_addr()) < 0) return -1; if(m_port > rhs.port()) return 1; if(m_port < rhs.port()) return -1; return 0; } std::vector<k2::ipv4::transport_addr> k2::ipv4::nonpublic::getaddrinfo_impl ( k2::type_tag<k2::ipv4::transport_addr>, bool is_udp, bool is_passive, bool is_numeric_host, const char* host, const char* port_num) { ::addrinfo hint; hint.ai_flags = 0; hint.ai_flags |= (is_passive ? AI_PASSIVE : 0); hint.ai_flags |= (is_numeric_host ? AI_NUMERICHOST : 0); hint.ai_family = PF_INET; hint.ai_socktype = (is_udp ? SOCK_DGRAM : SOCK_STREAM); ::addrinfo* results; int ret = ::getaddrinfo( host, port_num, &hint, &results); try { if(ret != 0) { const char* err = 0; switch(ret) { case EAI_NONAME: case EAI_SERVICE: break; default: err = ::gai_strerror(ret); } if(err) throw k2::runtime_error(err); } std::vector<k2::ipv4::transport_addr> addrs; if(ret == 0) { addrs.reserve(8); for(;results != 0; results = results->ai_next); { assert(results->ai_family == hint.ai_family); assert(results->ai_family == hint.ai_socktype); addrs.push_back(transport_addr(*reinterpret_cast<const sockaddr_in*>(results->ai_addr))); } } return addrs; } catch(std::exception&) { ::freeaddrinfo(results); throw; } ::freeaddrinfo(results); } k2::ipv6::interface_addr::interface_addr () { std::fill(m_data, m_data + interface_addr::size, 0); } k2::ipv6::interface_addr::interface_addr (const in6_addr& bsd_if_addr) { const uint8_t* src = #ifdef H2_HAS_POSIX_API // BSD Socket reinterpret_cast<const uint8_t*>(bsd_if_addr.s6_addr); #else // WinSocket reinterpret_cast<const uint8_t*>(bsd_if_addr.u.Byte); #endif std::copy(src, src + interface_addr::size, m_data); } k2::ipv6::interface_addr::operator const in6_addr () const { in6_addr ret; uint8_t* dst = #ifdef H2_HAS_POSIX_API // BSD Socket reinterpret_cast<uint8_t*>(ret.s6_addr); #else // WinSocket reinterpret_cast<uint8_t*>(ret.u.Byte); #endif std::copy(m_data, m_data + interface_addr::size, dst); return ret; } k2::ipv6::interface_addr::interface_addr (const uint8_t* data) { std::copy(data, data + interface_addr::size, m_data); } const k2::uint8_t* k2::ipv6::interface_addr::data () const { return m_data; } k2::uint32_t k2::ipv6::interface_addr::hash () const { const uint32_t* p = reinterpret_cast<const uint32_t*>(m_data); return (p[0] ^ p[1]) + (p[2] ^ p[3]); } int k2::ipv6::interface_addr::compare (const interface_addr& rhs) const { return std::lexicographical_compare( m_data, m_data + interface_addr::size, rhs.data(), rhs.data() + interface_addr::size); } k2::ipv6::transport_addr::transport_addr () : m_port(0) , m_flowinfo(0) , m_scope_id(0) { } k2::ipv6::transport_addr::transport_addr ( const interface_addr& if_addr, host16_t port, host32_t flowinfo, host32_t scope_id) : m_if_addr(if_addr) , m_port(port) , m_flowinfo(flowinfo) , m_scope_id(scope_id) { } k2::ipv6::transport_addr::transport_addr (const sockaddr_in6& bsd_tp_addr) : m_if_addr(bsd_tp_addr.sin6_addr) , m_port(net_conv(bsd_tp_addr.sin6_port)) , m_flowinfo(net_conv(bsd_tp_addr.sin6_flowinfo)) , m_scope_id(net_conv(bsd_tp_addr.sin6_scope_id)) { } k2::ipv6::transport_addr::operator const sockaddr_in6 () const { sockaddr_in6 ret; ret.sin6_family = AF_INET6; ret.sin6_addr = m_if_addr; ret.sin6_port = net_conv(m_port); ret.sin6_flowinfo = net_conv(m_flowinfo & 0x000fffff); ret.sin6_scope_id = net_conv(m_scope_id); return ret; } const k2::ipv6::interface_addr& k2::ipv6::transport_addr::if_addr () const { return m_if_addr; } k2::host16_t k2::ipv6::transport_addr::port () const { return m_port; } k2::host32_t k2::ipv6::transport_addr::flowinfo () const { return m_flowinfo & 0x000fffff; } k2::host32_t k2::ipv6::transport_addr::scope_id () const { return m_scope_id; } k2::ipv6::interface_addr& k2::ipv6::transport_addr::if_addr () { return m_if_addr; } k2::host16_t& k2::ipv6::transport_addr::port () { return m_port; } k2::host32_t& k2::ipv6::transport_addr::flowinfo () { return (m_flowinfo &= 0x000fffff); } k2::host32_t& k2::ipv6::transport_addr::scope_id () { return m_scope_id; } k2::uint32_t k2::ipv6::transport_addr::hash () const { return m_if_addr.hash() ^ (((m_flowinfo & 0x000fffff) << 6) ^ m_scope_id); } int k2::ipv6::transport_addr::compare (const transport_addr& rhs) const { if(m_if_addr.compare(rhs.if_addr()) > 0) return 1; if(m_if_addr.compare(rhs.if_addr()) < 0) return -1; if(m_port > rhs.port()) return 1; if(m_port < rhs.port()) return -1; if((m_flowinfo & 0x000fffff) > rhs.flowinfo()) return 1; if(m_flowinfo < rhs.flowinfo()) return -1; if(m_scope_id > rhs.scope_id()) return 1; if(m_scope_id < rhs.scope_id()) return -1; return 0; }
[ "kenho@7c6f2ee2-65e6-0310-8e79-8af021538eec" ]
[ [ [ 1, 413 ] ] ]
7b41000bba1802b9da1d363d4f6afe287c9ef8da
24d5129750a11b8e94d1d6a8d8a45cf5492f40e0
/open-ldb/LuaDebugger.h
d3c972edb3fed2a216bdf642796977c043981cce
[]
no_license
zhuhongbozhuhongbo/lua-eclipse-ide
0f39374e487c55f02b0f4a807364d1faa8c3c66e
29d3ac023ee0e02edbdc2c9907073bc64ab62e97
refs/heads/master
2021-12-03T04:00:19.389112
2008-11-27T00:00:40
2008-11-27T00:00:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,069
h
/********************************************************** Copyright (c) 2007 VeriSign, Inc. All rights reserved. This software is provided solely in connection with the terms of the license agreement. Any other use without the prior express written permission of VeriSign is completely prohibited. The software and documentation are "Commercial Items", as that term is defined in 48 C.F.R. Section 2.101, consisting of "Commercial Computer Software" and "Commercial Computer Software Documentation" as such terms are defined in 48 C.F.R. Section 252.227-7014(a)(5) and 48 C.F.R. Section 252.227-7014(a)(1), and used in 48 C.F.R. Section 12.212 and 48 C.F.R. Section 227.7202, as applicable. Pursuant to the above and other relevant sections of the Code of Federal Regulations, as applicable, VeriSign's publications, commercial computer software, and commercial computer software documentation are distributed and licensed to United States Government end users with only those rights as granted to all other end users, according to the terms and conditions contained in the license agreement(s) that accompany the products and software documentation. ***********************************************************/ #if !defined LUA_DEBUGGER_H #define LUA_DEBUGGER_H #ifdef WORKING_ON_PC #ifdef __cplusplus extern "C" { #endif #include "lua.h" #include "lualib.h" #include "lauxlib.h" #ifdef __cplusplus } #endif #include <stdlib.h> #include <string.h> #include <iostream> using std::cerr; using std::cout; using std::endl; #include <fstream> using std::ifstream; #include <vector> #include <map> #include <string> #include <sstream> #include "ServerSocket.h" #include "SocketException.h" using namespace std; extern void HookRoutine(lua_State *L, lua_Debug *ar); #else #ifdef __cplusplus extern "C" { #endif #include "../lua/src/lua.h" #include "../lua/src/lualib.h" #include "../lua/src/lauxlib.h" #ifdef __cplusplus } #endif #include <stdlib.h> #include <string.h> #include <iostream> using std::cerr; using std::cout; using std::endl; #include <fstream> using std::ifstream; #include <vector> #include <map> #include <string> using namespace std; extern void HookRoutine(lua_State *L, lua_Debug *ar); #endif /* * ldb - a cmdline debugger with input/output via stdin/stdout * ide - an eclipse plugin with input/output over sockets */ enum debuggerType {ldb, ide}; class LuaDebugger { public: LuaDebugger(); ~LuaDebugger() { } static void readSourcefromStringBuffer(const char* source, const char* name); static char* readFileIntoString(const char *pFileName); static string getFileLine(const char *pFileName, int index); static void commandParser(lua_State *L, lua_Debug *ar); static void setBreakPointList(const char* scriptName, int lineNumber); static void listLocalVariables (lua_State *L, int level); static void listLocalVariable (lua_State *L, int level, const char* localVarName); static void listGlobalVariables(lua_State *L); static void listGlobalVariable(lua_State *L, const char* globalVarName); static void drawStackTrace(lua_State *L); static void stackDump (lua_State *L); static void printBreakpoints(const char * scriptName, vector<int> bp); static char* printIt(lua_State *L, int index, char *value); static void readFile(const char *pFileName); static int errormessage(lua_State *L); static void setLineSourceList(const char* scriptName, char* text); static int OutputTop(lua_State* L); static void ideStackTrace(lua_State *L, char* str); static void getLocalVarValue(lua_State *L, int nLevel, char* var, char *val); static void stackDumpForIde (lua_State *L, char *results); static void getGlobals(lua_State *L, char *val); private: void whereAmI(lua_State* L, lua_Debug* ar); int listvars (lua_State *L, int level); }; #if !defined WORKING_ON_PC #endif #endif // #if !defined LUA_DEBUGGER_H
[ [ [ 1, 133 ] ] ]
2ae30de5e020d7604bb1949cb06915a9313770b1
d1dc408f6b65c4e5209041b62cd32fb5083fe140
/src/gameobjects/structures/cStarPort.h
ff00d02006631e52b713f445e2b307d481bd2f68
[]
no_license
dmitrygerasimuk/dune2themaker-fossfriendly
7b4bed2dfb2b42590e4b72bd34bb0f37f6c81e37
89a6920b216f3964241eeab7cf1a631e1e63f110
refs/heads/master
2020-03-12T03:23:40.821001
2011-02-19T12:01:30
2011-02-19T12:01:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
609
h
// Structure class class cStarPort : public cAbstractStructure { private: void think_deployment(); bool frigateDroppedPackage; // TIMERs int TIMER_deploy; public: cStarPort(); ~cStarPort(); // overloaded functions void think(); void think_animation(); void think_deploy(); // starport uses this to deploy unit void think_guard(); void draw(int iStage); int getType(); bool isFrigatePackageDropped() { return frigateDroppedPackage; } void setFrigateDroppedPackage (bool value) { frigateDroppedPackage = value; } };
[ "stefanhen83@52bf4e17-6a1c-0410-83a1-9b5866916151" ]
[ [ [ 1, 31 ] ] ]
e2c7334b9a32f9c552424a44684795966b5ca340
1e8b8f8441f9bc7847415f0a01a7d285198b0526
/BCB6_Heap/clases/HeapObject.h
224af0738967ae2c6cc4c5679c56e96fb2433540
[]
no_license
jmnavarro/BCB_LosRinconesDelAPIWin32
8d5ecde4c2b60795b0cd7f69840bae48612c1fce
e3f03ccf706caf1a99c53eae2994d051b6513c17
refs/heads/master
2020-05-18T11:43:03.637385
2011-06-30T23:24:23
2011-06-30T23:24:23
1,980,854
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,878
h
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ // // Unidad: HeapObject.h // // Propósito: // Interfaz de la clase CHeapObject, que representa un objeto que será almacenado // en un montón dedicado a los objetos de su clase. // // Las clases definidas son: // CHeapBlock: representa un bloque reservado con HeapAlloc. // CHeap: representa un montón creado con HeapCreate. Se compone de uno o // varios bloques de tipo CHeapBlock. // CHeapList: representa una lista de punteros almacenada en un montón dedicado. // CHeapBlockList: especialización de CHeapList que maneja objetos de tipo CHeapBlock // en vez de punteros genéricos. // // Autor: José Manuel Navarro (jose.man_ARROBA_iespana.es) // // Fecha: 01/11/2002 // // Observaciones: Clase creada en C++ Builder 6 para el artículo "Los montones en Win32" // publicado en http://users.servicios.retecal.es/sapivi/prog/cpp/montones.html // // Copyright: Este código es de dominio público y se puede utilizar y/o mejorar siempre // que SE HAGA REFERENCIA AL AUTOR ORIGINAL, ya sea a través de estos // comentarios o de cualquier otro modo. // //~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #ifndef HEAPOBJECT_H #define HEAPOBJECT_H #include <windows.h> #define INITIAL_SIZE 1024 * 64 class CHeapObject { private: static HANDLE s_hHeap; static UINT s_NumBlocks; public: CHeapObject(); virtual ~CHeapObject(); HANDLE static GetHeap( VOID ); void *operator new( SIZE_T size ); void operator delete( void *obj ); }; #endif // HEAPOBJECT_H
[ [ [ 1, 56 ] ] ]
8302e9686c29af3943b8f38dd57628906f92fe70
df238aa31eb8c74e2c208188109813272472beec
/Include/CDataContainer.h
44f444be802f79fc0157b0ff0fc7ce4ab0d6d00e
[]
no_license
myme5261314/plugin-system
d3166f36972c73f74768faae00ac9b6e0d58d862
be490acba46c7f0d561adc373acd840201c0570c
refs/heads/master
2020-03-29T20:00:01.155206
2011-06-27T15:23:30
2011-06-27T15:23:30
39,724,191
0
0
null
null
null
null
GB18030
C++
false
false
1,943
h
// Copyright (C) 1991 - 1999 Rational Software Corporation #if defined (_MSC_VER) && (_MSC_VER >= 1000) #pragma once #endif #ifndef _INC_CDATACONTAINER_4C5E26180115_INCLUDED #define _INC_CDATACONTAINER_4C5E26180115_INCLUDED #include "CDataElement.h" const String PLUGIN_CONTAINER_GUID = "{4D0FF8C1-1022-40ed-8F32-CE0DCF2CF050}"; //##ModelId=4C5FE0CD0072 typedef std::map<String, CDataElement*> DataChildMap; //##ModelId=4C5FE0CD0081 typedef std::map<String, CDataContainer*> DataChildContainerMap; //##ModelId=4C5E26180115 class PLUGIN_EXPORT_CLASS CDataContainer : public CDataElement { protected: //##ModelId=4C5FE0CD0092 DataChildMap m_ChildList; //##ModelId=4C5FE0CD00A1 DataChildContainerMap m_ChildContainerList; public: //##ModelId=4C5FE0CD00B0 CDataContainer(const String& Name); //##ModelId=4C5E6DF90349 virtual ~CDataContainer(); //容器的装载与卸载. //##ModelId=4C5EA79903C4 virtual bool Load(void); //##ModelId=4C5EA79A002A virtual bool UnLoad(void); //////////////////////////容器结点相关操作////////////////////////////////////////////// //是否为容器. //##ModelId=4C5FE0CD010E inline virtual bool IsContainer() const { return true; } //容器通知. //##ModelId=4C5FF2880308 virtual void _NotifyParent(CDataContainer* pParent); //添加一个孩子. //##ModelId=4C5FE0CD014C virtual bool AddChild(CDataElement *pElement); //添加一个元素. //##ModelId=4C5FE0CD01C9 virtual bool AddElement(CDataElement *pElement); //添加一个容器. //##ModelId=4C5FE0CD0246 virtual bool AddContainer(CDataContainer *pContainer); //删除一个孩子. //##ModelId=4C5FE0CD02D2 virtual void ReomveChild(const String& Name); //获取一个孩子. //##ModelId=4C5FE0CD033F virtual CDataElement *GetChild(const String& Name); }; #endif /* _INC_CDATACONTAINER_4C5E26180115_INCLUDED */
[ "myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5", "[email protected]" ]
[ [ [ 1, 12 ], [ 14, 14 ], [ 16, 17 ], [ 19, 21 ], [ 23, 23 ], [ 25, 27 ], [ 29, 29 ], [ 31, 33 ], [ 35, 35 ], [ 37, 41 ], [ 43, 45 ], [ 47, 49 ], [ 51, 53 ], [ 55, 57 ], [ 59, 61 ], [ 63, 65 ], [ 67, 72 ] ], [ [ 13, 13 ], [ 15, 15 ], [ 18, 18 ], [ 22, 22 ], [ 24, 24 ], [ 28, 28 ], [ 30, 30 ], [ 34, 34 ], [ 36, 36 ], [ 42, 42 ], [ 46, 46 ], [ 50, 50 ], [ 54, 54 ], [ 58, 58 ], [ 62, 62 ], [ 66, 66 ] ] ]
e6e5b2e981b630f1eeab40781623f00dc5ac09aa
0b039565382fe5cf8a9abe90a2999396d79ca37f
/GrpInformative/dumpGetFeatures_r10b.h
b61ce32c774ecd61817d4fe383591dd601f33935
[ "Apache-2.0" ]
permissive
cornsea/tnvme
989cf26233e05f816b7d64d4bb402124efd7d4e6
9e6100b771cd3d0ee7c497e27db391fca626d245
refs/heads/master
2021-01-16T18:14:35.269183
2011-12-23T20:56:25
2011-12-23T20:56:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,975
h
/* * Copyright (c) 2011, Intel Corporation. * * 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. */ #ifndef _DUMPGETFEATURES_r10b_H_ #define _DUMPGETFEATURES_r10b_H_ #include "test.h" #include "../Queues/asq.h" #include "../Queues/acq.h" /** \verbatim * ----------------------------------------------------------------------------- * ----------------Mandatory rules for children to follow----------------------- * ----------------------------------------------------------------------------- * 1) See notes in the header file of the Test base class * \endverbatim */ class DumpGetFeatures_r10b : public Test { public: DumpGetFeatures_r10b(int fd, string grpName, string testName); virtual ~DumpGetFeatures_r10b(); /** * IMPORTANT: Read Test::Clone() header comment. */ virtual DumpGetFeatures_r10b *Clone() const { return new DumpGetFeatures_r10b(*this); } DumpGetFeatures_r10b &operator=(const DumpGetFeatures_r10b &other); DumpGetFeatures_r10b(const DumpGetFeatures_r10b &other); protected: virtual bool RunCoreTest(); private: /////////////////////////////////////////////////////////////////////////// // Adding a member variable? Then edit the copy constructor and operator(). /////////////////////////////////////////////////////////////////////////// void SendGetFeaturesNumOfQueues(SharedASQPtr asq, SharedACQPtr acq); }; #endif
[ [ [ 1, 16 ] ], [ [ 17, 59 ] ] ]
20bfc9afe7112cdbdfa5479af3f7b0e32465d08d
a22826defa63e9c1487cfea12a295b1427befe9c
/software/neek/LCDTouchscreen.cpp
e5b735e46682fb752008fd98d8e5a0880104355f
[]
no_license
cadenass/neek-klondike
5107726c3edc8957ae8ec8b06d08ef0f2f4ad648
29a0a0b65e689db7517cc3417eaa3ed50713c6db
refs/heads/master
2021-04-12T04:50:27.476316
2010-09-17T12:56:22
2010-09-17T12:56:22
33,462,152
0
0
null
null
null
null
UTF-8
C++
false
false
4,445
cpp
/* * Nios II Klondike Solitaire (Altera Neek Edition) */ #include "LCDTouchscreen.hpp" #include <list> #include <algorithm> #include "Graphics.hpp" #include "Touchable.hpp" #include "Displayable.hpp" #include "HardwareMalfunction.hpp" extern "C" { /* * LCD's libraries. */ #include "altera_libs/alt_video_display.h" #include "altera_libs/alt_tpo_lcd.h" /* * Touch-screen's libraries. */ #include "altera_libs/alt_touchscreen.h" #include "includes.h" } namespace neek { enum Settings { LCD_BUFFERS_NUM = 2, LCD_COLOR_DEPTH = 32, TOUCHSCREEN_UPPER_RIGHT_ADC_X = 3946, TOUCHSCREEN_UPPER_RIGHT_ADC_Y = 3849, TOUCHSCREEN_UPPER_RIGHT_X = 799, TOUCHSCREEN_UPPER_RIGHT_Y = 0, TOUCHSCREEN_LOWER_LEFT_ADC_X = 132, TOUCHSCREEN_LOWER_LEFT_ADC_Y = 148, TOUCHSCREEN_LOWER_LEFT_X = 0, TOUCHSCREEN_LOWER_LEFT_Y = 479 }; class LCDTouchscreenImpl { public: alt_tpo_lcd lcd_; alt_video_display * video_; Graphics * graphics_; alt_touchscreen touchscreen_; std::list <Touchable *> touchscreenListeners_; std::list <Displayable *> displayListeners_; }; void onTouch (int, int x, int y, void * context) { LCDTouchscreenImpl * impl = static_cast <LCDTouchscreenImpl *> (context); typedef std::list <Touchable *>::iterator ListenersIter; for (ListenersIter iter = impl->touchscreenListeners_.begin (); iter != impl->touchscreenListeners_.end (); ++iter) { (*iter)->touched (x, y); } } LCDTouchscreen * LCDTouchscreen::instance_ = 0; LCDTouchscreen * LCDTouchscreen::getInstance () { if (instance_ == 0) { instance_ = new LCDTouchscreen (); } return instance_; } LCDTouchscreen::LCDTouchscreen () : impl_ (new LCDTouchscreenImpl ()) { /* * LCD's initialization. */ impl_->lcd_.scen_pio = LCD_I2C_EN_BASE; impl_->lcd_.scl_pio = LCD_I2C_SCL_BASE; impl_->lcd_.sda_pio = LCD_I2C_SDAT_BASE; if(alt_tpo_lcd_init(&impl_->lcd_, LCD_WIDTH, LCD_HEIGHT) != 0) { throw HardwareMalfunction ("LCD initialization failed."); } impl_->video_ = alt_video_display_init ( "/dev/lcd_sgdma", LCD_WIDTH, LCD_HEIGHT, LCD_COLOR_DEPTH, ALT_VIDEO_DISPLAY_USE_HEAP, ALT_VIDEO_DISPLAY_USE_HEAP, LCD_BUFFERS_NUM); if (impl_->video_ == 0) { throw HardwareMalfunction ("Video initialization failed."); } impl_->graphics_ = new Graphics (impl_->video_); /* * Touch-screen's initialization. */ if (alt_touchscreen_init (&impl_->touchscreen_, TOUCH_PANEL_SPI_BASE, TOUCH_PANEL_SPI_IRQ, TOUCH_PANEL_PEN_IRQ_BASE, TOUCHSCREEN_SAMPLE_RATE, ALT_TOUCHSCREEN_SWAP_XY)) { throw HardwareMalfunction ("Touch-screen initialization failed."); } if (alt_touchscreen_register_callback_func (&impl_->touchscreen_, ALT_TOUCHSCREEN_CALLBACK_ON_PEN_DOWN, onTouch, impl_) != 0) { throw HardwareMalfunction ("Touch-screen initialization failed."); } alt_touchscreen_calibrate_upper_right (&impl_->touchscreen_, TOUCHSCREEN_UPPER_RIGHT_ADC_X, TOUCHSCREEN_UPPER_RIGHT_ADC_Y, TOUCHSCREEN_UPPER_RIGHT_X, TOUCHSCREEN_UPPER_RIGHT_Y); alt_touchscreen_calibrate_lower_left (&impl_->touchscreen_, TOUCHSCREEN_LOWER_LEFT_ADC_X, TOUCHSCREEN_LOWER_LEFT_ADC_Y, TOUCHSCREEN_LOWER_LEFT_X, TOUCHSCREEN_LOWER_LEFT_Y); } LCDTouchscreen::~LCDTouchscreen () { alt_video_display_close (impl_->video_, ALT_VIDEO_DISPLAY_USE_HEAP, ALT_VIDEO_DISPLAY_USE_HEAP); impl_->video_ = 0; } void LCDTouchscreen::addTouchable (Touchable * listener) { if (std::find (impl_->touchscreenListeners_.begin (), impl_->touchscreenListeners_.end (), listener) == impl_->touchscreenListeners_.end ()) { impl_->touchscreenListeners_.push_back (listener); } } void LCDTouchscreen::addDisplayable (Displayable * listener) { if (std::find (impl_->displayListeners_.begin (), impl_->displayListeners_.end (), listener) == impl_->displayListeners_.end ()) { impl_->displayListeners_.push_back (listener); } } void LCDTouchscreen::updateTouchscreen () { alt_touchscreen_event_loop_update (&impl_->touchscreen_); } void LCDTouchscreen::updateLCD () { typedef std::list <Displayable *>::iterator ListenersIter; for (ListenersIter iter = impl_->displayListeners_.begin (); iter != impl_->displayListeners_.end (); ++iter) { (*iter)->draw (impl_->graphics_, LCD_WIDTH, LCD_HEIGHT); } alt_video_display_register_written_buffer (impl_->video_); } }
[ "[email protected]@7300451d-d64f-7b9e-e916-f946393f26c1" ]
[ [ [ 1, 154 ] ] ]
ed5350322106b1270fc20d53e8c176e165346839
97f1be9ac088e1c9d3fd73d76c63fc2c4e28749a
/3dc/avp/win95/gadgets/textexp.hpp
81191e37152ce342438f4cc374f0c9d25a885384
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
SR-dude/AvP-Wine
2875f7fd6b7914d03d7f58e8f0ec4793f971ad23
41a9c69a45aacc2c345570ba0e37ec3dc89f4efa
refs/heads/master
2021-01-23T02:54:33.593334
2011-09-17T11:10:07
2011-09-17T11:10:07
2,375,686
1
0
null
null
null
null
UTF-8
C++
false
false
2,248
hpp
/* textexp.hpp Text Expansions for typing */ #ifndef _textexp #define _textexp 1 #ifndef _scstring #include "scstring.hpp" #endif #ifdef __cplusplus extern "C" { #endif /* Version settings *****************************************************/ /* Constants ***********************************************************/ /* Macros ***************************************************************/ /* Type definitions *****************************************************/ // When typing, whenever space is pressed, the program searches // the last word typed to see if it matches one of the expansions // If it does, then the word is replaced by the expanded version // E.g. "SG" could be defined to expand to "SENTRYGUN" class TextInputState; // fully declared in TEXTIN.HPP class TextExpansion { public: ~TextExpansion(); void Display(void); // sends info on this expansion to the screen static void AddExpansion ( ProjChar* pProjCh_ToParse ); static void TryToRemoveExpansion ( ProjChar* pProjCh_ToParse ); static void TestForExpansions ( TextInputState* pTextInputState_In ); // Called by the typing code whenever a word is completed // This function is a friend to the class TextInputState static void ListAll(void); static int bVerbose; // public global so it can be accessed via a console variable private: TextExpansion ( SCString* pSCString_Short, SCString* pSCString_Expansion ); static void TryToRemoveExpansion ( SCString* pSCString_Word ); // assumed the word is already parsed/doesn't contain whitespace SCString* pSCString_Short_Val; SCString* pSCString_Expansion_Val; SCString* pSCString_Description_Val; // a string of the form: "<shortform>" -> "<longform>" static List<TextExpansion*> List_pTextExp; }; // suggested naming: TextExp /* Exported globals *****************************************************/ /* Function prototypes **************************************************/ /* End of the header ****************************************************/ #ifdef __cplusplus }; #endif #endif
[ "a_jagers@ANTHONYJ.(none)" ]
[ [ [ 1, 103 ] ] ]
3adaf130d14e3ee7883b5689e81dfc8ca6e4865d
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/terralib/src/DSDK/include/base/lti_rawImageReader.h
b6a95b75cac4aa4aa7684c2244ccc28e0b5cb1d6
[]
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
10,033
h
/* $Id: lti_rawImageReader.h 5124 2006-10-27 11:40:40Z lubia $ */ /* ////////////////////////////////////////////////////////////////////////// // // // This code is Copyright (c) 2004 LizardTech, Inc, 1008 Western Avenue, // // Suite 200, Seattle, WA 98104. Unauthorized use or distribution // // prohibited. Access to and use of this code is permitted only under // // license from LizardTech, Inc. Portions of the code are protected by // // US and foreign patents and other filings. All Rights Reserved. // // // ////////////////////////////////////////////////////////////////////////// */ /* PUBLIC */ #ifndef LTIRAWIMAGEREADER_H #define LTIRAWIMAGEREADER_H // lt_lib_mrsid_core #include "lti_geoImageReader.h" LT_BEGIN_NAMESPACE(LizardTech) #if defined(LT_COMPILER_MS) #pragma warning(push,4) #endif class LTIPixel; class LTIOStreamInf; class LTFileSpec; class LTIGeoCoord; class LTIPixel; /** * class for reading RAW files * * This class reads a RAW image. * * The RAW format used is simple packed BIP form. */ class LTIRawImageReader : public LTIGeoImageReader { public: /** * constructor (stream) * * This function constructs an LTIImageReader using the data in the * stream with the image properties specified. The input taken from a * stream. * * @param stream stream containing the RAW image data (may not be NULL) * @param pixelProps the pixel properties of the image (colorspace, datatype, etc) * @param width the width of the image * @param height the height of the image * @param useWorldFile use world file information if available */ LTIRawImageReader(LTIOStreamInf* stream, const LTIPixel& pixelProps, lt_uint32 width, lt_uint32 height, bool useWorldFile = true); /** * constructor (FileSpec) * * This function constructs an LTIImageReader using the data in the * stream with the image properties specified. The input taken from a * stream, and the background and nodata pixels may be specified. * * @param fileSpec file containing the RAW image data * @param pixelProps the pixel properties of the image (colorspace, datatype, etc) * @param width the width of the image * @param height the height of the image * @param useWorldFile use world file information if available */ LTIRawImageReader(const LTFileSpec& fileSpec, const LTIPixel& pixelProps, lt_uint32 width, lt_uint32 height, bool useWorldFile = true); /** * constructor (char*) * * This function constructs an LTIImageReader using the data in the * stream with the image properties specified. The input taken from a * stream, and the background and nodata pixels may be specified. * * @param file file containing the RAW image data (may not be NULL) * @param pixelProps the pixel properties of the image (colorspace, datatype, etc) * @param width the width of the image * @param height the height of the image * @param useWorldFile use world file information if available */ LTIRawImageReader(const char* file, const LTIPixel& pixelProps, lt_uint32 width, lt_uint32 height, bool useWorldFile = true); /** * destructor */ virtual ~LTIRawImageReader(); /** * initializer */ virtual LT_STATUS initialize(); /** * @name Properties of the RAW image * * These must be called prior to calling initialize(), unlike most other SDK * objects. */ /*@{*/ /** * set geo coordinates * * Sets the geographic coordinates for the image. If not set, the default * is the normal default of (0,h-1) with resolutions (1.0,-1.0). * * @note This must be called prior to calling initialize(). * * @param geo the geo coordinates for the image */ void setGeoCoordinate(const LTIGeoCoord& geo); /** * set stream ownership * * Sets the ownership of the stream, to indicate responsibility for * deleting the stream when done. This only pertains to objects which were * passed a stream in the ctor. * * If not set, the default is for the object to not take ownership of the * stream. * * @note This must be called prior to calling initialize(). * * @param takeOwnership set to true to have the reader delete the stream */ void setStreamOwnership(bool takeOwnership); /** * add classical metadata * * Directs the reader to populate the standard "classical" metadata tags. * * If not set, the default is to not add the metadata tags. * * @note This must be called prior to calling initialize(). * * @param withMetadata set to true to have the reader add metadata */ void setMetadata(bool withMetadata); /** * set background color * * Sets the background pixel of the image. * * If not set, the default is to leave the background pixel unset. * * @note This must be called prior to calling initialize(). * * @param background the new background color of the image */ void setBackground(const LTIPixel* background); /** * set nodata color * * Sets the NoData pixel of the image. * * If not set, the default is to leave the NoData pixel unset. * * @note This must be called prior to calling initialize(). * * @param nodata the new nodata color of the image */ void setNoData(const LTIPixel* nodata); /** * sets the number of bytes in each row * * Sets the number of bytes in each row. This allows for alignment * padding, required by certain RAW formats. * * If not set, the bytes per row is simply the number of data items per * row times the size of a data item. (Note that a "data item" in this * case may be either a pixel or a sample, depending on the layout being * used.) * * @note This must be called prior to calling initialize(). * * @param rowBytes the number of bytes per row */ void setRowBytes(lt_uint32 rowBytes); /** * sets the layout or organization of the raw data * * Sets the layout or organization of the raw data. * * If not set, the default is BIP format. * * @note This must be called prior to calling initialize(). * * @param layout the layout of the raw data */ void setLayout(LTILayout layout); /** * sets the number of bytes to skip at the beginning of the file * * Sets the number of bytes to skip at the beginning of the file. If not * set, the default is zero (no leading bytes are skipped). * * No skip bytes are assumed to be at the end of the file, and this * function only takes a 32-bit skip length; see the second version * of setSkipBytes() for an alternative. * * @note This must be called prior to calling initialize(). * * @param skipBytes the number of bytes to skip */ void setSkipBytes(lt_uint32 skipBytes); /** * sets the number of bytes to skip at the beginning and end of the file * * Sets the number of bytes to skip at the beginning of the file and * the end of the file. (The "ending skip bytes" property is sometimes * required because LTIRawImageReader::initialize() does a sanity check * to make sure the number of data bytes in the file is equal to the * number of bytes needed for the given width, height, etc. * * @note This must be called prior to calling initialize(). * * @param leadingBytes the number of bytes to skip at the top * @param trailingBytes the number of bytes to skip at the bottom */ void setSkipBytes(lt_int64 leadingBytes, lt_int64 trailingBytes); /** * sets endianness of output file * * Sets the byte order or endianness of the output file. * * @note This must be called prior to calling initialize(). * * @param byteOrder the endian setting to use */ void setByteOrder(LTIEndian byteOrder); /*@}*/ virtual LTIImageReader* duplicate(); virtual lt_int64 getPhysicalFileSize() const; protected: LTIRawImageReader(const LTFileSpec& fileSpec, bool useWorldFile = true); void setCtorPixelProps(const LTIPixel& pixelProps); void setCtorDimensions(lt_uint32 width, lt_uint32 height); virtual LT_STATUS decodeStrip(LTISceneBuffer& stripBuffer, const LTIScene& stripScene); virtual LT_STATUS decodeBegin(const LTIScene& scene); virtual LT_STATUS decodeEnd(); LTFileSpec* m_fileSpec; private: LTIOStreamInf* m_stream; bool m_ownsStream; LTIPixel* m_pixel; lt_uint32 m_width; lt_uint32 m_height; LTIGeoCoord* m_geoCoordArg; lt_int64 m_fileSize; bool m_withMetadata; lt_uint32 m_rowBytes; LTILayout m_layout; lt_int64 m_leadingSkipBytes; lt_int64 m_trailingSkipBytes; LTIEndian m_byteOrder; lt_uint8* m_rowBuffer; const LTIPixel* m_backgroundPixel; const LTIPixel* m_nodataPixel; // nope LTIRawImageReader(LTIRawImageReader&); LTIRawImageReader& operator=(const LTIRawImageReader&); }; LT_END_NAMESPACE(LizardTech) #if defined(LT_COMPILER_MS) #pragma warning(pop) #endif #endif // LTIRAWIMAGEREADER_H
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 308 ] ] ]
72fee4e2af330711d04d8d7a15e8b5c8ecf10996
c60f02a60d94fb5ca4d8a185e055df4addca519c
/src/Distance.cpp
50b14d78ee345b1d6c72c94a42e6429ca59e7965
[]
no_license
kbeyerlein/kDFA
9b4f48afba43bd2fc730b8d5889b23c247051ff2
c075b85629ff53dfe1e2f51f61c656fe7d032429
refs/heads/master
2020-03-29T12:29:01.244581
2011-08-22T23:28:14
2011-08-22T23:28:14
2,067,600
0
1
null
null
null
null
UTF-8
C++
false
false
16,936
cpp
#include "Distance.h" Distance::Distance(char *_fileName) { fileName=_fileName; shell=0; f=0; kappa=0; nDist=0; dist=0; mult=0; nextDist=0; } Distance::Distance() { fileName=""; shell=0; f=0; kappa=0; nDist=0; dist=0; mult=0; nextDist=0; } Distance::~Distance(void) { delete [] dist; delete [] mult; } void Distance::ReadDistFile() { string tempstring1; int counter=1; ifstream infile; infile.open(fileName.c_str()); if (infile.is_open()){ //printf("file %s opened\n", fileName.c_str()); while ((!infile.eof())) { infile >> tempstring1; if (tempstring1=="SHAPE") infile >> tempstring1>>tempstring1>>shell; //Input surface relax parameters else if (tempstring1=="SURFACE"){ infile >>tempstring1>>f>>kappa; } //Input number of distances in file else if (tempstring1=="NUMBER"){ infile >> tempstring1>>tempstring1>>nDist; //allocate mem for distances and mult try{ dist=new double [nDist]; mult=new double [nDist]; } catch (exception& e){ printf("\nException found in ReadDistFile alloc: %s\n", e.what()); exit(-1); } } //Input distances and multiplicites else if (tempstring1=="DISTANCES"){ for (int i=0; i<nDist; i++){ infile >>dist[i]>>mult[i]; } } else { //If there is an error with reading the data from the file an error message will be displayed and // the loop index that the error occured on. /* if (counter <5){ printf("Error in reading file: %s\n", fileName.c_str()); printf("Error with data input: cycle %s\n",tempstring1.c_str()); infile.close(); err= -1; } */ if (counter <5){ cout<<"Error in reading file: "<<fileName<<endl; cout<<"Unrecognized keyword: " <<tempstring1<<endl; infile.close(); exit (1); } } counter++; } infile.close(); } else { printf("Could not open file: %s \n", fileName.c_str()); exit(1); } } int Distance::CalcDistances(int _shell, Position *firstPos) { int i, j, k, nTot=0, n1, n2, nD, place; Position *curPos=firstPos; float *x1, *y1, *z1, *x2, *y2, *z2; double *d, *m, *tempd, *tempm; //Calc max number of possible dist shell=_shell; for (i=1;i<shell;i++){ nTot+=curPos->nAtoms; curPos=curPos->nextPos; } x1=curPos->x; y1=curPos->y; z1=curPos->z; n1=curPos->nAtoms; nD=(n1*(n1-1)/2)+n1*nTot+1; try { d=new double [nD]; m=new double [nD]; } catch (exception& e){ printf("\nException found in CalcDistances alloc: %s\n", e.what()); return -1; } //Calc distances within shell x2=curPos->x; y2=curPos->y; z2=curPos->z; d[0]=0; m[0]=double(n1); place=1; for (i=0;i<n1;i++){ for (j=i+1;j<n1;j++){ d[place]=(x1[i]-x2[j])*(x1[i]-x2[j])+(y1[i]-y2[j])*(y1[i]-y2[j])+(z1[i]-z2[j])*(z1[i]-z2[j]); m[place]=2; place++; } } //Calc distances btw shell and smaller shells curPos=firstPos; for (k=1;k<shell;k++){ n2=curPos->nAtoms; x2=curPos->x; y2=curPos->y; z2=curPos->z; for (i=0;i<n1;i++){ for (j=0;j<n2;j++){ d[place]=(x1[i]-x2[j])*(x1[i]-x2[j])+(y1[i]-y2[j])*(y1[i]-y2[j])+(z1[i]-z2[j])*(z1[i]-z2[j]); m[place]=2; place++; } } curPos=curPos->nextPos; } //compress distances QuickSortImproved(d,m,0,nD-1); nDist=MultiplicitiesCompute(d,m,nD); try{ tempd=new double [nDist]; tempm=new double [nDist]; for (i=0;i<nDist;i++){ tempd[i]=d[i]; tempm[i]=m[i]; } delete [] d; delete [] m; dist=new double [nDist]; mult=new double [nDist]; } catch (exception& e){ printf("\nException found in CalcDistances alloc: %s\n", e.what()); return -1; } //Set the for (i=0;i<nDist;i++){ dist[i]=sqrt(tempd[i]); mult[i]=tempm[i]; } delete [] tempd; delete [] tempm; return 0; } void Distance:: QuickSortImproved(double *x, double *y, int lb, int ub) { while (lb < ub) { int m; /* quickly sort short lists */ if (ub - lb <= 50) { this->sortByInsertion(x, y, lb, ub); return; } m = partition(x, y, lb, ub); /* eliminate tail recursion and */ /* sort the smallest partition first */ /* to minimize stack requirements */ if (m - lb <= ub - m) { QuickSortImproved(x, y,lb, m); lb = m + 1; } else { QuickSortImproved(x, y,m + 1, ub); ub = m; } } } void Distance :: sortByInsertion(double *x, double *y, int lb, int ub) { int i, j; for (i = lb + 1; i <= ub; i++) { double t = x[i]; double u = y[i]; /* shift down until insertion point found */ for (j = i-1; j >= lb && (x[j]> t); j--){ x[j+1] = x[j]; y[j+1] = y[j]; } /* insert */ x[j+1] = t; y[j+1] = u; } } int Distance :: partition(double *x, double *y, int lb, int ub) { /* select a pivot */ double pivot = x[(lb+ub)/2]; /* work from both ends, swapping to keep */ /* values less than pivot to the left, and */ /* values greater than pivot to the right */ int i = lb - 1; int j = ub + 1; while (1) { double t; double u; while ((x[--j]> pivot)); while ((x[++i]< pivot)); if (i >= j) break; /* swap x[i], x[j] */ t = x[i]; u = y[i]; x[i] = x[j]; y[i]=y[j]; x[j] = t; y[j]=u; } return j; } int Distance::MultiplicitiesCompute(double *d, double *m, int nD) { int i,j=0; double prevVal, currVal=0; prevVal=d[0]; for (i=1; i<nD;i++){ currVal=d[i]; if (currVal<=(prevVal+PREC)) { m[j]+=m[i]; } else { j++; d[j]=currVal; m[j]=m[i]; prevVal=currVal; } } return (j+1); } void Distance::OutputDistToFile(string path, string shape) { string _file = path + fileName; fstream file(_file.c_str(), ios_base::out|ios_base::trunc); if (file.is_open()){ file.setf(ios::fixed, ios::floatfield); file << "SHAPE SHELL\n"; file << shape<<" "<<shell<<"\n"; file << "SURFACE RELAXATION\n"; file<<f<<" "<<kappa<<"\n"; file <<"NUMBER OF DISTANCES\n"; file<<nDist<<"\n"; file<< "DISTANCES" <<"\n"; file.precision(5); for (int i=0;i<nDist;i++){ file << dist[i] << " "; file << mult[i]<< "\n"; } file.close(); } else { printf("Error writing file... check path."); exit (1); } } void Distance::DebbyCalcSums(float* pArray1x, float* pArray1y, float* pArray1z, int p1Size, float* pArray2x, float* pArray2y, float* pArray2z, int p2Size, double* pResult, // [out] result array double stepd, // [in] step size in d int nSize, // [in] size of result array bool sameArray, // [in] if pArray1==pArray2 float startd) { #ifndef NOUSESTEP float istep=1.0f/float(stepd); __m128 pvals = _mm_load1_ps(&istep); __m128 d0= _mm_load1_ps(&startd); #endif #ifdef DBLSPD int DSPD = 2; #else int DSPD = 1; #endif int DIV = 4*DSPD; int p2optsize = p2Size/DIV; int p2optrem = p2Size%DIV; int maxBegVect = p1Size-p2optrem; int flag=0; //#pragma omp parallel for //schedule(static, 2) for(int i=0;i<p1Size;i++) { __m128* p2x = (__m128*) pArray2x; __m128* p2y = (__m128*) pArray2y; __m128* p2z = (__m128*) pArray2z; __m128 p1x = _mm_load1_ps(pArray1x++); __m128 p1y = _mm_load1_ps(pArray1y++); __m128 p1z = _mm_load1_ps(pArray1z++); int ibeg; if(sameArray){ #ifdef JUSTENOUGH int irem = i%DIV; ibeg = i/DIV; p2x+=(DSPD*ibeg); p2y+=(DSPD*ibeg); p2z+=(DSPD*ibeg); // LEFTOVERS: BEGINNING OF VECTOR (if i>0 and not %4) // The second control is to impliment an upper bound of when to use the beginnings (do not need in the bottom corner of the distance matrix) if (irem>0&&(i<maxBegVect)) { ibeg++; // get 4 deltacoords __m128 dx,dy,dz, d2; __m128i jumps; if (irem<4){ dx = _mm_sub_ps(p1x, *(p2x++)); dy = _mm_sub_ps(p1y, *(p2y++)); dz = _mm_sub_ps(p1z, *(p2z++)); // square dx = _mm_mul_ps(dx, dx); dy = _mm_mul_ps(dy, dy); dz = _mm_mul_ps(dz, dz); // sum dx+dy+dz d2 = _mm_add_ps(dx, dy); d2 = _mm_add_ps(d2, dz); //subtract the offset of the distances d2 = _mm_sub_ps(d2,d0); } else{ p2x++; p2y++; p2z++; } #ifdef DBLSPD dx = _mm_sub_ps(p1x, *(p2x++)); dy = _mm_sub_ps(p1y, *(p2y++)); dz = _mm_sub_ps(p1z, *(p2z++)); dx = _mm_mul_ps(dx, dx); dy = _mm_mul_ps(dy, dy); dz = _mm_mul_ps(dz, dz); #endif // square root #ifdef USESQRT d2 = _mm_sqrt_ps(d2); #endif // get entry points in the PDF table if (irem<4){ #ifndef NOUSESTEP d2 = _mm_mul_ps(d2,pvals); #endif jumps = _mm_cvtps_epi32(d2); } #ifdef DBLSPD __m128 d22 = _mm_add_ps(dx, dy); d22 = _mm_add_ps(d22, dz); d22 = _mm_sub_ps(d22,d0); #ifndef NOUSESTEP d22 = _mm_mul_ps(d22,pvals); #endif __m128i jumps2 = _mm_cvtps_epi32(d22); #endif // update PDF for (int i=0;i<4;i++){ if (i>=irem) pResult[_mm_cvtsi128_si32(jumps)]++; jumps=_mm_srli_si128(jumps,4); } #ifdef DBLSPD for (int i=0;i<4;i++){ if (i>=(irem-4)) pResult[_mm_cvtsi128_si32(jumps2)]++; jumps2=_mm_srli_si128(jumps2,4); } #endif } #endif } else ibeg=0; // MAIN CORE: 4-tuples //#pragma omp parallel for schedule(static, 2) for(int j=ibeg;j<p2optsize;j++) { // get 4 deltacoords __m128 dx = _mm_sub_ps(p1x, *(p2x++)); __m128 dy = _mm_sub_ps(p1y, *(p2y++)); __m128 dz = _mm_sub_ps(p1z, *(p2z++)); // square dx = _mm_mul_ps(dx, dx); dy = _mm_mul_ps(dy, dy); dz = _mm_mul_ps(dz, dz); // sum dx+dy+dz __m128 d2 = _mm_add_ps(dx, dy); d2 = _mm_add_ps(d2, dz); //subtract the offset of the distances d2 = _mm_sub_ps(d2,d0); #ifdef DBLSPD dx = _mm_sub_ps(p1x, *(p2x++)); dy = _mm_sub_ps(p1y, *(p2y++)); dz = _mm_sub_ps(p1z, *(p2z++)); dx = _mm_mul_ps(dx, dx); dy = _mm_mul_ps(dy, dy); dz = _mm_mul_ps(dz, dz); #endif // square root #ifdef USESQRT d2 = _mm_sqrt_ps(d2); #endif // get entry points in the PDF table #ifndef NOUSESTEP d2 = _mm_mul_ps(d2,pvals); #endif __m128i jumps = _mm_cvtps_epi32(d2); #ifdef DBLSPD __m128 d22 = _mm_add_ps(dx, dy); d22 = _mm_add_ps(d22, dz); //subtract the offset of the distances d22 = _mm_sub_ps(d22,d0); #ifndef NOUSESTEP d22 = _mm_mul_ps(d22,pvals); #endif __m128i jumps2 = _mm_cvtps_epi32(d22); #endif // update PDF for (int i=0;i<4;i++){ // int temp=_mm_cvtsi128_si32(jumps); pResult[_mm_cvtsi128_si32(jumps)]++; jumps=_mm_srli_si128(jumps,4); } #ifdef DBLSPD for (int i=0;i<4;i++){ pResult[_mm_cvtsi128_si32(jumps2)]++; jumps2=_mm_srli_si128(jumps2,4); } #endif } #ifdef JUSTENOUGH // LEFTOVERS: END OF VECTOR if (p2optrem>0) { //flag is a control to correctly shrink the Leftover vector when in the bottom corner of the distance matrix Only necessary when p1Array=p2Array if (i>maxBegVect && sameArray){ flag++; } // get 4 deltacoords #ifndef DBLSPD __m128 dx = _mm_sub_ps(p1x, *(p2x)); __m128 dy = _mm_sub_ps(p1y, *(p2y)); __m128 dz = _mm_sub_ps(p1z, *(p2z)); #else __m128 dx = _mm_sub_ps(p1x, *(p2x++)); __m128 dy = _mm_sub_ps(p1y, *(p2y++)); __m128 dz = _mm_sub_ps(p1z, *(p2z++)); #endif // square dx = _mm_mul_ps(dx, dx); dy = _mm_mul_ps(dy, dy); dz = _mm_mul_ps(dz, dz); // sum dx+dy+dz __m128 d2 = _mm_add_ps(dx, dy); d2 = _mm_add_ps(d2, dz); //subtract the offset of the distances d2 = _mm_sub_ps(d2,d0); #ifdef DBLSPD if(p2optrem>4){ dx = _mm_sub_ps(p1x, *(p2x)); dy = _mm_sub_ps(p1y, *(p2y)); dz = _mm_sub_ps(p1z, *(p2z)); dx = _mm_mul_ps(dx, dx); dy = _mm_mul_ps(dy, dy); dz = _mm_mul_ps(dz, dz); } #endif // square root #ifdef USESQRT d2 = _mm_sqrt_ps(d2); #endif // get entry points in the PDF table #ifndef NOUSESTEP d2 = _mm_mul_ps(d2,pvals); #endif __m128i jumps = _mm_cvtps_epi32(d2); #ifdef DBLSPD __m128 d22; __m128i jumps2; if (p2optrem>4){ d22= _mm_add_ps(dx, dy); d22 = _mm_add_ps(d22, dz); //subtract the offset of the distances d22 = _mm_sub_ps(d22,d0); #ifndef NOUSESTEP d22 = _mm_mul_ps(d22,pvals); #endif jumps2 = _mm_cvtps_epi32(d22); } #endif // update PDF //Start at flag and only increase the PDF for the flag<=k<=p2optrem for (int i=0;i<4;i++){ if (i<p2optrem && i>=flag) pResult[_mm_cvtsi128_si32(jumps)]++; jumps=_mm_srli_si128(jumps,4); } #ifdef DBLSPD for (int i=0;i<4;i++){ if (i<p2optrem-4 && i>=flag-4) pResult[_mm_cvtsi128_si32(jumps2)]++; jumps2=_mm_srli_si128(jumps2,4); } #endif } #endif } } int Distance::CalcDistLatticeSym(int _shell, Position *firstPos) { int i, j, k, n1, n2, place, nbins; Position *curPos=firstPos; float *x1, *y1, *z1, *x2, *y2, *z2; float minx=0, miny=0, minz=0, maxx=0, maxy=0, maxz=0; double *d, *m; //Calc max number of possible dist shell=_shell; for (i=1;i<shell;i++){ curPos=curPos->nextPos; } x1=curPos->x; y1=curPos->y; z1=curPos->z; n1=curPos->nAtoms; for (i=0;i<n1;i++){ maxx=getmax(maxx,x1[i]); minx=getmin(minx,x1[i]); maxy=getmax(maxy,y1[i]); miny=getmin(miny,y1[i]); maxz=getmax(maxz,z1[i]); minz=getmin(minz,z1[i]); } nbins=int(ceil(((maxx-minx)*(maxx-minx)+(maxy-miny)*(maxy-miny)+(maxz-minz)*(maxz-minz))*2)+1); try { d=new double [nbins]; m=new double [nbins]; } catch (exception& e){ printf("\nException found in CalcDistances alloc: %s\n", e.what()); return -1; } for(i=0;i<nbins;i++){ d[i]=i/2.0; m[i]=0; } //Calc distances within shell x2=curPos->x; y2=curPos->y; z2=curPos->z; m[0]+=n1; for (i=0;i<n1;i++){ for (j=i+1;j<n1;j++){ place=int(2*((x1[i]-x2[j])*(x1[i]-x2[j])+(y1[i]-y2[j])*(y1[i]-y2[j])+(z1[i]-z2[j])*(z1[i]-z2[j]))); if(place<nbins) m[place]+=2.0; else{ printf("\nError: Calculated distance larger than allowed in histogram array\n"); return -1; } } } //Calc distances btw shell and smaller shells curPos=firstPos; for (k=1;k<shell;k++){ n2=curPos->nAtoms; x2=curPos->x; y2=curPos->y; z2=curPos->z; for (i=0;i<n1;i++){ for (j=0;j<n2;j++){ place=int(2*((x1[i]-x2[j])*(x1[i]-x2[j])+(y1[i]-y2[j])*(y1[i]-y2[j])+(z1[i]-z2[j])*(z1[i]-z2[j]))); m[place]+=2.0; } } curPos=curPos->nextPos; } //compress distances for (i=0;i<nbins;i++){ if (m[i]!=0) nDist++; } try{ dist=new double [nDist]; mult=new double [nDist]; } catch (exception& e){ printf("\nException found in CalcDistances alloc: %s\n", e.what()); return -1; } //Set the class variables place=0; for (i=0;i<nbins;i++){ if (m[i]!=0){ dist[place]=sqrt(d[i]); mult[place]=m[i]; place++; } } delete [] d; delete [] m; return 0; } void Distance::ConsolidateDistance() { int nNZDist=0; double *d, *m; for (int i=0;i<nDist;i++){ if (mult[i]!=0) nNZDist++; } try{ d= new double [nNZDist]; m= new double [nNZDist]; } catch (exception& e){ printf("\nException found in ConsolidateDistance alloc: %s\n", e.what()); exit(-1); } nNZDist=0; for (int i=0;i<nDist;i++){ if (mult[i]!=0) { d[nNZDist]=dist[i]; m[nNZDist]=mult[i]; nNZDist++; } } try{ delete [] dist; delete [] mult; dist=new double [nNZDist]; mult=new double [nNZDist]; } catch (exception& e){ printf("\nException found in ConsolidateDistance alloc: %s\n", e.what()); exit(-1); } nDist=nNZDist; for (int i=0;i<nDist;i++){ dist[i]=d[i]; mult[i]=m[i]; } delete [] d; delete [] m; } void Distance::InitDistance(int nD) { nDist=nD; try{ if (dist!=0) delete [] dist; dist= new double [nDist]; if (mult!=0) delete [] mult; mult= new double [nDist]; } catch (exception& e){ printf("\nException found in InitDistance alloc: %s", e.what()); exit(1); } //Do not need to recalculate sqrts for distances that already exist for (int i=0;i<nDist;i++){ mult[i]=0; dist[i]=sqrt(i*SRPREC); } } void Distance::ScaleDistance(double scale) { for (int i=0;i<nDist;i++){ dist[i]*=scale; } }
[ [ [ 1, 784 ] ] ]
8be5ccf7518f8551b76ca3d39ab256a4a5e37544
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/OggVorbisLib/symbian/tremor/res012.cpp
3c967d0e6cd814907dbaab024fa9864406407e44
[ "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
9,428
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-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: residue backend 0, 1 and 2 implementation ********************************************************************/ #include "os.h" #include <stdlib.h> #include <string.h> #include <math.h> #include "ogg.h" #include "ivorbiscodec.h" #include "codec_internal.h" #include "registry.h" #include "codebook.h" #include "misc.h" #include "block.h" typedef struct { vorbis_info_residue0 *info; int map; int parts; int stages; codebook *fullbooks; codebook *phrasebook; codebook ***partbooks; int partvals; int **decodemap; } vorbis_look_residue0; void res0_free_info(vorbis_info_residue *i){ vorbis_info_residue0 *info=(vorbis_info_residue0 *)i; if(info){ memset(info,0,sizeof(*info)); _ogg_free(info); } } void res0_free_look(vorbis_look_residue *i){ int j; if(i){ vorbis_look_residue0 *look=(vorbis_look_residue0 *)i; for(j=0;j<look->parts;j++) if(look->partbooks[j])_ogg_free(look->partbooks[j]); _ogg_free(look->partbooks); for(j=0;j<look->partvals;j++) _ogg_free(look->decodemap[j]); _ogg_free(look->decodemap); memset(look,0,sizeof(*look)); _ogg_free(look); } } static int ilog(unsigned int v){ int ret=0; while(v){ ret++; v>>=1; } return(ret); } static int icount(unsigned int v){ int ret=0; while(v){ ret+=v&1; v>>=1; } return(ret); } /* vorbis_info is for range checking */ vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){ int j,acc=0; vorbis_info_residue0 *info=(vorbis_info_residue0 *)_ogg_calloc(1,sizeof(*info)); codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; info->begin=oggpack_read(opb,24); info->end=oggpack_read(opb,24); info->grouping=oggpack_read(opb,24)+1; info->partitions=oggpack_read(opb,6)+1; info->groupbook=oggpack_read(opb,8); for(j=0;j<info->partitions;j++){ int cascade=oggpack_read(opb,3); if(oggpack_read(opb,1)) cascade|=(oggpack_read(opb,5)<<3); info->secondstages[j]=cascade; acc+=icount(cascade); } for(j=0;j<acc;j++) info->booklist[j]=oggpack_read(opb,8); if(info->groupbook>=ci->books)goto errout; for(j=0;j<acc;j++) if(info->booklist[j]>=ci->books)goto errout; return(info); errout: res0_free_info(info); return(NULL); } vorbis_look_residue *res0_look(vorbis_dsp_state *vd,vorbis_info_mode *vm, vorbis_info_residue *vr){ vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr; vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look)); codec_setup_info *ci=(codec_setup_info *)vd->vi->codec_setup; int j,k,acc=0; int dim; int maxstage=0; look->info=info; look->map=vm->mapping; look->parts=info->partitions; look->fullbooks=ci->fullbooks; look->phrasebook=ci->fullbooks+info->groupbook; dim=look->phrasebook->dim; look->partbooks=(codebook ***)_ogg_calloc(look->parts,sizeof(*look->partbooks)); for(j=0;j<look->parts;j++){ int stages=ilog(info->secondstages[j]); if(stages){ if(stages>maxstage)maxstage=stages; look->partbooks[j]=(codebook **)_ogg_calloc(stages,sizeof(*look->partbooks[j])); for(k=0;k<stages;k++) if(info->secondstages[j]&(1<<k)){ look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++]; #ifdef TRAIN_RES look->training_data[k][j]=calloc(look->partbooks[j][k]->entries, sizeof(***look->training_data)); #endif } } } look->partvals=look->parts; for(j=1;j<dim;j++)look->partvals*=look->parts; look->stages=maxstage; look->decodemap=(int **)_ogg_malloc(look->partvals*sizeof(*look->decodemap)); for(j=0;j<look->partvals;j++){ long val=j; long mult=look->partvals/look->parts; look->decodemap[j]=(int *)_ogg_malloc(dim*sizeof(*look->decodemap[j])); for(k=0;k<dim;k++){ long deco=val/mult; val-=deco*mult; mult/=look->parts; look->decodemap[j][k]=deco; } } return(look); } /* a truncated packet here just means 'stop working'; it's not an error */ static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl, ogg_int32_t **in,int ch, long (*decodepart)(codebook *, ogg_int32_t *, oggpack_buffer *,int,int)){ long i,j,k,l,s; vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl; vorbis_info_residue0 *info=look->info; /* move all this setup out later */ int samples_per_partition=info->grouping; int partitions_per_word=look->phrasebook->dim; int n=info->end-info->begin; int partvals=n/samples_per_partition; int partwords=(partvals+partitions_per_word-1)/partitions_per_word; int ***partword=(int ***)_ogg_malloc(ch*sizeof(*partword)); for(j=0;j<ch;j++) partword[j]=(int **)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j])); for(s=0;s<look->stages;s++){ /* each loop decodes on partition codeword containing partitions_pre_word partitions */ for(i=0,l=0;i<partvals;l++){ if(s==0){ /* fetch the partition word for each channel */ for(j=0;j<ch;j++){ int temp=vorbis_book_decode(look->phrasebook,&vb->opb); if(temp==-1)goto eopbreak; partword[j][l]=look->decodemap[temp]; if(partword[j][l]==NULL)goto errout; } } /* now we decode residual values for the partitions */ for(k=0;k<partitions_per_word && i<partvals;k++,i++) for(j=0;j<ch;j++){ long offset=info->begin+i*samples_per_partition; if(info->secondstages[partword[j][l][k]]&(1<<s)){ codebook *stagebook=look->partbooks[partword[j][l][k]][s]; if(stagebook){ if(decodepart(stagebook,in[j]+offset,&vb->opb, samples_per_partition,-8)==-1)goto eopbreak; } } } } } errout: eopbreak: _ogg_free(partword); return(0); } int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl, ogg_int32_t **in,int *nonzero,int ch){ int i,used=0; for(i=0;i<ch;i++) if(nonzero[i]) in[used++]=in[i]; if(used) return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add)); else return(0); } int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl, ogg_int32_t **in,int *nonzero,int ch){ int i,used=0; for(i=0;i<ch;i++) if(nonzero[i]) in[used++]=in[i]; if(used) return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add)); else return(0); } /* duplicate code here as speed is somewhat more important */ int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl, ogg_int32_t **in,int *nonzero,int ch){ long i,k,l,s; vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl; vorbis_info_residue0 *info=look->info; /* move all this setup out later */ int samples_per_partition=info->grouping; int partitions_per_word=look->phrasebook->dim; int n=info->end-info->begin; int partvals=n/samples_per_partition; int partwords=(partvals+partitions_per_word-1)/partitions_per_word; int **partword=(int **)_vorbis_block_alloc(vb,partwords*sizeof(*partword)); int beginoff=info->begin/ch; for(i=0;i<ch;i++)if(nonzero[i])break; if(i==ch)return(0); /* no nonzero vectors */ samples_per_partition/=ch; for(s=0;s<look->stages;s++){ for(i=0,l=0;i<partvals;l++){ if(s==0){ /* fetch the partition word */ int temp=vorbis_book_decode(look->phrasebook,&vb->opb); if(temp==-1)goto eopbreak; partword[l]=look->decodemap[temp]; if(partword[l]==NULL)goto errout; } /* now we decode residual values for the partitions */ for(k=0;k<partitions_per_word && i<partvals;k++,i++) if(info->secondstages[partword[l][k]]&(1<<s)){ codebook *stagebook=look->partbooks[partword[l][k]][s]; if(stagebook){ if(vorbis_book_decodevv_add(stagebook,in, i*samples_per_partition+beginoff,ch, &vb->opb, samples_per_partition,-8)==-1) goto eopbreak; } } } } errout: eopbreak: return(0); } const vorbis_func_residue residue0_exportbundle={ &res0_unpack, &res0_look, &res0_free_info, &res0_free_look, &res0_inverse }; const vorbis_func_residue residue1_exportbundle={ &res0_unpack, &res0_look, &res0_free_info, &res0_free_look, &res1_inverse }; const vorbis_func_residue residue2_exportbundle={ &res0_unpack, &res0_look, &res0_free_info, &res0_free_look, &res2_inverse };
[ [ [ 1, 336 ] ] ]
1bf97b3e75ae46b4acdc2a8e81af55073f38a5d1
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2006-04-24/pcbnew/board.cpp
2af463d6e2df970fbffb93042e0b0b507fe7e629
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
UTF-8
C++
false
false
14,180
cpp
/************************************************/ /* EDITEUR de PCB: AUTOROUTAGE: routines d'init */ /************************************************/ /* Fichier BOARD.CC */ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "pcbnew.h" #include "autorout.h" #include "cell.h" #include "protos.h" /* routines externes : */ /* Routines definies ici: */ int Build_Work(BOARD * Pcb, CHEVELU* pt_base_chevelu); void PlaceCells(BOARD * Pcb, int net_code, int flag); int InitBoard( void ); BoardCell GetCell( int, int, int ); void SetCell(int row,int col,int side,BoardCell x ); void OrCell( int, int, int, BoardCell ); void AndCell( int, int, int, BoardCell ); void AddCell( int, int, int, BoardCell ); void XorCell( int, int, int, BoardCell ); void AddCell( int, int, int, BoardCell ); DistCell GetDist( int, int, int ); void SetDist( int, int, int, DistCell ); int GetDir( int, int, int ); void SetDir( int, int, int, int ); /*****************************************************************/ bool ComputeMatriceSize(WinEDA_BasePcbFrame * frame, int pas_route) /*****************************************************************/ /* Calcule Nrows et Ncols, dimensions de la matrice de representation du BOARD pour les routages automatiques et calculs de zone */ { BOARD * pcb = frame->m_Pcb; pcb->ComputeBoundaryBox(); /* The boundary box must have its start point on routing grid: */ pcb->m_BoundaryBox.m_Pos.x -= pcb->m_BoundaryBox.m_Pos.x % pas_route; pcb->m_BoundaryBox.m_Pos.y -= pcb->m_BoundaryBox.m_Pos.y % pas_route; /* The boundary box must have its end point on routing grid: */ wxPoint end = pcb->m_BoundaryBox.GetEnd(); end.x -= end.x % pas_route; end.x += pas_route; end.y -= end.y % pas_route; end.y += pas_route; pcb->m_BoundaryBox.SetEnd(end); Nrows = pcb->m_BoundaryBox.m_Size.y / pas_route ; Ncols = pcb->m_BoundaryBox.m_Size.x / pas_route ; /* get a small margin for memory allocation: */ Ncols += 2; Nrows += 2; return TRUE; } /*******************/ /* class BOARDHEAD */ /*******************/ BOARDHEAD::BOARDHEAD(void) { m_BoardSide[0] = m_BoardSide[1] = NULL; m_DistSide[0] = m_DistSide[1] = NULL; m_DirSide[0] = m_DirSide[1] = NULL; m_InitBoardDone = FALSE; m_Layers = 2; m_Nrows = m_Ncols = 0; m_MemSize = 0; } BOARDHEAD::~BOARDHEAD(void) { } /******************************/ int BOARDHEAD::InitBoard (void) /*****************************/ /* initialize the data structures retourne la taille RAM utilisee, ou -1 si defaut */ { int ii, kk; if (Nrows <= 0 || Ncols <= 0) return(0); m_Nrows = Nrows; m_Ncols = Ncols; m_InitBoardDone = TRUE; /* we have been called */ ii = (Nrows+1) * (Ncols+1); for ( kk = 0; kk < m_Layers; kk++ ) { m_BoardSide[kk] = NULL; m_DistSide[kk] = NULL; m_DirSide[kk] = NULL; /* allocate Board & initialize everything to empty */ m_BoardSide[kk] = (BoardCell*)MyZMalloc( ii * sizeof (BoardCell) ); if( m_BoardSide[kk] == NULL) return(-1); /***** allocate Distances *****/ m_DistSide[kk] = (DistCell *)MyZMalloc( ii * sizeof(DistCell) ); if (m_DistSide[kk] == NULL) return(-1); /***** allocate Dir (chars) *****/ m_DirSide[kk] = (char *)MyZMalloc( ii ); if (m_DirSide[kk] == NULL) return( -1 ); } m_MemSize = m_Layers * ii * ( sizeof(BoardCell) + sizeof(DistCell) + sizeof(char) ); return(m_MemSize); } /*********************************/ void BOARDHEAD::UnInitBoard(void) /*********************************/ /* deallocation de la memoire */ { int ii; m_InitBoardDone = FALSE; for ( ii = 0; ii < 2; ii++ ) { /***** de-allocate Dir (chars) *****/ if( m_DirSide[ii] ) { MyFree(m_DirSide[ii]); m_DirSide[ii] = NULL; } /***** de-allocate Distances *****/ if( m_DistSide[ii] ) { MyFree(m_DistSide[ii]); m_DistSide[ii] = NULL; } /**** de-allocate Board *****/ if( m_BoardSide[ii] ) { MyFree(m_BoardSide[ii]); m_BoardSide[ii] = NULL; } } m_Nrows = m_Ncols = 0; } /*****************************************************/ void PlaceCells(BOARD * Pcb, int net_code, int flag) /*****************************************************/ /* Initialise les cellules du board a la valeur HOLE et VIA_IMPOSSIBLE selon les marges d'isolement les elements de net_code = net_code ne seront pas places comme occupe mais en VIA_IMPOSSIBLE uniquement Pour Routage 1 seule face: le plan BOTTOM est utilise et Route_Layer_BOTTOM = Route_Layer_TOP Selon les bits = 1 du parametre flag: si FORCE_PADS : tous les pads seront places meme ceux de meme net_code */ { int ii; LISTE_PAD* ptr; TRACK * pt_segm; TEXTE_PCB * PtText; DRAWSEGMENT * DrawSegm; EDA_BaseStruct * PtStruct; int ux0 = 0 , uy0 = 0, ux1, uy1, dx, dy; int marge, via_marge; int masque_layer; marge = g_DesignSettings.m_TrackClearence + (g_DesignSettings.m_CurrentTrackWidth /2); via_marge = g_DesignSettings.m_TrackClearence + (g_DesignSettings.m_CurrentViaSize /2); ///////////////////////////////////// // Placement des PADS sur le board // ///////////////////////////////////// ptr = (LISTE_PAD*)Pcb->m_Pads; ii = Pcb->m_NbPads; for( ; ii > 0 ; ii-- , ptr++) { if( (net_code != (*ptr)->m_NetCode ) || (flag & FORCE_PADS) ) { Place_1_Pad_Board(Pcb, *ptr, HOLE, marge, WRITE_CELL); } Place_1_Pad_Board(Pcb, *ptr, VIA_IMPOSSIBLE, via_marge, WRITE_OR_CELL); } /////////////////////////////////////////////// // Placement des elements de modules sur PCB // /////////////////////////////////////////////// PtStruct = Pcb->m_Modules; for( ; PtStruct != NULL; PtStruct = PtStruct->Pnext ) { EDA_BaseStruct * PtModStruct = ((MODULE*)PtStruct)->m_Drawings; for( ;PtModStruct != NULL; PtModStruct = PtModStruct->Pnext ) { switch( PtModStruct->m_StructType ) { case TYPEEDGEMODULE: { TRACK * TmpSegm = new TRACK(NULL); TmpSegm->m_Layer = ((EDGE_MODULE *) PtModStruct)->m_Layer; if(TmpSegm->m_Layer == EDGE_N) TmpSegm->m_Layer = -1; TmpSegm->m_Start = ((EDGE_MODULE *) PtModStruct)->m_Start; TmpSegm->m_End = ((EDGE_MODULE *) PtModStruct)->m_End; TmpSegm->m_Shape = ((EDGE_MODULE *) PtModStruct)->m_Shape; TmpSegm->m_Width = ((EDGE_MODULE *) PtModStruct)->m_Width; TmpSegm->m_Param = ((EDGE_MODULE *) PtModStruct)->m_Angle; TmpSegm->m_NetCode = -1; TraceSegmentPcb(Pcb, TmpSegm, HOLE, marge,WRITE_CELL ); TraceSegmentPcb(Pcb, TmpSegm, VIA_IMPOSSIBLE, via_marge, WRITE_OR_CELL ); delete TmpSegm; break; } default: break; } } } //////////////////////////////////////////// // Placement des contours et segments PCB // //////////////////////////////////////////// PtStruct = Pcb->m_Drawings; for( ; PtStruct != NULL; PtStruct = PtStruct->Pnext ) { switch( PtStruct->m_StructType) { case TYPEDRAWSEGMENT: { int type_cell = HOLE; TRACK * TmpSegm = new TRACK(NULL); DrawSegm = (DRAWSEGMENT *) PtStruct; TmpSegm->m_Layer = DrawSegm->m_Layer; if(DrawSegm->m_Layer == EDGE_N) { TmpSegm->m_Layer = -1; type_cell |= CELL_is_EDGE; } TmpSegm->m_Start = DrawSegm->m_Start; TmpSegm->m_End = DrawSegm->m_End; TmpSegm->m_Shape = DrawSegm->m_Shape; TmpSegm->m_Width = DrawSegm->m_Width; TmpSegm->m_Param = DrawSegm->m_Angle; TmpSegm->m_NetCode = -1; TraceSegmentPcb(Pcb, TmpSegm, type_cell, marge,WRITE_CELL ); // TraceSegmentPcb(Pcb, TmpSegm, VIA_IMPOSSIBLE, via_marge,WRITE_OR_CELL ); delete TmpSegm; break; } case TYPETEXTE: PtText = (TEXTE_PCB*) PtStruct; if(PtText->GetLength() == 0 ) break; ux0 = PtText->m_Pos.x; uy0 = PtText->m_Pos.y; dx = PtText->Pitch()* PtText->GetLength(); dy = PtText->m_Size.y + PtText->m_Width; /* Calcul du rectangle d'encadrement */ dx /= 2; dy /= 2; /* dx et dy = demi dimensionx X et Y */ ux1 = ux0 + dx; uy1 = uy0 + dy; ux0 -= dx; uy0 -= dy; masque_layer = g_TabOneLayerMask[PtText->m_Layer]; TraceFilledRectangle(Pcb, ux0-marge, uy0-marge, ux1+marge, uy1+marge, (int)(PtText->m_Orient), masque_layer, HOLE, WRITE_CELL); TraceFilledRectangle(Pcb, ux0-via_marge, uy0-via_marge, ux1+via_marge, uy1+via_marge, (int)(PtText->m_Orient), masque_layer, VIA_IMPOSSIBLE, WRITE_OR_CELL); break; default: break; } } /* Placement des PISTES */ pt_segm = Pcb->m_Track; for( ; pt_segm != NULL; pt_segm = (TRACK*) pt_segm->Pnext) { if(net_code == pt_segm->m_NetCode) continue; TraceSegmentPcb(Pcb, pt_segm, HOLE, marge, WRITE_CELL ); TraceSegmentPcb(Pcb, pt_segm, VIA_IMPOSSIBLE, via_marge, WRITE_OR_CELL ); } /* Placement des ZONES */ pt_segm = (TRACK*) Pcb->m_Zone; for( ; pt_segm != NULL; pt_segm = (TRACK*) pt_segm->Pnext) { if(net_code == pt_segm->m_NetCode) continue; TraceSegmentPcb(Pcb, pt_segm, HOLE, marge, WRITE_CELL ); TraceSegmentPcb(Pcb, pt_segm, VIA_IMPOSSIBLE, via_marge, WRITE_OR_CELL ); } } /******************************************************/ int Build_Work(BOARD * Pcb, CHEVELU* pt_base_chevelu) /*****************************************************/ /* Build liste conn */ { int ii; CHEVELU* pt_rats = pt_base_chevelu; D_PAD * pt_pad; int r1,r2, c1,c2, current_net_code; CHEVELU * pt_ch; int demi_pas = pas_route /2; wxString msg; InitWork(); /* clear work list */ Ntotal = 0; for ( ii = Pcb->GetNumRatsnests(); ii > 0 ; ii-- , pt_rats++) { /* On ne route que les chevelus actifs et routables */ if( (pt_rats->status & CH_ACTIF) == 0) continue; if( pt_rats->status & CH_UNROUTABLE) continue; if( (pt_rats->status & CH_ROUTE_REQ) == 0 ) continue; pt_pad = pt_rats->pad_start; current_net_code = pt_pad->m_NetCode; pt_ch = pt_rats; r1 = (pt_pad->m_Pos.y - Pcb->m_BoundaryBox.m_Pos.y + demi_pas ) / pas_route; if( r1 < 0 || r1 >= Nrows) { msg.Printf( wxT("erreur : row = %d ( padY %d pcbY %d) "), r1, pt_pad->m_Pos.y, Pcb->m_BoundaryBox.m_Pos.y); DisplayError(NULL, msg); return(0); } c1 = (pt_pad->m_Pos.x - Pcb->m_BoundaryBox.m_Pos.x + demi_pas ) / pas_route; if( c1 < 0 || c1 >= Ncols) { msg.Printf( wxT("erreur : col = %d ( padX %d pcbX %d) "), c1, pt_pad->m_Pos.x, Pcb->m_BoundaryBox.m_Pos.x); DisplayError(NULL, msg); return(0); } pt_pad = pt_rats->pad_end; r2 = (pt_pad->m_Pos.y - Pcb->m_BoundaryBox.m_Pos.y + demi_pas ) / pas_route; if( r2 < 0 || r2 >= Nrows) { msg.Printf( wxT("erreur : row = %d ( padY %d pcbY %d) "), r2, pt_pad->m_Pos.y, Pcb->m_BoundaryBox.m_Pos.y); DisplayError(NULL, msg); return(0); } c2 = (pt_pad->m_Pos.x - Pcb->m_BoundaryBox.m_Pos.x + demi_pas ) / pas_route; if( c2 < 0 || c2 >= Ncols) { msg.Printf( wxT("erreur : col = %d ( padX %d pcbX %d) "), c2, pt_pad->m_Pos.x, Pcb->m_BoundaryBox.m_Pos.x); DisplayError(NULL, msg); return(0); } SetWork( r1, c1, current_net_code, r2, c2, pt_ch, 0 ); Ntotal++; } SortWork(); return(Ntotal); } /*******************************************/ BoardCell GetCell(int row,int col,int side ) /*******************************************/ /* fetch board cell : */ { BoardCell *p; p = Board.m_BoardSide[side]; return( p[row*Ncols +col] ); } /************************************************/ /* void SetCell(int r,int c,int s,BoardCell x ) */ /************************************************/ /* store board cell */ void SetCell(int row,int col,int side,BoardCell x ) { BoardCell *p; p = Board.m_BoardSide[side]; p[row*Ncols+col] = x; } /******************************************/ /* void OrCell(int r,int c,int s,BoardCell x ) */ /******************************************/ void OrCell(int r,int c,int s,BoardCell x ) { BoardCell *p; p = Board.m_BoardSide[s]; p[r*Ncols+c] |= x; } /******************************************/ /* void XorCell(int r,int c,int s,BoardCell x ) */ /******************************************/ void XorCell(int r,int c,int s,BoardCell x ) { BoardCell *p; p = Board.m_BoardSide[s]; p[r*Ncols+c] ^= x; } /************************************************/ /* void AndCell(int r,int c,int s,BoardCell x ) */ /************************************************/ void AndCell(int r,int c,int s,BoardCell x ) { BoardCell *p; p = Board.m_BoardSide[s]; p[r*Ncols+c] &= x; } /************************************************/ /* void AddCell(int r,int c,int s,BoardCell x ) */ /************************************************/ void AddCell(int r,int c,int s,BoardCell x ) { BoardCell *p; p = Board.m_BoardSide[s]; p[r*Ncols+c] += x; } /****************************************/ /* DistCell GetDist(int r,int c,int s ) */ /****************************************/ /* fetch distance cell */ DistCell GetDist(int r,int c,int s ) /* fetch distance cell */ { DistCell *p; p = Board.m_DistSide[s]; return( p[r*Ncols+c] ); } /***********************************************/ /* void SetDist(int r,int c,int s,DistCell x ) */ /***********************************************/ /* store distance cell */ void SetDist(int r,int c,int s,DistCell x ) { DistCell *p; p = Board.m_DistSide[s]; p[r*Ncols+c] = x; } /**********************************/ /* int GetDir(int r,int c,int s ) */ /**********************************/ /* fetch direction cell */ int GetDir(int r,int c,int s ) { char *p; p = Board.m_DirSide[s]; return( (int)(p[r*Ncols+c]) ); } /*****************************************/ /* void SetDir(int r,int c,int s,int x ) */ /*****************************************/ /* store direction cell */ void SetDir(int r,int c,int s,int x ) { char *p; p = Board.m_DirSide[s]; p[r*Ncols+c] = (char)x; }
[ "fcoiffie@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 520 ] ] ]
aede764822c14dc3199236bfebd4d6b3f9170511
05f4bd87bd001ab38701ff8a71d91b198ef1cb72
/TPTaller/TP3/src/Escenario.cpp
d747685d5534fad4c38c15e0b066123db8528e73
[]
no_license
oscarcp777/tpfontela
ef6828a57a0bc52dd7313cde8e55c3fd9ff78a12
2489442b81dab052cf87b6dedd33cbb51c2a0a04
refs/heads/master
2016-09-01T18:40:21.893393
2011-12-03T04:26:33
2011-12-03T04:26:33
35,110,434
0
0
null
null
null
null
ISO-8859-1
C++
false
false
19,512
cpp
#include <stdio.h> #include <list> #include <windows.h> #include "Escenario.h" #include <utility> #include "archivoTexto.h" #include "Posicion.h" #include "Teclado.h" #include "Pad.h" #include "Tejo.h" #include "Define.h" #include "GraficadorPuntajes.h" const string configDefaultEscenario = "config Default Escenario.txt"; Escenario::Escenario(){ //los siguientes son valores por defecto (si existe <General> estos se modificaran) this->icono=NULL; this->fondoPantalla=NULL; this->setResolucion(RESOLUCION_800); this->texturaFig = "FigDefault"; this->texturaEsc = "EscDefault"; this->setColorFondoEscenario(new Color(0,0,0)); this->setColorFondoFiguras(new Color(42,0,246)); this->setColorLinea(new Color(255,0,0)); inicializarLog(this->log, "errores.err"); this->validador = new Validador("config Validador.txt","config Atributos.txt"); escribirTituloLog(*(this->getLog()),"DESCRIPCION DE ERRORES"); this->validador->setLog(&(this->log)); this->padJugador = NULL; this->bonusActual = NULL; //levanto del archivo siguiente las texturas por default para el escenario ArchivoTexto miArchivoDefault(configDefaultEscenario); string linea; //la primera linea tiene el path de textura escenario por default miArchivoDefault.leerLinea(linea); Textura * texturaEscDefault = new Textura("EscDefault", linea); // this->addTextura(texturaEscDefault); this->tejosRestantes = 7; this->numeroNivel = 1; this->primerPintada = false; } void Escenario::servidorInicializarListaBonus(){ DecLongPad* decLongPad = new DecLongPad(); decLongPad->setTipoBonus(DEC_LONG_PAD); this->listaBonus.push_back(decLongPad); DecLongPadVs* decLongPadVs = new DecLongPadVs(); decLongPadVs->setTipoBonus(DEC_LONG_PAD_VS); this->listaBonus.push_back(decLongPadVs); DecRadioTejo* decRadioTejo = new DecRadioTejo(); decRadioTejo->setTipoBonus(DEC_RADIO_TEJO); this->listaBonus.push_back(decRadioTejo); IncLongPad* incLongPad = new IncLongPad(); incLongPad->setTipoBonus(INC_LONG_PAD); this->listaBonus.push_back(incLongPad); IncLongPadVs* incLongPadVs = new IncLongPadVs(); incLongPadVs->setTipoBonus(INC_LONG_PAD_VS); this->listaBonus.push_back(incLongPadVs); IncRadioTejo* incRadioTejo = new IncRadioTejo(); incRadioTejo->setTipoBonus(INC_RADIO_TEJO); this->listaBonus.push_back(incRadioTejo); IncVelocidadTejo* incVelocidadTejo = new IncVelocidadTejo(); incVelocidadTejo->setTipoBonus(INC_VELOCIDAD_TEJO); this->listaBonus.push_back(incVelocidadTejo); PegamentoTejo* pegamentoTejo = new PegamentoTejo(); pegamentoTejo->setTipoBonus(PEGAMENTO_TEJO); this->listaBonus.push_back(pegamentoTejo); FrenoTejo* frenoTejo = new FrenoTejo(); frenoTejo->setTipoBonus(FRENO_TEJO); this->listaBonus.push_back(frenoTejo); } void Escenario::clienteInicializarListaBonus(){ DecLongPad* decLongPad = new DecLongPad(); decLongPad->setTipoBonus(DEC_LONG_PAD); decLongPad->cargarImagen("decLongPad"); this->listaBonus.push_back(decLongPad); DecLongPadVs* decLongPadVs = new DecLongPadVs(); decLongPadVs->setTipoBonus(DEC_LONG_PAD_VS); decLongPadVs->cargarImagen("decLongPadVs"); this->listaBonus.push_back(decLongPadVs); DecRadioTejo* decRadioTejo = new DecRadioTejo(); decRadioTejo->setTipoBonus(DEC_RADIO_TEJO); decRadioTejo->cargarImagen("decRadioTejo"); this->listaBonus.push_back(decRadioTejo); IncLongPad* incLongPad = new IncLongPad(); incLongPad->setTipoBonus(INC_LONG_PAD); incLongPad->cargarImagen("incLongPad"); this->listaBonus.push_back(incLongPad); IncLongPadVs* incLongPadVs = new IncLongPadVs(); incLongPadVs->setTipoBonus(INC_LONG_PAD_VS); incLongPadVs->cargarImagen("incLongPadVs"); this->listaBonus.push_back(incLongPadVs); IncRadioTejo* incRadioTejo = new IncRadioTejo(); incRadioTejo->setTipoBonus(INC_RADIO_TEJO); incRadioTejo->cargarImagen("incRadioTejo"); this->listaBonus.push_back(incRadioTejo); IncVelocidadTejo* incVelocidadTejo = new IncVelocidadTejo(); incVelocidadTejo->setTipoBonus(INC_VELOCIDAD_TEJO); incVelocidadTejo->cargarImagen("incVelocidadTejo"); this->listaBonus.push_back(incVelocidadTejo); PegamentoTejo* pegamentoTejo = new PegamentoTejo(); pegamentoTejo->setTipoBonus(PEGAMENTO_TEJO); pegamentoTejo->cargarImagen("pegamentoTejo"); this->listaBonus.push_back(pegamentoTejo); FrenoTejo* frenoTejo = new FrenoTejo(); frenoTejo->setTipoBonus(FRENO_TEJO); frenoTejo->cargarImagen("frenoTejo"); this->listaBonus.push_back(frenoTejo); } void Escenario::shuffleListBonus(){ list<Bonus*>::iterator begin = this->listaBonus.begin(); list<Bonus*>::iterator end = this->listaBonus.end(); list<Bonus*>::iterator p = begin; for (int i = this->listaBonus.size(); i > 0; --i) { for (int r = rand(); r > 0; --r) { if (++p == end) p = begin; } swap<Bonus*>(*begin, *p); } } int Escenario::shuffleListFiguras(){ int res = -1; if(this->sizeListaFiguras()>0){ res = 0; list<Figura*>::iterator begin = this->listaFiguras.begin(); list<Figura*>::iterator end = this->listaFiguras.end(); list<Figura*>::iterator p = begin; for (int i = this->listaFiguras.size(); i > 0; --i) { for (int r = rand(); r > 0; --r) { if (++p == end) p = begin; } swap<Figura*>(*begin, *p); } } return res; } Validador* Escenario::getValidador(){ return this->validador; } Rectangulo* Escenario::getArcoDerecha() { return arcoDerecha; } void Escenario::setArcoDerecha(Rectangulo *arcoDerecha) { this->arcoDerecha = arcoDerecha; } Rectangulo* Escenario::getArcoIzquierda() { return arcoIzquierda; } void Escenario::setArcoIzquierda(Rectangulo *arcoIzquierda) { this->arcoIzquierda = arcoIzquierda; } Escenario::~Escenario(){ //los siguientes son valores por defecto (si existe <General> estos se modificaran) SDL_FreeSurface(this->icono); SDL_FreeSurface(this->fondoPantalla); SDL_FreeSurface(this->buffer); delete this->tejo; delete this->padCliente1; delete this->padCliente2; destruirLog(this->log); delete this->colorLinea; delete this->colorFondoEscenario; delete this->colorFondoFiguras; delete this->validador; delete this->arcoDerecha; delete this->arcoIzquierda; delete this->posicionInicialTejo; this->borrarListaFiguras(); this->borrarListaTexturas(); this->borrarListaBonus(); if(DEBUG_DESTRUCTOR==1) std::cout<<" entro al destructor de Escenario"<<std::endl; } int Escenario::cargarArchivo(std::string nombreArchivo){ return this->validador->validarSintaxis(nombreArchivo); } Escenario* Escenario::unicaInstanciaEscenario = NULL; void Escenario::setTexturaFig(std::string texturaFig){ this->texturaFig=texturaFig; } std::string Escenario::getTexturaFig(){ return this->texturaFig; } std::string Escenario::getTexturaEsc(){ return this->texturaEsc; } void Escenario::setTexturaEsc(std::string texturaEsc){ this->texturaEsc=texturaEsc; } Escenario* Escenario::obtenerInstancia(){ if(!Escenario::unicaInstanciaEscenario){ Escenario::unicaInstanciaEscenario = new Escenario(); } return Escenario::unicaInstanciaEscenario; } void Escenario::setColorFondoEscenario(Color* colorFondoEscenario){ this->colorFondoEscenario=colorFondoEscenario; } void Escenario::setColorFondoFiguras(Color* colorFondoFiguras){ this->colorFondoFiguras=colorFondoFiguras; } void Escenario::setColorLinea(Color* colorLinea){ this->colorLinea=colorLinea; } SDL_Color Escenario::getColorFondoEscenario(){ return this->colorFondoEscenario->getColor(); } Color* Escenario::getColorFondoFiguras(){ return this->colorFondoFiguras; } Color* Escenario::getColorLinea(){ return this->colorLinea; } void Escenario::setAncho(int ancho){ this->ancho=ancho; } int Escenario::getAncho(){ return this->ancho; } void Escenario::setAlto(int alto){ this->alto=alto; } int Escenario::getAlto(){ return this->alto; } int Escenario::getResolucion(){ return this->resolucion; } void Escenario::setResolucion(int resolucion){ this->resolucion=resolucion; if(resolucion==RESOLUCION_640){ this->alto=RESOLUCION_640_ALTO; this->ancho=RESOLUCION_640_ANCHO; } if(resolucion==RESOLUCION_800){ this->alto=RESOLUCION_800_ALTO; this->ancho=RESOLUCION_800_ANCHO; } if(resolucion==RESOLUCION_1024){ this->alto=RESOLUCION_1024_ALTO; this->ancho=RESOLUCION_1024_ANCHO; } if(resolucion==RESOLUCION_1280){ this->alto=RESOLUCION_1280_ALTO; this->ancho=RESOLUCION_1280_ANCHO; } } void Escenario::addFigura(Figura *figura){ //si existe el id de figura tiro error y no lo agrego if(this->existeIdFigura(figura->getId())){ escribirMensajeLog(this->log,"error: idFigura duplicado, ya existia una figura con el id: " + figura->getId() ); } //sino la agrego else{ this->listaFiguras.push_back(figura); } } void Escenario::addTextura(Textura *textura){ this->listaTexturas.push_back(textura); } int Escenario::sizeListaFiguras(){ return this->listaFiguras.size(); } int Escenario::sizeListaBonus(){ return this->listaBonus.size(); } int Escenario::sizeListaTexturas(){ return this->listaTexturas.size(); } std::list<Figura*>::iterator Escenario::iteratorListaFiguras(){ return this->listaFiguras.begin(); } std::list<Bonus*>::iterator Escenario::iteratorListaBonus(){ return this->listaBonus.begin(); } std::list<Textura*>::iterator Escenario::iteratorListaTexturas(){ return this->listaTexturas.begin(); } void Escenario::setIdTextura(std::string idTextura){ this->texturaEsc = idTextura; } Log* Escenario::getLog(){ return &(this->log); } void Escenario::pintarPantalla(){ SDL_Surface *imagen; std::list<Figura*>::iterator iter; iter = this->iteratorListaFiguras(); int res = this->texturaEsc.compare("NULL"); if( res!=0){ if(this->fondoPantalla==NULL){ //si no tiene NULL en texturaEsc std::string path = this->obtenerPathTextura(this->texturaEsc); if(path.compare("NULL") != 0){ //si se encontro el path de la textura imagen = IMG_Load (path.begin()); if(imagen == NULL) { escribirMensajeLog(this->log,"error al intentar cargar la imagen: "+path); SDL_Rect dest; dest.x = 0; dest.y = 0; dest.w = this->screen->w; dest.h = this->screen->h; SDL_Color color = this->getColorFondoEscenario(); SDL_FillRect(screen,&dest,SDL_MapRGB(screen->format, color.r,color.g,color.b)); } if(imagen != NULL){ imagen = Figura::ScaleSurface(imagen, this->getAncho(), this->getAlto()); } } else{ //si NO se encontro el path de la textura, es porque el id no existe en la lista escribirMensajeLog(this->log,"no se encontro el path correspondiente a texturaEsc: "+this->texturaEsc); SDL_Rect dest; dest.x = 0; dest.y = 0; dest.w = this->screen->w; dest.h = this->screen->h; SDL_Color color = this->getColorFondoEscenario(); SDL_FillRect(screen,&dest,SDL_MapRGB(screen->format, color.r,color.g,color.b)); } this->fondoPantalla=SDL_DisplayFormat(imagen); SDL_FreeSurface(imagen); } if(this->fondoPantalla != NULL){ SDL_Rect rect; rect.x =0; rect.y =0; rect.w = this->getAncho(); rect.h = this->getAlto(); SDL_BlitSurface(this->fondoPantalla, NULL,this->buffer, &rect); // dibujo los arcos this->arcoDerecha->dibujar(this->buffer); this->arcoIzquierda->dibujar(this->buffer); int i = 1; Figura *figura; while(i<=this->sizeListaFiguras()){ figura = *iter; figura->dibujar(this->buffer); iter++; i++; } GraficadorPuntajes* graficadorPuntajes=GraficadorPuntajes::obtenerInstancia(); graficadorPuntajes->graficarPuntaje(this->buffer); graficadorPuntajes->graficarCantidadDeTejos(this->buffer); } } } std::string Escenario::obtenerPathTextura(std::string id){ std::list<Textura*>::iterator iter; Textura *textura; iter = this->iteratorListaTexturas(); int i=1; std::string idAux = "NULL"; while(i<=this->sizeListaTexturas()){ textura = *iter; if(textura->getId().compare(id)==0){ return textura->getPath(); } else{ i++; iter++; } } return idAux; } bool Escenario::existeIdFigura(std::string idFigura){ bool existe = false; std::list<Figura*>::iterator iter; Figura *figura; iter = this->iteratorListaFiguras(); int i=1; while(i<=this->sizeListaFiguras()){ figura = *iter; if(figura->getId().compare(idFigura) == 0){ return true; } else{ i++; iter++; } } return existe; } Figura* Escenario::getFiguraPorId(std::string idFigura){ std::list<Figura*>::iterator iter; Figura *figura = NULL; iter = this->iteratorListaFiguras(); int i=1; while(i<=this->sizeListaFiguras()){ figura = *iter; if(figura->getId().compare(idFigura) == 0){ return figura; } else{ i++; iter++; } } return figura; } Bonus* Escenario::obtenerBonusPorTipo(int tipo){ std::list<Bonus*>::iterator iter; Bonus *bonus; iter = this->iteratorListaBonus(); int i=1; while(i<=this->sizeListaBonus()){ bonus = *iter; if(bonus->getTipoBonus() == tipo ){ return bonus; } else{ i++; iter++; } } return bonus; } SDL_Surface* Escenario::getScreen(){ return this->screen; } Posicion* Escenario::getPosicionInicialTejo() { return posicionInicialTejo; } void Escenario::setPosicionInicialTejo(Posicion *posicionInicialTejo) { this->posicionInicialTejo = posicionInicialTejo; } int Escenario::iniciarSDL(){ // Iniciar SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("No se pudo iniciar SDL: %s\n",SDL_GetError()); std::string aux = SDL_GetError(); escribirMensajeLog(this->log,"No se pudo iniciar SDL: " + aux ); exit(1); } atexit(SDL_Quit); // Comprobamos que sea compatible el modo de video if(SDL_VideoModeOK(this->getAncho(), this->getAlto(), 24, SDL_SWSURFACE|SDL_DOUBLEBUF) == 0) { std::cout<< "Modo no soportado: " << SDL_GetError() << endl; exit(1); } //seteamos el titulo a la barra SDL_WM_SetCaption(" Taller de Programacion Grupo Nro:3 GRAFICADOR "," Taller de Programacion Grupo Nro:3 GRAFICADOR "); //SDL_WM_SetIcon(icono, NULL); // Compatible con MS Windows this->screen = SDL_SetVideoMode(this->getAncho(),this->getAlto(),16, SDL_SWSURFACE | SDL_DOUBLEBUF ); this->buffer = SDL_CreateRGBSurface(SDL_SWSURFACE, this->getAncho(), this->getAlto(), 16, 0,0,0,0); if(!this->screen){ std::cout<<"No se pudo iniciar la pantalla: %s"<<SDL_GetError(); std::string aux = SDL_GetError(); escribirMensajeLog(this->log,"No se pudo iniciar la pantalla: " + aux ); exit(1); } return 0; } int Escenario::graficar(){ SDL_Rect rect; rect.x =0; rect.y =0; rect.w = this->getAncho(); rect.h = this->getAlto(); Pad* pad; // Actualización lógica de la posición pad = this->getPadJugador(); if (!primerPintada){ this->pintarPantalla(); primerPintada = true; } SDL_BlitSurface(this->buffer, NULL,this->screen, &rect); this->getPadCliente1()->dibujar(this->screen); this->getPadCliente2()->dibujar(this->screen); this->getTejo()->dibujar(this->screen); SDL_Flip(this->getScreen()); SDL_FreeSurface(this->screen); return 0; } void Escenario::setPadCliente1(Pad *padCliente1){ this->padCliente1 = padCliente1; } void Escenario::setPadCliente2(Pad *padCliente2){ this->padCliente2 = padCliente2; } void Escenario::setTejo(Tejo *tejo){ this->tejo = tejo; } Pad* Escenario::getPadCliente1(){ return this->padCliente1; } Pad* Escenario::getPadCliente2(){ return this->padCliente2; } Tejo* Escenario::getTejo(){ return this->tejo; } /*void Escenario::setNumJugador(int num){ this->numJugador = num; } */ int Escenario::getNumJugador(){ return this->numJugador; } Pad* Escenario::getPadJugador(){ return this->padJugador; } void Escenario::setPadJugador(int jugador){ if (jugador == 1){ this->padJugador = this->getPadCliente1(); this->numJugador=1; } else{ this->padJugador = this->getPadCliente2(); this->numJugador=2; } } int Escenario::getTejosRestantes(){ return this->tejosRestantes; } void Escenario::decrementarTejosRestantes(){ this->tejosRestantes--; } bool Escenario::getCorriendo(){ return this->corriendo; } void Escenario::setCorriendo(bool corriendo){ this->corriendo = corriendo; } void Escenario::setTejosRestantes(int cantTejos){ this->tejosRestantes = cantTejos; } int Escenario::getNumeroNivel(){ return this->numeroNivel; } void Escenario::incrementarNivel(){ this->numeroNivel++; } std::string Escenario::getNumeroNivelEnString(){ std::string cadena; char num[10]; char* pNum = num; char aux1[5]; char* paux1 = aux1; memset(paux1,0,sizeof(char)*5); memset(pNum,0,sizeof(char)*10); itoa(this->numeroNivel,paux1,10); strcat(pNum,paux1); cadena = pNum; return cadena; } void Escenario::borrarListaFiguras(){ list<Figura*>::iterator iterFiguras; Figura* figura; iterFiguras=this->listaFiguras.begin(); while(iterFiguras !=this->listaFiguras.end()){ figura=*iterFiguras; delete figura; iterFiguras++; } if(DEBUG_DESTRUCTOR==1) std::cout<<" entro al borrarListaFiguras"<<endl<<endl; this->listaFiguras.clear(); } void Escenario::borrarListaTexturas(){ list<Textura*>::iterator iterTextura; Textura* textura; iterTextura=this->listaTexturas.begin(); while(iterTextura !=this->listaTexturas.end()){ textura=*iterTextura; delete textura; iterTextura++; } if(DEBUG_DESTRUCTOR==1) std::cout<<" entro al borrarListaTexturas"<<endl<<endl; this->listaTexturas.clear(); } void Escenario::borrarListaBonus(){ list<Bonus*>::iterator iterBonus; Bonus* bonus; iterBonus=this->listaBonus.begin(); while(iterBonus !=this->listaBonus.end()){ bonus=*iterBonus; delete bonus; iterBonus++; } if(DEBUG_DESTRUCTOR==1) std::cout<<" entro al borrarListaBonus"<<endl<<endl; this->listaBonus.clear(); } void Escenario::setearImagenesEnNull(){ this->fondoPantalla = NULL; this->tejo->setImagen(NULL); this->padCliente1->setImagen(NULL); this->padCliente2->setImagen(NULL); this->arcoDerecha->setImagen(NULL); this->arcoIzquierda->setImagen(NULL); GraficadorPuntajes::obtenerInstancia()->setImagen(NULL); } int Escenario::getPosicionYPad(){ return this->posicionYPad; } void Escenario::setPosicionYPad(int pos){ this->posicionYPad = pos; } void Escenario::setGolDe(std::string pad){ this->golDe = pad; } std::string Escenario::getGolDe(){ return this->golDe; } void Escenario::setBonusActual(Bonus* bonus){ this->bonusActual = bonus; } Bonus* Escenario::getBonusActual(){ return this->bonusActual; } void Escenario::setFiguraConBonus(Figura* figura){ this->figuraConBonus = figura; } Figura* Escenario::getFiguraConBonus(){ return this->figuraConBonus; } void Escenario::setPrimerPintada(bool primerPintada){ this->primerPintada = primerPintada; } bool Escenario::getPrimerPintada(){ return this->primerPintada; }
[ "rdubini@a1477896-89e5-11dd-84d8-5ff37064ad4b", "caceres.oscar7@a1477896-89e5-11dd-84d8-5ff37064ad4b" ]
[ [ [ 1, 35 ], [ 37, 587 ], [ 589, 600 ], [ 602, 775 ] ], [ [ 36, 36 ], [ 588, 588 ], [ 601, 601 ] ] ]
c93073fc29b598f092e1db39ea05395a5ee89539
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/test/thread_pool.cpp
00b5667308d83f5808c202e7557f82cdf0fc4ef2
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
7,766
cpp
// Copyright (C) 2008 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #include <sstream> #include <string> #include <cstdlib> #include <ctime> #include <dlib/misc_api.h> #include <dlib/threads.h> #include "tester.h" namespace { using namespace test; using namespace dlib; using namespace std; logger dlog("test.thread_pool"); struct some_struct : noncopyable { float val; }; struct add_functor { template <typename T, typename U, typename V> void operator()(T a, U b, V& res) { dlib::sleep(20); res = a + b; } }; void gset_struct_to_zero (some_struct& a) { a.val = 0; } void gset_to_zero (int& a) { a = 0; } void gincrement (int& a) { ++a; } void gadd (int a, const int& b, int& res) { dlib::sleep(20); res = a + b; } void gadd1(int& a, int& res) { res += a; } void gadd2 (int c, int a, const int& b, int& res) { dlib::sleep(20); res = a + b + c; } class thread_pool_tester : public tester { public: thread_pool_tester ( ) : tester ("test_thread_pool", "Runs tests on the thread_pool component.") {} void perform_test ( ) { for (int num_threads= 0; num_threads < 4; ++num_threads) { thread_pool tp(num_threads); print_spinner(); future<int> a, b, c, res; future<some_struct> obj; for (int i = 0; i < 4; ++i) { a = 1; b = 2; c = 3; res = 4; DLIB_CASSERT(a==a,""); DLIB_CASSERT(a!=b,""); DLIB_CASSERT(a==1,""); tp.add_task(gset_to_zero, a); tp.add_task(gset_to_zero, b); tp.add_task(*this, &thread_pool_tester::set_to_zero, c); tp.add_task(gset_to_zero, res); DLIB_CASSERT(a == 0,""); DLIB_CASSERT(b == 0,""); DLIB_CASSERT(c == 0,""); DLIB_CASSERT(res == 0,""); tp.add_task(gincrement, a); tp.add_task(*this, &thread_pool_tester::increment, b); tp.add_task(*this, &thread_pool_tester::increment, c); tp.add_task(gincrement, res); DLIB_CASSERT(a == 1,""); DLIB_CASSERT(b == 1,""); DLIB_CASSERT(c == 1,""); DLIB_CASSERT(res == 1,""); tp.add_task(&gincrement, a); tp.add_task(*this, &thread_pool_tester::increment, b); tp.add_task(*this, &thread_pool_tester::increment, c); tp.add_task(&gincrement, res); tp.add_task(gincrement, a); tp.add_task(*this, &thread_pool_tester::increment, b); tp.add_task(*this, &thread_pool_tester::increment, c); tp.add_task(gincrement, res); DLIB_CASSERT(a == 3,""); DLIB_CASSERT(b == 3,""); DLIB_CASSERT(c == 3,""); DLIB_CASSERT(res == 3,""); tp.add_task(*this, &thread_pool_tester::increment, c); tp.add_task(gincrement, res); DLIB_CASSERT(c == 4,""); DLIB_CASSERT(res == 4,""); tp.add_task(gadd, a, b, res); DLIB_CASSERT(res == a+b,""); DLIB_CASSERT(res == 6,""); a = 3; b = 4; res = 99; DLIB_CASSERT(res == 99,""); tp.add_task(*this, &thread_pool_tester::add, a, b, res); DLIB_CASSERT(res == a+b,""); DLIB_CASSERT(res == 7,""); a = 1; b = 2; c = 3; res = 88; DLIB_CASSERT(res == 88,""); DLIB_CASSERT(a == 1,""); DLIB_CASSERT(b == 2,""); DLIB_CASSERT(c == 3,""); tp.add_task(gadd2, a, b, c, res); DLIB_CASSERT(res == 6,""); DLIB_CASSERT(a == 1,""); DLIB_CASSERT(b == 2,""); DLIB_CASSERT(c == 3,""); a = 1; b = 2; c = 3; res = 88; DLIB_CASSERT(res == 88,""); DLIB_CASSERT(a == 1,""); DLIB_CASSERT(b == 2,""); DLIB_CASSERT(c == 3,""); tp.add_task(*this, &thread_pool_tester::add2, a, b, c, res); DLIB_CASSERT(res == 6,""); DLIB_CASSERT(a == 1,""); DLIB_CASSERT(b == 2,""); DLIB_CASSERT(c == 3,""); a = 1; b = 2; c = 3; res = 88; tp.add_task(gadd1, a, b); DLIB_CASSERT(a == 1,""); DLIB_CASSERT(b == 3,""); a = 2; tp.add_task(*this, &thread_pool_tester::add1, a, b); DLIB_CASSERT(a == 2,""); DLIB_CASSERT(b == 5,""); val = 4; uint64 id = tp.add_task(*this, &thread_pool_tester::zero_val); tp.wait_for_task(id); DLIB_CASSERT(val == 0,""); id = tp.add_task(*this, &thread_pool_tester::accum2, 1,2); tp.wait_for_all_tasks(); DLIB_CASSERT(val == 3,""); id = tp.add_task(*this, &thread_pool_tester::accum1, 3); tp.wait_for_task(id); DLIB_CASSERT(val == 6,""); obj.get().val = 8; DLIB_CASSERT(obj.get().val == 8,""); tp.add_task(gset_struct_to_zero, obj); DLIB_CASSERT(obj.get().val == 0,""); obj.get().val = 8; DLIB_CASSERT(obj.get().val == 8,""); tp.add_task(*this,&thread_pool_tester::set_struct_to_zero, obj); DLIB_CASSERT(obj.get().val == 0,""); a = 1; b = 2; res = 0; add_functor f; tp.add_task(f, a, b, res); DLIB_CASSERT(a == 1,""); DLIB_CASSERT(b == 2,""); DLIB_CASSERT(res == 3,""); } } } long val; void accum1(long a) { val += a; } void accum2(long a, long b) { val += a + b; } void zero_val() { dlib::sleep(20); val = 0; } void set_struct_to_zero (some_struct& a) { a.val = 0; } void set_to_zero (int& a) { dlib::sleep(20); a = 0; } void increment (int& a) const { dlib::sleep(20); ++a; } void add (int a, const int& b, int& res) { dlib::sleep(20); res = a + b; } void add1(int& a, int& res) const { res += a; } void add2 (int c, int a, const int& b, int& res) { res = a + b + c; } } a; }
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 224 ] ] ]
826a61130d9573415740965ba83020b02686d119
cbe040d6c5be2241d61c706f3c112f5da1b25006
/Calculator/Lexer.h
9c798a40c6803ec84be037d95c2b60c301a98bc8
[]
no_license
ilh19/315-calculator
d95346684cb7a63d803d5fd370243f0e216a3faa
c6762d277d07177a34f50bf28a16438f86664572
refs/heads/master
2020-06-05T00:17:13.711126
2011-04-05T02:45:46
2011-04-05T02:45:46
32,126,597
0
0
null
null
null
null
UTF-8
C++
false
false
377
h
#ifndef LEXER_H #define LEXER_H #include "Token.h" #include "RuntimeException.h" #include <string> #include <vector> using namespace std; class Lexer{ public: Lexer(string str); vector<Token*> v; vector<Token*> get_v()const ; string get_s()const ; void break_into_tokens(); void printfunc()const; private: string s; }; #endif
[ "[email protected]@7330a5c5-07fc-53ea-e431-edd981856d35", "irms19@7330a5c5-07fc-53ea-e431-edd981856d35" ]
[ [ [ 1, 2 ], [ 4, 4 ], [ 6, 11 ], [ 16, 16 ], [ 18, 23 ] ], [ [ 3, 3 ], [ 5, 5 ], [ 12, 15 ], [ 17, 17 ] ] ]
4fc8f2ac8263e394f69d8504931c2693b8ef7256
87d4429333abecd325727ccf81ae8102dbbaefc6
/loginForm.h
4dd70ddd57c6b3fb026db59967599c54c84dc2aa
[]
no_license
jonrohan/SMTPemailclient
499f58539276de739a27771dd7211e6e5c7c43c5
bcc22f898eddbd2c327ca3a1c9a388147c3b3957
refs/heads/master
2020-05-16T23:45:52.764827
2005-03-28T18:40:26
2005-03-28T18:40:26
5,825,153
2
1
null
null
null
null
UTF-8
C++
false
false
11,603
h
#pragma once using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; extern "C++" { void setSmtpServerAddress(String*,int); void setPop3ServerAddress(String*,int); void setUserInfo(String*,String*); String* loginToPop3Server(); } namespace SMTPemailclient { /// <summary> /// Summary for loginForm /// /// WARNING: If you change the name of this class, you will need to change the /// 'Resource File Name' property for the managed resource compiler tool /// associated with all .resx files this class depends on. Otherwise, /// the designers will not be able to interact properly with localized /// resources associated with this form. /// </summary> public __gc class loginForm : public System::Windows::Forms::Form { public: loginForm(void) { InitializeComponent(); } protected: void Dispose(Boolean disposing) { if (disposing && components) { components->Dispose(); } __super::Dispose(disposing); } private: System::Windows::Forms::Label * label1; private: System::Windows::Forms::Label * label2; private: System::Windows::Forms::Label * label3; private: System::Windows::Forms::Label * label4; private: System::Windows::Forms::PictureBox * pictureBox1; private: System::Windows::Forms::Button * button1; private: System::Windows::Forms::Button * button2; private: System::Windows::Forms::TextBox * serverTextBox; private: System::Windows::Forms::TextBox * usernameTextBox; private: System::Windows::Forms::TextBox * passwordTextBox; private: System::Windows::Forms::ErrorProvider * loginError; private: System::Windows::Forms::CheckBox * checkBox1; private: bool pop3enabled; private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container* components; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { System::Resources::ResourceManager * resources = new System::Resources::ResourceManager(__typeof(SMTPemailclient::loginForm)); this->label1 = new System::Windows::Forms::Label(); this->label2 = new System::Windows::Forms::Label(); this->label3 = new System::Windows::Forms::Label(); this->label4 = new System::Windows::Forms::Label(); this->serverTextBox = new System::Windows::Forms::TextBox(); this->usernameTextBox = new System::Windows::Forms::TextBox(); this->passwordTextBox = new System::Windows::Forms::TextBox(); this->pictureBox1 = new System::Windows::Forms::PictureBox(); this->button1 = new System::Windows::Forms::Button(); this->button2 = new System::Windows::Forms::Button(); this->loginError = new System::Windows::Forms::ErrorProvider(); this->checkBox1 = new System::Windows::Forms::CheckBox(); this->SuspendLayout(); // // label1 // this->label1->Font = new System::Drawing::Font(S"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, (System::Byte)0); this->label1->Location = System::Drawing::Point(88, 32); this->label1->Name = S"label1"; this->label1->Size = System::Drawing::Size(296, 24); this->label1->TabIndex = 0; this->label1->Text = S"Please type your user name and password."; // // label2 // this->label2->Font = new System::Drawing::Font(S"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, (System::Byte)0); this->label2->Location = System::Drawing::Point(96, 72); this->label2->Name = S"label2"; this->label2->Size = System::Drawing::Size(88, 24); this->label2->TabIndex = 1; this->label2->Text = S"Server:"; this->label2->TextAlign = System::Drawing::ContentAlignment::MiddleLeft; // // label3 // this->label3->Font = new System::Drawing::Font(S"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, (System::Byte)0); this->label3->Location = System::Drawing::Point(96, 112); this->label3->Name = S"label3"; this->label3->Size = System::Drawing::Size(88, 24); this->label3->TabIndex = 2; this->label3->Text = S"User name:"; this->label3->TextAlign = System::Drawing::ContentAlignment::MiddleLeft; // // label4 // this->label4->Font = new System::Drawing::Font(S"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, (System::Byte)0); this->label4->Location = System::Drawing::Point(96, 152); this->label4->Name = S"label4"; this->label4->Size = System::Drawing::Size(88, 24); this->label4->TabIndex = 3; this->label4->Text = S"Password:"; this->label4->TextAlign = System::Drawing::ContentAlignment::MiddleLeft; // // serverTextBox // this->serverTextBox->Font = new System::Drawing::Font(S"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, (System::Byte)0); this->serverTextBox->Location = System::Drawing::Point(192, 73); this->serverTextBox->Name = S"serverTextBox"; this->serverTextBox->Size = System::Drawing::Size(272, 22); this->serverTextBox->TabIndex = 1; this->serverTextBox->Text = S""; // // usernameTextBox // this->usernameTextBox->Font = new System::Drawing::Font(S"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, (System::Byte)0); this->usernameTextBox->Location = System::Drawing::Point(192, 113); this->usernameTextBox->Name = S"usernameTextBox"; this->usernameTextBox->Size = System::Drawing::Size(272, 22); this->usernameTextBox->TabIndex = 2; this->usernameTextBox->Text = S""; // // passwordTextBox // this->passwordTextBox->Font = new System::Drawing::Font(S"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, (System::Byte)0); this->passwordTextBox->Location = System::Drawing::Point(192, 153); this->passwordTextBox->Name = S"passwordTextBox"; this->passwordTextBox->PasswordChar = '*'; this->passwordTextBox->Size = System::Drawing::Size(272, 22); this->passwordTextBox->TabIndex = 3; this->passwordTextBox->Text = S""; // // pictureBox1 // this->pictureBox1->Image = (__try_cast<System::Drawing::Image * >(resources->GetObject(S"pictureBox1.Image"))); this->pictureBox1->Location = System::Drawing::Point(24, 56); this->pictureBox1->Name = S"pictureBox1"; this->pictureBox1->Size = System::Drawing::Size(64, 72); this->pictureBox1->TabIndex = 7; this->pictureBox1->TabStop = false; // // button1 // this->button1->Font = new System::Drawing::Font(S"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, (System::Byte)0); this->button1->Location = System::Drawing::Point(288, 224); this->button1->Name = S"button1"; this->button1->Size = System::Drawing::Size(72, 32); this->button1->TabIndex = 4; this->button1->Text = S"OK"; this->button1->Click += new System::EventHandler(this, button1_Click); // // button2 // this->button2->Font = new System::Drawing::Font(S"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, (System::Byte)0); this->button2->Location = System::Drawing::Point(392, 224); this->button2->Name = S"button2"; this->button2->Size = System::Drawing::Size(72, 32); this->button2->TabIndex = 5; this->button2->Text = S"Cancel"; this->button2->Click += new System::EventHandler(this, button2_Click); // // loginError // this->loginError->ContainerControl = this; // // checkBox1 // this->checkBox1->Location = System::Drawing::Point(48, 200); this->checkBox1->Name = S"checkBox1"; this->checkBox1->Size = System::Drawing::Size(152, 24); this->checkBox1->TabIndex = 8; this->checkBox1->Text = S"login without pop3"; // // loginForm // this->AcceptButton = this->button1; this->AutoScaleBaseSize = System::Drawing::Size(5, 13); this->ClientSize = System::Drawing::Size(482, 272); this->ControlBox = false; this->Controls->Add(this->checkBox1); this->Controls->Add(this->button2); this->Controls->Add(this->button1); this->Controls->Add(this->pictureBox1); this->Controls->Add(this->passwordTextBox); this->Controls->Add(this->usernameTextBox); this->Controls->Add(this->serverTextBox); this->Controls->Add(this->label4); this->Controls->Add(this->label3); this->Controls->Add(this->label2); this->Controls->Add(this->label1); this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::FixedDialog; this->Name = S"loginForm"; this->ShowInTaskbar = false; this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen; this->Text = S"Please Sign in"; this->TopMost = true; this->ResumeLayout(false); } private: System::Void button2_Click(System::Object * sender, System::EventArgs * e) { exit(0); } private: System::Void button1_Click(System::Object * sender, System::EventArgs * e) { String* server = S""; String* smtpServer = S""; String* pop3Server = S""; String* username = S""; String* password = S""; String* serverMessage = S""; Char delimStr = '.'; int index; if(this->checkBox1->Checked) { pop3enabled = false; if(this->serverTextBox->get_Text()->Equals(S"")) { loginError->SetIconAlignment(this->serverTextBox,ErrorIconAlignment::MiddleLeft); loginError->SetError(this->usernameTextBox,S"You must at least specify a server address"); } else { server = this->serverTextBox->get_Text(); index = server->IndexOf(delimStr); server = server->Remove(0,index); smtpServer = System::String::Concat("mail",server); setSmtpServerAddress(smtpServer,25); this->Hide(); } } else { server = this->serverTextBox->get_Text(); username = this->usernameTextBox->get_Text(); password = this->passwordTextBox->get_Text(); index = server->IndexOf(delimStr); server = server->Remove(0,index); smtpServer = System::String::Concat("mail",server); pop3Server = System::String::Concat("pop3",server); setSmtpServerAddress(smtpServer,25); setPop3ServerAddress(pop3Server,110); setUserInfo(username,password); bool connected = processServerMessage(loginToPop3Server()); if(connected) this->Hide(); else { loginError->SetIconAlignment(this->usernameTextBox,ErrorIconAlignment::MiddleLeft); loginError->SetError(this->usernameTextBox,S"ERROR: \n\nIncorrect username and or password, please try again"); this->usernameTextBox->Text = ""; this->passwordTextBox->Text = ""; } } } bool processServerMessage(String* message) { if(message->StartsWith(S"+OK")) return true; else return false; } public: bool getpop3enabled() { return pop3enabled; } }; }
[ [ [ 1, 297 ] ] ]
a7d2071aa7c6390e173b44e92026dfdd8fbd4d97
b0f91e945e4a3be58548385c3f6e3fa702a2b6ef
/ACE/ENTROPIA/entropia.cpp
57f0ad06f855a033558311c7a41fffb713b7ce72
[]
no_license
ismafc/fisicacomputacionaluned
11f651a2953f6ba427e32e62585383f0653ef293
e3ea421a9b5c294766d4ce7cf58dc8925cac5cf3
refs/heads/master
2020-05-17T10:17:59.294210
2011-07-19T08:33:34
2011-07-19T08:33:34
35,503,402
0
0
null
null
null
null
ISO-8859-1
C++
false
false
5,956
cpp
#include "libguardaimagen.h" #include "libACE.h" #pragma warning ( disable: 4996 ) // Evita los warnings del compilador de funciones obsoletas #define REGLA 54 // regla a aplicar por defecto #define PASOS 20 // número de pasos de evolución por defecto #define TODAS_LAS_REGLAS -1 // valor de regla que indica que hay que calcular todas las reglas #define MAX_REGLAS 256 // Número máximo de reglas a calcular #define MIN_PASOS 1 // como mínimo 1 paso de evolución #define MAX_PASOS 5000 // como máximo 5000 pasos de evolución #define N_MIN 3 // En evoluciones por número de celdas, valor mínimo #define N_MAX 20 // En evoluciones por número de celdas, valor máximo /* * Nombre: ENTROPIA (Estudio de la evolución de la entropia) * Autor: Ismael Flores Campoy * Descripción: Genera información a propósito de la evolución de autómatas celulares elementales * según el número de celdas. Se analiza la evolución del valor estacionario de la entropía y * la evolución del porcentaje final de estados no visitados, ambas en función del número de celdas del ACE. * Sintaxis: ACE <opcion1>:<valor1> <opcion2>:<valor2> ... * * Opción | Valores (separados por comas) | Valor por defecto * ------------------------------------------------------------------------------------------------------- * regla | [0, 255], todas | REGLA (54) * pasos | [1, 5000] | PASOS (500) * * Argumento | Significado * ------------------------------------------------------------------------------------------------------------ * regla:todas | Se calculan los ACEs (y se guardan en ficheros) de todas las reglas [0, 255] * regla:4 | Se calcula el ACE (y se guarda en ficheros) de la regla 4 * regla:4,90,126 | Se calcula el ACE (y se guarda en ficheros) de laS reglas 4, 90 y 126 * pasos:300 | Se calculan 300 pasos de la evolución del ACE * * Ejemplos: * * ENTROPIA regla:126,90 * ENTROPIA regla:todas * ENTROPIA regla:4 pasos:200 * */ int main(int argc, char** argv) { int pasos = PASOS; // Pasos de evolución a simular (por defecto PASOS) int** ACE; // Donde guardamos el estado del autómata [PASOS + 1][CELDAS + 2] int reglas[256]; // Guardamos las reglas a aplicar int nreglas; // Guardamos el número de reglas a aplicar char nombreFichero[256]; // Guardamos los nombres de los ficheros a crear double* noVisitados; // Guardamos los porcentajes finales de estados no visitados double* entropias; // Guardamos los valores estacionario de las entropías // Por defecto aplicaremos la regla REGLA si como argumento no indicamos otra cosa reglas[0] = REGLA; nreglas = 1; // Procesado de los parámetros de entrada (si existen) for (int a = 1; a < argc; a++) { if (strstr(argv[a], "reglas:") == argv[a]) { // Si encontramos un argumento 'regla:' analizamos que valor tiene. if (strstr(argv[a], ":todas") != NULL) nreglas = obtenerValores(reglas, MAX_REGLAS, "0-255"); else nreglas = obtenerValores(reglas, MAX_REGLAS, argv[a] + strlen("reglas:")); } else if (strstr(argv[a], "pasos:") == argv[a]) { // Si encontramos un argumento 'pasos:' analizamos que valor tiene. pasos = atoi(argv[a] + strlen("pasos:")); if (pasos < MIN_PASOS || pasos > MAX_PASOS || errno != 0) { pasos = PASOS; printf("Parámetro incorrecto, se esperaba un número de pasos entre %d y %d... Se asumen %d pasos\n", MIN_PASOS, MAX_PASOS, pasos); } } } // Asignamos memoria para los datos de los cálculos noVisitados = new double [N_MAX - N_MIN + 1]; entropias = new double [N_MAX - N_MIN + 1]; // Hacemos los cálculos para cada regla indicada for (int nr = 0; nr < nreglas; nr++) { // Para cada regla, hacemos los cáculos para ACEs con números de celdas que van de N_MIN a N_MAX for (int N = N_MIN; N <= N_MAX; N++) { // Estados posibles para ese tipo de ACE con ese número de celdas int estadosPosibles = (int)pow(2.0, N); // Inicializamos las variables necesarias para los cálculos int visitadosPaso = 0; int* probabilidades = new int [estadosPosibles]; memset(probabilidades, 0, estadosPosibles * sizeof(int)); int* base = new int [N + 2]; asignarMemoriaACE(&ACE, pasos, N); // Recorremos todos los estados posibles para el número de celdas dado for (int estado = 0; estado < estadosPosibles; estado++) { generarEstadoInicial(base, estado, N); inicializarACE(ACE, N, INICIALIZACION_FIJA, base); long* estados = generarACE(ACE, reglas[nr], pasos, N); // Actualizamos las veces que cada estado es visitado en el último paso probabilidades[estados[pasos - 1]]++; // Actualizamos el número de estados diferentes visitados en el último paso if (probabilidades[estados[pasos - 1]] == 1) visitadosPaso++; // Eliminamos la lista de estados visitados delete[] estados; } // Calculamos el porcentaje de estados no visitados y la entropía (ambos en el paso final) noVisitados[N - N_MIN] = (double)(estadosPosibles - visitadosPaso) / (double)estadosPosibles; entropias[N - N_MIN] = entropia(probabilidades, N); // Liberamos la memoria no necesaria liberarMemoriaACE(ACE, pasos); delete[] base; delete[] probabilidades; } // Guardamos los datos calculados sprintf(nombreFichero, "NOVISITADOS_R%03d_P%05d.dat", reglas[nr], pasos); guardaPLOT(nombreFichero, noVisitados, N_MAX - N_MIN + 1, N_MIN, 5); sprintf(nombreFichero, "ENTROPIA_R%03d_P%05d.dat", reglas[nr], pasos); guardaPLOT(nombreFichero, entropias, N_MAX - N_MIN + 1, N_MIN); } // Liberamos la memoria necesaria para guardar los datos finales delete[] noVisitados; delete[] entropias; }
[ "[email protected]@654a2211-555d-b977-7330-fc5d5f669db8" ]
[ [ [ 1, 138 ] ] ]
a29d706f288b1c66c94faa85a0540257f889d143
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit2/WebProcess/Plugins/Plugin.h
f694ff0cf0db820385c548781430771cd3fe2115
[]
no_license
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,564
h
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. */ #ifndef Plugin_h #define Plugin_h #include <WebCore/GraphicsLayer.h> #include <WebCore/KURL.h> #include <wtf/RefCounted.h> #include <wtf/Vector.h> struct NPObject; namespace WebCore { class GraphicsContext; class IntRect; } namespace WebKit { class WebMouseEvent; class WebWheelEvent; class PluginController; class Plugin : public RefCounted<Plugin> { public: struct Parameters { WebCore::KURL url; Vector<WTF::String> names; Vector<WTF::String> values; WTF::String mimeType; bool loadManually; }; virtual ~Plugin(); // Initializes the plug-in. If the plug-in fails to initialize this should return false. virtual bool initialize(PluginController*, const Parameters&) = 0; // Destroys the plug-in. virtual void destroy() = 0; // Tells the plug-in to paint itself into the given graphics context. The passed-in context and // dirty rect are in window coordinates. The context is saved/restored by the caller. virtual void paint(WebCore::GraphicsContext*, const WebCore::IntRect& dirtyRect) = 0; #if PLATFORM(MAC) // If a plug-in is using the Core Animation drawing model, this returns its plug-in layer. virtual PlatformLayer* pluginLayer() = 0; #endif // Tells the plug-in that either the plug-ins frame rect or its clip rect has changed. Both rects are in window coordinates. virtual void geometryDidChange(const WebCore::IntRect& frameRect, const WebCore::IntRect& clipRect) = 0; // Tells the plug-in that a frame load request that the plug-in made by calling PluginController::loadURL has finished. virtual void frameDidFinishLoading(uint64_t requestID) = 0; // Tells the plug-in that a frame load request that the plug-in made by calling PluginController::loadURL has failed. virtual void frameDidFail(uint64_t requestID, bool wasCancelled) = 0; // Tells the plug-in that a request to evaluate JavaScript (using PluginController::loadURL) has been fulfilled and passes // back the result. If evaluating the script failed, result will be null. virtual void didEvaluateJavaScript(uint64_t requestID, const WTF::String& requestURLString, const WTF::String& result) = 0; // Tells the plug-in that a stream has received its HTTP response. virtual void streamDidReceiveResponse(uint64_t streamID, const WebCore::KURL& responseURL, uint32_t streamLength, uint32_t lastModifiedTime, const WTF::String& mimeType, const WTF::String& headers) = 0; // Tells the plug-in that a stream did receive data. virtual void streamDidReceiveData(uint64_t streamID, const char* bytes, int length) = 0; // Tells the plug-in that a stream has finished loading. virtual void streamDidFinishLoading(uint64_t streamID) = 0; // Tells the plug-in that a stream has failed to load, either because of network errors or because the load was cancelled. virtual void streamDidFail(uint64_t streamID, bool wasCancelled) = 0; // Tells the plug-in that the manual stream has received its HTTP response. virtual void manualStreamDidReceiveResponse(const WebCore::KURL& responseURL, uint32_t streamLength, uint32_t lastModifiedTime, const WTF::String& mimeType, const WTF::String& headers) = 0; // Tells the plug-in that the manual stream did receive data. virtual void manualStreamDidReceiveData(const char* bytes, int length) = 0; // Tells the plug-in that a stream has finished loading. virtual void manualStreamDidFinishLoading() = 0; // Tells the plug-in that a stream has failed to load, either because of network errors or because the load was cancelled. virtual void manualStreamDidFail(bool wasCancelled) = 0; // Tells the plug-in to handle the passed in mouse event. The plug-in should return true if it processed the event. virtual bool handleMouseEvent(const WebMouseEvent&) = 0; // Tells the plug-in to handle the passed in wheel event. The plug-in should return true if it processed the event. virtual bool handleWheelEvent(const WebWheelEvent&) = 0; // Tells the plug-in to handle the passed in mouse over event. The plug-in should return true if it processed the event. virtual bool handleMouseEnterEvent(const WebMouseEvent&) = 0; // Tells the plug-in to handle the passed in mouse leave event. The plug-in should return true if it processed the event. virtual bool handleMouseLeaveEvent(const WebMouseEvent&) = 0; // Tells the focus about focus changes. virtual void setFocus(bool) = 0; // Get the NPObject that corresponds to the plug-in's scriptable object. Returns a retained object. virtual NPObject* pluginScriptableNPObject() = 0; // Returns the plug-in controller for this plug-in. // FIXME: We could just have the controller be a member variable of Plugin. virtual PluginController* controller() = 0; protected: Plugin(); }; } // namespace WebKit #endif // Plugin_h
[ [ [ 1, 142 ] ] ]
25dc5c3c28469df8a355a3bf432e87b816381b50
6e4f9952ef7a3a47330a707aa993247afde65597
/PROJECTS_ROOT/WireChanger/WCHtmlViewer/Idispimp.cpp
c8b2379bc12ab0033fc1ac3b716cfcedc35fb5f8
[]
no_license
meiercn/wiredplane-wintools
b35422570e2c4b486c3aa6e73200ea7035e9b232
134db644e4271079d631776cffcedc51b5456442
refs/heads/master
2021-01-19T07:50:42.622687
2009-07-07T03:34:11
2009-07-07T03:34:11
34,017,037
2
1
null
null
null
null
UTF-8
C++
false
false
3,464
cpp
/* * idispimp.CPP * IDispatch for Extending Dynamic HTML Object Model * * Copyright (c)1995-1999 Microsoft Corporation, All Rights Reserved */ #include "stdafx.h" #include "idispimp.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // Hardcoded information for extending the Object Model // Typically this would be supplied through a TypeInfo // In this case the name "xxyyzz" maps to DISPID_Extend const WCHAR pszExtend[10]=L"xxyyzz"; #define DISPID_Extend 12345 /* * CImpIDispatch::CImpIDispatch * CImpIDispatch::~CImpIDispatch * * Parameters (Constructor): * pSite PCSite of the site we're in. * pUnkOuter LPUNKNOWN to which we delegate. */ CImpIDispatch::CImpIDispatch( void ) { m_cRef = 0; } CImpIDispatch::~CImpIDispatch( void ) { ASSERT( m_cRef == 0 ); } /* * CImpIDispatch::QueryInterface * CImpIDispatch::AddRef * CImpIDispatch::Release * * Purpose: * IUnknown members for CImpIDispatch object. */ STDMETHODIMP CImpIDispatch::QueryInterface( REFIID riid, void **ppv ) { *ppv = NULL; if ( IID_IDispatch == riid ) { *ppv = this; } if ( NULL != *ppv ) { ((LPUNKNOWN)*ppv)->AddRef(); return NOERROR; } return E_NOINTERFACE; } STDMETHODIMP_(ULONG) CImpIDispatch::AddRef(void) { return ++m_cRef; } STDMETHODIMP_(ULONG) CImpIDispatch::Release(void) { return --m_cRef; } //IDispatch STDMETHODIMP CImpIDispatch::GetTypeInfoCount(UINT* /*pctinfo*/) { return E_NOTIMPL; } STDMETHODIMP CImpIDispatch::GetTypeInfo(/* [in] */ UINT /*iTInfo*/, /* [in] */ LCID /*lcid*/, /* [out] */ ITypeInfo** /*ppTInfo*/) { return E_NOTIMPL; } STDMETHODIMP CImpIDispatch::GetIDsOfNames( /* [in] */ REFIID riid, /* [size_is][in] */ OLECHAR** rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID* rgDispId) { HRESULT hr; UINT i; // Assume some degree of success hr = NOERROR; // Hardcoded mapping for this sample // A more usual procedure would be to use a TypeInfo for ( i=0; i < cNames; i++) { if ( 2 == CompareString( lcid, NORM_IGNOREWIDTH, (char*)pszExtend, 3, (char*)rgszNames[i], 3 ) ) { rgDispId[i] = DISPID_Extend; } else { // One or more are unknown so set the return code accordingly hr = ResultFromScode(DISP_E_UNKNOWNNAME); rgDispId[i] = DISPID_UNKNOWN; } } return hr; } STDMETHODIMP CImpIDispatch::Invoke( /* [in] */ DISPID dispIdMember, /* [in] */ REFIID /*riid*/, /* [in] */ LCID /*lcid*/, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS* pDispParams, /* [out] */ VARIANT* pVarResult, /* [out] */ EXCEPINFO* /*pExcepInfo*/, /* [out] */ UINT* puArgErr) { // For this sample we only support a Property Get on DISPID_Extend // returning a BSTR with "Wibble" as the value if ( dispIdMember == DISPID_Extend ) { if ( wFlags & DISPATCH_PROPERTYGET ) { if ( pVarResult != NULL ) { WCHAR buff[10]=L"Wibble"; BSTR bstrRet = SysAllocString( buff ); VariantInit(pVarResult); V_VT(pVarResult)=VT_BSTR; V_BSTR(pVarResult) = bstrRet; } } } return S_OK; }
[ "wplabs@3fb49600-69e0-11de-a8c1-9da277d31688" ]
[ [ [ 1, 159 ] ] ]
8b528724a202580e2312ffb2dc54a46ce72e249c
9cc347d44d6465eb6c7f03fadc6c0652cfb572cb
/kod/SVM-Face_Recognition/Greska.cpp
ea9ce0c43229d732efebecb1191a1ec0d29f2f87
[]
no_license
PetaPowerGroup/pattern-recognition-lab
0979ae29de4d1645d6fcec5a35cfa4a133bfd9cb
dd9d1fb042a23ef3de9d6ec43a55bdcf84523c7b
refs/heads/master
2016-08-07T01:05:11.347524
2010-01-19T10:12:32
2010-01-19T10:12:32
7,590,036
0
1
null
null
null
null
UTF-8
C++
false
false
755
cpp
#include "Greska.h" #include <iostream> #include <fstream> #include <string> #include <time.h> using namespace std; Greska::Greska(char* poruka) { strcpy(porukaGreske,poruka); } void Greska::ispisGreske() { cout<<porukaGreske<<endl; } void Greska::ispisGreske(streamEnum stream) { if (stream == Greska::KONZOLA) { cout<<porukaGreske<<endl; } else { ofstream datoteka; datoteka.open("errorlog.txt",ios::out | ios::app); if (!datoteka.is_open()) { cout<<"GRESKA: Provjera pristupa\n\tDatoteka \"errorlog.txt\" nije otvorena."<<endl; } else { time_t vrijeme; time (&vrijeme); datoteka<<asctime(localtime(&vrijeme))<<" "<<porukaGreske<<endl; } datoteka.close(); } }
[ "" ]
[ [ [ 1, 45 ] ] ]
203d7ed16824fcd2063f253e6df6aa288dee3bdf
57d74ff818cabf449d3ad457bcc54c5d78550352
/8.0/SpiraTestCompletePlugIn/atlsiface.h
8ff4ba9dc0b52722e843167b00e79de7e52f619d
[]
no_license
Inflectra/spira-testing-test-complete
f6e28f558b97689331ee2107501eb121341aabdb
9bcf5d3286dd3bba492bc432511be193becca547
refs/heads/main
2023-04-09T07:14:02.796898
2010-08-05T17:39:00
2010-08-05T17:39:00
359,174,921
0
0
null
null
null
null
UTF-8
C++
false
false
23,641
h
// This is a part of the Active Template Library. // Copyright (C) Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Active Template Library Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Active Template Library product. #ifndef __ATLSIFACE_H__ #define __ATLSIFACE_H__ #pragma once #include <atlcoll.h> #include <httpext.h> #include "atlserr.h" #include <atlcom.h> #include <string.h> #include <atlpath.h> #pragma pack(push,_ATL_PACKING) namespace ATL{ // Forward declarations of custom data types used in // interfaces declared in this file. struct AtlServerRequest; class CIsapiWorker; __interface IAtlMemMgr; class CCookie; // Forward declarations of all interfaces declared in this file. __interface IWriteStream; __interface IHttpFile; __interface IHttpServerContext; __interface IHttpRequestLookup; __interface IRequestHandler; __interface ITagReplacer; __interface IIsapiExtension; __interface IPageCacheControl; __interface IRequestStats; __interface IBrowserCaps; __interface IBrowserCapsSvc; // ATLS Interface declarations. // IWriteStream // Interface for writing to a stream. __interface IWriteStream { HRESULT WriteStream(LPCSTR szOut, int nLen, DWORD *pdwWritten); HRESULT FlushStream(); }; // IHttpFile // This is an interface that provides for basic accessor // functionality for files (see CHttpRequestFile). __interface IHttpFile { LPCSTR GetParamName(); LPCSTR GetFileName(); LPCSTR GetFullFileName(); LPCSTR GetContentType(); LPCSTR GetTempFileName(); ULONGLONG GetFileSize(); void Free(); }; // IHttpServerContext // This interface encapsulates the capabilities of the web server and provides information about // the current request being handled. See CServerContext for implementation. __interface ATL_NO_VTABLE __declspec(uuid("813F3F00-3881-11d3-977B-00C04F8EE25E")) IHttpServerContext : public IUnknown { HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv); ULONG STDMETHODCALLTYPE AddRef(); ULONG STDMETHODCALLTYPE Release(); LPCSTR GetRequestMethod(); LPCSTR GetQueryString(); LPCSTR GetPathInfo(); LPCSTR GetPathTranslated(); LPCSTR GetScriptPathTranslated(); DWORD GetTotalBytes(); DWORD GetAvailableBytes(); BYTE *GetAvailableData(); LPCSTR GetContentType(); BOOL GetServerVariable(__in_z LPCSTR pszVariableName, __out_ecount_part_opt(*pdwSize, *pdwSize) LPSTR pvBuffer, __inout DWORD *pdwSize); BOOL GetImpersonationToken(HANDLE * pToken); BOOL WriteClient(void *pvBuffer, DWORD *pdwBytes); BOOL AsyncWriteClient(void *pvBuffer, DWORD *pdwBytes); BOOL ReadClient(void *pvBuffer, DWORD *pdwSize); BOOL AsyncReadClient(void *pvBuffer, DWORD *pdwSize); BOOL SendRedirectResponse(LPCSTR pszRedirectUrl); BOOL SendResponseHeader(LPCSTR pszHeader, LPCSTR pszStatusCode, BOOL fKeepConn); BOOL DoneWithSession(DWORD dwHttpStatusCode); BOOL RequestIOCompletion(PFN_HSE_IO_COMPLETION pfn, DWORD *pdwContext); BOOL TransmitFile(HANDLE hFile, PFN_HSE_IO_COMPLETION pfn, void *pContext, LPCSTR szStatusCode, DWORD dwBytesToWrite, DWORD dwOffset, void *pvHead, DWORD dwHeadLen, void *pvTail, DWORD dwTailLen, DWORD dwFlags); BOOL AppendToLog(LPCSTR szMessage, DWORD* pdwLen); BOOL MapUrlToPathEx(LPCSTR szLogicalPath, DWORD dwLen, HSE_URL_MAPEX_INFO *pumInfo); }; // IHttpRequestLookup // This interface is designed to allow one map to chain to another map. // The interface is implemented by the CHttpThunkMap and CHttpRequest classes. // Pointers to this interface are passed around by CRequestHandlerT and CHtmlTagReplacer. // dwType - the type of item being requested __interface ATL_NO_VTABLE __declspec(uuid("A5990B44-FF74-4bfe-B66D-F9E7E9F42D42")) IHttpRequestLookup : public IUnknown { POSITION GetFirstQueryParam(LPCSTR *ppszName, LPCSTR *ppszValue); POSITION GetNextQueryParam(POSITION pos, LPCSTR *ppszName, LPCSTR *ppszValue); POSITION GetFirstFormVar(LPCSTR *ppszName, LPCSTR *ppszValue); POSITION GetNextFormVar(POSITION pos, LPCSTR *ppszName, LPCSTR *ppszValue); POSITION GetFirstFile(LPCSTR *ppszName, IHttpFile **ppFile); POSITION GetNextFile(POSITION pos, LPCSTR *ppszName, IHttpFile **ppFile); HRESULT GetServerContext(IHttpServerContext **ppOut); }; // IRequestHandler // This interface is impelemented by clients who want to be request handlers in an // atl server application. Server default implementations are provided in ATL, including // IRequestHandlerImpl (atlisapi.h) and CRequestHandlerT (atlstencil.h) __interface ATL_NO_VTABLE __declspec(uuid("D57F8D0C-751A-4223-92BC-0B29F65D2453")) IRequestHandler : public IUnknown { HTTP_CODE GetFlags(DWORD *pdwStatus); HTTP_CODE InitializeHandler(AtlServerRequest *pRequestInfo, IServiceProvider *pProvider); HTTP_CODE InitializeChild(AtlServerRequest *pRequestInfo, IServiceProvider *pProvider, IHttpRequestLookup *pLookup); HTTP_CODE HandleRequest(AtlServerRequest *pRequestInfo, IServiceProvider *pProvider); void UninitializeHandler(); }; // ITagReplacer // This interface defines the methods necessary for server response file processing. __interface ATL_NO_VTABLE __declspec(uuid("8FF5E90C-8CE0-43aa-96C4-3BF930837512")) ITagReplacer : public IUnknown { HTTP_CODE FindReplacementOffset(LPCSTR szMethodName, DWORD *pdwMethodOffset, LPCSTR szObjectName, DWORD *pdwObjOffset, DWORD *pdwMap, void **ppvParam, IAtlMemMgr *pMemMgr); HTTP_CODE RenderReplacement(DWORD dwFnOffset, DWORD dwObjOffset, DWORD dwMap, void *pvParam); HRESULT GetContext(REFIID riid, void** ppv); IWriteStream *SetStream(IWriteStream *pStream); }; struct CStencilState; // IIsapiExtension // Tnis is the interface to the ISAPI extension of a running ATL Server web // application. Provides request handler clients with access to functions of the // ISAPI server. __interface __declspec(uuid("79DD4A27-D820-4fa6-954D-E1DFC2C05978")) IIsapiExtension : public IUnknown { BOOL DispatchStencilCall(AtlServerRequest *pRequestInfo); void RequestComplete(AtlServerRequest *pRequestInfo, DWORD hStatus, DWORD dwSubStatus); BOOL OnThreadAttach(); void OnThreadTerminate(); BOOL QueueRequest(AtlServerRequest *pRequestInfo); CIsapiWorker *GetThreadWorker(); BOOL SetThreadWorker(CIsapiWorker *pWorker); HTTP_CODE LoadRequestHandler(LPCSTR szDllPath, LPCSTR szHandlerName, IHttpServerContext *pServerContext, HINSTANCE *phInstance, IRequestHandler **ppHandler); HRESULT AddService(REFGUID guidService, REFIID riid, IUnknown *punk, HINSTANCE hInstance); HRESULT RemoveService(REFGUID guidService, REFIID riid); HTTP_CODE LoadDispatchFile(LPCSTR szFileName, AtlServerRequest *pRequestInfo); AtlServerRequest* CreateRequest(); void FreeRequest(AtlServerRequest* pRequest); HTTP_CODE TransferRequest( AtlServerRequest *pRequest, IServiceProvider *pServiceProvider, IWriteStream *pWriteStream, IHttpRequestLookup *pLookup, LPCSTR szNewUrl, WORD nCodePage, bool bContinueAfterProcess, CStencilState *pState); }; // IPageCacheControl // This interface controls the cacheability of the current page __interface ATL_NO_VTABLE __declspec(uuid("9868BFC0-D44D-4154-931C-D186EC0C45D5")) IPageCacheControl : public IUnknown { HRESULT GetExpiration(FILETIME *pftExpiration); HRESULT SetExpiration(FILETIME ftExpiration); BOOL IsCached(); BOOL Cache(BOOL bCache); }; // IRequestStats // Used to query request statistics from a running ATL server ISAPI application. __interface ATL_NO_VTABLE __declspec(uuid("2B75C68D-0DDF-48d6-B58A-CC7C2387A6F2")) IRequestStats : public IUnknown { long GetTotalRequests(); long GetFailedRequests(); long GetAvgResponseTime(); long GetCurrWaiting(); long GetMaxWaiting(); long GetActiveThreads(); }; // IBrowserCaps // Interface that provides information about a particular web brorwser. // See atlutil.h and the ATL Browser Capabilities service for information // about this interface's implementation __interface __declspec(uuid("3339FCE2-99BC-4985-A702-4ABC8304A995")) IBrowserCaps : public IUnknown { HRESULT GetPropertyString(BSTR bstrProperty, BSTR * pbstrOut); HRESULT GetBooleanPropertyValue(BSTR bstrProperty, BOOL* pbOut); HRESULT GetBrowserName(BSTR * pbstrName); HRESULT GetPlatform(BSTR * pbstrPlatform); HRESULT GetVersion(BSTR * pbstrVersion); HRESULT GetMajorVer(BSTR * pbstrMajorVer); HRESULT GetMinorVer(BSTR * pbstrMinorVer); HRESULT SupportsFrames(BOOL* pbFrames); HRESULT SupportsTables(BOOL* pbTables); HRESULT SupportsCookies(BOOL* pbCookies); HRESULT SupportsBackgroundSounds(BOOL* pbBackgroundSounds); HRESULT SupportsVBScript(BOOL* pbVBScript); HRESULT SupportsJavaScript(BOOL* pbJavaScript); HRESULT SupportsJavaApplets(BOOL* pbJavaApplets); HRESULT SupportsActiveXControls(BOOL* pbActiveXControls); HRESULT SupportsCDF(BOOL* pbCDF); HRESULT SupportsAuthenticodeUpdate(BOOL* pbAuthenticodeUpdate); HRESULT IsBeta(BOOL* pbIsBeta); HRESULT IsCrawler(BOOL* pbIsCrawler); HRESULT IsAOL(BOOL* pbIsAOL); HRESULT IsWin16(BOOL* pbIsWin16); HRESULT IsAK(BOOL* pbIsAK); HRESULT IsSK(BOOL* pbIsSK); HRESULT IsUpdate(BOOL* pbIsUpdate); }; // IBrowserCapsSvc. // Interface on the browser caps service. Used by clients to query a running // instance of the browser capabilities service for information about a user's web // browser. See atlutil.h for implementation of the browser capabilities services. __interface __declspec(uuid("391E7418-863B-430e-81BB-1312ED2FF3E9")) IBrowserCapsSvc : public IUnknown { HRESULT GetCaps(IHttpServerContext * pContext, IBrowserCaps ** ppOut); HRESULT GetCapsUserAgent(BSTR bstrAgent, IBrowserCaps ** ppOut); }; class CBrowserCapsSvc : public IBrowserCapsSvc, public CComObjectRootEx<CComSingleThreadModel> { public: virtual ~CBrowserCapsSvc() { } BEGIN_COM_MAP(CBrowserCapsSvc) COM_INTERFACE_ENTRY(IBrowserCapsSvc) END_COM_MAP() __success(SUCCEEDED(return)) __checkReturn HRESULT GetCaps(__in IHttpServerContext * pContext, __deref_out_opt IBrowserCaps ** ppOut) { if (!pContext) return E_POINTER; if (!ppOut) return E_POINTER; *ppOut = NULL; char szUserAgent[256]; DWORD dwSize = sizeof(szUserAgent); if (!pContext->GetServerVariable("HTTP_USER_AGENT", szUserAgent, &dwSize)) return E_FAIL; return GetCapsUserAgent(CComBSTR(szUserAgent), ppOut); } __success(SUCCEEDED(return)) __checkReturn HRESULT GetCapsUserAgent(__in BSTR bstrAgent, __deref_out IBrowserCaps ** ppOut) { if (::SysStringLen(bstrAgent) == 0 || ppOut == NULL) { return E_POINTER; } *ppOut = NULL; BrowserCaps* pCaps = NULL; _ATLTRY { CW2CT szUserAgent(bstrAgent); if (!m_mapAgent.Lookup(szUserAgent, pCaps)) { pCaps = NULL; for (size_t i=0; i<m_caps.GetCount(); i++) { BrowserCaps& caps = m_caps[i]; if (IsEqualAgentString(caps.m_strUserAgent, szUserAgent)) { pCaps = &caps; break; } } } } _ATLCATCHALL() { return E_FAIL; } #pragma warning(push) #pragma warning(disable: 6014) if (pCaps != NULL) { CComObjectNoLock<CBrowserCaps> *pRet = NULL; ATLTRY(pRet = new CComObjectNoLock<CBrowserCaps>); if (!pRet) return E_OUTOFMEMORY; pRet->AddRef(); HRESULT hr = pRet->Initialize(pCaps); if (FAILED(hr)) { pRet->Release(); return hr; } *ppOut = pRet; return S_OK; } #pragma warning(pop) return E_FAIL; } __checkReturn HRESULT Initialize(__in HINSTANCE hInstance) throw() { // tries loading browscap.ini from the same directory as the module if (hInstance != NULL) { _ATLTRY { CPath strBrowscapPath; LPTSTR sz = strBrowscapPath.m_strPath.GetBuffer(MAX_PATH); UINT nChars = ::GetModuleFileName(hInstance, sz, MAX_PATH); strBrowscapPath.m_strPath.ReleaseBuffer(nChars); if (nChars != 0 && nChars != MAX_PATH && strBrowscapPath.RemoveFileSpec()) { strBrowscapPath += _T("\\browscap.ini"); if (SUCCEEDED(Load(strBrowscapPath))) return S_OK; } } _ATLCATCHALL() { return E_FAIL; } } // falls back to the system browscap.ini if previous Load failed return Load(); } HRESULT Uninitialize() { Clear(); return S_OK; } private: static bool IsEqualAgentString(__in LPCTSTR szPattern, __in LPCTSTR szInput) { while (*szPattern && *szInput && (*szPattern == *szInput || *szPattern == '?')) { szPattern++; szInput++; } if (*szPattern == *szInput) { return true; } if (*szPattern == '*') { szPattern++; if (!*szPattern) { return true; } while(*szInput) { if (IsEqualAgentString(szPattern, szInput)) { return true; } szInput++; } } return false; } __checkReturn HRESULT Load(__in_opt LPCTSTR szPath = NULL) { _ATLTRY { Clear(); CString strBrowscapPath(szPath); // use default load path if a path isn't specified if (strBrowscapPath.IsEmpty()) { LPTSTR sz = strBrowscapPath.GetBuffer(MAX_PATH); UINT nChars = ::GetSystemDirectory(sz, MAX_PATH); strBrowscapPath.ReleaseBuffer(nChars); if (nChars == 0 || nChars == MAX_PATH) return E_FAIL; strBrowscapPath += _T("\\inetsrv\\browscap.ini"); } size_t nCurrent = 16384; CHeapPtr<TCHAR> data; if (!data.Allocate(nCurrent)) return E_OUTOFMEMORY; // load the list of all the user agents bool bRetrieved = false; do { DWORD dwRetrieved = ::GetPrivateProfileSectionNames(data, (DWORD) nCurrent, strBrowscapPath); if (dwRetrieved == 0) { return AtlHresultFromWin32(ERROR_FILE_NOT_FOUND); } else if (dwRetrieved < nCurrent-2) { bRetrieved = true; } else if(SIZE_MAX/2<nCurrent) { return E_OUTOFMEMORY; } else if (!data.Reallocate(nCurrent *= 2)) { return E_OUTOFMEMORY; } } while (!bRetrieved); // figure out how many user agents there are // and set them in the structure LPTSTR sz = data; int nSections = 0; while (*sz) { nSections++; sz += (lstrlen(sz)+1); } if (!m_caps.SetCount(nSections)) return E_OUTOFMEMORY; sz = data; nSections = 0; while (*sz) { BrowserCaps& caps = m_caps[nSections++]; caps.m_strUserAgent = sz; m_mapAgent[caps.m_strUserAgent] = &caps; sz += (caps.m_strUserAgent.GetLength()+1); } // for each user agent, load the properties for (size_t i=0; i<m_caps.GetCount(); i++) { bRetrieved = false; BrowserCaps& caps = m_caps[i]; caps.m_pParent = NULL; do { DWORD dwRetrieved = ::GetPrivateProfileSection(caps.m_strUserAgent, data, (DWORD) nCurrent, strBrowscapPath); if (dwRetrieved == 0) { return AtlHresultFromWin32(ERROR_FILE_NOT_FOUND); } else if (dwRetrieved < nCurrent-2) { bRetrieved = true; } else if(SIZE_MAX/2<nCurrent) { return E_OUTOFMEMORY; } else if (!data.Reallocate(nCurrent *= 2)) { return E_OUTOFMEMORY; } } while (!bRetrieved); sz = data; while (*sz) { CString str = sz; int nChar = str.Find('='); if (nChar != -1) { CString strPropName = str.Left(nChar); CString strPropVal = str.Mid(nChar+1); strPropName.Trim(); strPropVal.Trim(); caps.m_props.SetAt(strPropName, strPropVal); // if it's the parent property, set up the parent pointer if (strPropName.CompareNoCase(_T("parent")) == 0) { BrowserCaps* pParent = NULL; if (m_mapAgent.Lookup(strPropVal, pParent)) caps.m_pParent = pParent; } } sz += (str.GetLength()+1); } } } _ATLCATCHALL() { return E_FAIL; } return S_OK; } void Clear() { m_caps.RemoveAll(); m_mapAgent.RemoveAll(); } friend class CBrowserCaps; struct BrowserCaps { CString m_strUserAgent; // user agent string to match against (with wildcards) BrowserCaps* m_pParent; CAtlMap<CString, CString, CStringElementTraitsI<CString>, CStringElementTraits<CString> > m_props; }; // map from UserAgent string to caps // used for non-wildcard lookup and parent lookup CAtlMap<CString, BrowserCaps*, CStringElementTraits<CString> > m_mapAgent; // all of the caps CAtlArray<BrowserCaps> m_caps; class CBrowserCaps : public IBrowserCaps, public CComObjectRootEx<CComSingleThreadModel> { public: BEGIN_COM_MAP(CBrowserCaps) COM_INTERFACE_ENTRY(IBrowserCaps) END_COM_MAP() CBrowserCaps() { } HRESULT Initialize(__in CBrowserCapsSvc::BrowserCaps * pCaps) { m_pCaps = pCaps; return S_OK; } __checkReturn HRESULT GetPropertyString(__in BSTR bstrProperty, __out BSTR * pbstrOut) { _ATLTRY { ATLASSUME(m_pCaps); if (!m_pCaps) return E_UNEXPECTED; if (!pbstrOut) return E_POINTER; *pbstrOut = NULL; CString strName(bstrProperty); CString strVal; CBrowserCapsSvc::BrowserCaps * pCaps = m_pCaps; while (pCaps) { if (pCaps->m_props.Lookup(strName, strVal)) { CComBSTR bstrVal(strVal); *pbstrOut = bstrVal.Detach(); return S_OK; } pCaps = pCaps->m_pParent; } return S_FALSE; } _ATLCATCHALL() { return E_FAIL; } } __checkReturn HRESULT GetBooleanPropertyValue(__in BSTR bstrProperty, __out BOOL* pbOut) { if (!pbOut) return E_POINTER; CComBSTR bstrOut; HRESULT hr = GetPropertyString(bstrProperty, &bstrOut); if (FAILED(hr) || S_FALSE == hr) return hr; if (_wcsicmp(bstrOut, L"true") == 0) *pbOut = TRUE; else *pbOut = FALSE; return S_OK; } __checkReturn HRESULT GetBrowserName(__out BSTR * pbstrName) { return GetPropertyString(CComBSTR(L"browser"), pbstrName); } __checkReturn HRESULT GetPlatform(__out BSTR * pbstrPlatform) { return GetPropertyString(CComBSTR(L"platform"), pbstrPlatform); } __checkReturn HRESULT GetVersion(__out BSTR * pbstrVersion) { return GetPropertyString(CComBSTR(L"version"), pbstrVersion); } __checkReturn HRESULT GetMajorVer(__out BSTR * pbstrMajorVer) { return GetPropertyString(CComBSTR(L"majorver"), pbstrMajorVer); } __checkReturn HRESULT GetMinorVer(__out BSTR * pbstrMinorVer) { return GetPropertyString(CComBSTR(L"minorver"), pbstrMinorVer); } __checkReturn HRESULT SupportsFrames(__out BOOL* pbFrames) { return GetBooleanPropertyValue(CComBSTR(L"frames"), pbFrames); } __checkReturn HRESULT SupportsTables(__out BOOL* pbTables) { return GetBooleanPropertyValue(CComBSTR(L"tables"), pbTables); } __checkReturn HRESULT SupportsCookies(__out BOOL* pbCookies) { return GetBooleanPropertyValue(CComBSTR(L"cookies"), pbCookies); } __checkReturn HRESULT SupportsBackgroundSounds(__out BOOL* pbBackgroundSounds) { return GetBooleanPropertyValue(CComBSTR(L"backgroundsounds"), pbBackgroundSounds); } __checkReturn HRESULT SupportsVBScript(__out BOOL* pbVBScript) { return GetBooleanPropertyValue(CComBSTR(L"vbscript"), pbVBScript); } __checkReturn HRESULT SupportsJavaScript(__out BOOL* pbJavaScript) { return GetBooleanPropertyValue(CComBSTR(L"javascript"), pbJavaScript); } __checkReturn HRESULT SupportsJavaApplets(__out BOOL* pbJavaApplets) { return GetBooleanPropertyValue(CComBSTR(L"javaapplets"), pbJavaApplets); } __checkReturn HRESULT SupportsActiveXControls(__out BOOL* pbActiveXControls) { return GetBooleanPropertyValue(CComBSTR(L"ActiveXControls"), pbActiveXControls); } __checkReturn HRESULT SupportsCDF(__out BOOL* pbCDF) { return GetBooleanPropertyValue(CComBSTR(L"CDF"), pbCDF); } __checkReturn HRESULT SupportsAuthenticodeUpdate(__out BOOL* pbAuthenticodeUpdate) { return GetBooleanPropertyValue(CComBSTR(L"AuthenticodeUpdate"), pbAuthenticodeUpdate); } __checkReturn HRESULT IsBeta(__out BOOL* pbIsBeta) { return GetBooleanPropertyValue(CComBSTR(L"beta"), pbIsBeta); } __checkReturn HRESULT IsCrawler(__out BOOL* pbIsCrawler) { return GetBooleanPropertyValue(CComBSTR(L"Crawler"), pbIsCrawler); } __checkReturn HRESULT IsAOL(__out BOOL* pbIsAOL) { return GetBooleanPropertyValue(CComBSTR(L"AOL"), pbIsAOL); } __checkReturn HRESULT IsWin16(__out BOOL* pbIsWin16) { return GetBooleanPropertyValue(CComBSTR(L"Win16"), pbIsWin16); } __checkReturn HRESULT IsAK(__out BOOL* pbIsAK) { return GetBooleanPropertyValue(CComBSTR(L"AK"), pbIsAK); } __checkReturn HRESULT IsSK(__out BOOL* pbIsSK) { return GetBooleanPropertyValue(CComBSTR(L"SK"), pbIsSK); } __checkReturn HRESULT IsUpdate(__out BOOL* pbIsUpdate) { return GetBooleanPropertyValue(CComBSTR(L"Update"), pbIsUpdate); } private: CBrowserCapsSvc::BrowserCaps * m_pCaps; }; }; typedef DWORD_PTR HSESSIONENUM; // ISession // Interface on a single client session. Used to access variables in the client // session in the session state services. See atlsession.h for implementation of // this interface. __interface __declspec(uuid("DEB69BE3-7AC9-4a13-9519-266C1EA3AB39")) ISession : public IUnknown { STDMETHOD(SetVariable)(LPCSTR szName, VARIANT NewVal); STDMETHOD(GetVariable)(LPCSTR szName, VARIANT *pVal); STDMETHOD(GetCount)(long *pnCount); STDMETHOD(RemoveVariable)(LPCSTR szName); STDMETHOD(RemoveAllVariables)(); STDMETHOD(BeginVariableEnum)(POSITION *pPOS, HSESSIONENUM *phEnumHandle); STDMETHOD(GetNextVariable)(POSITION *pPOS, VARIANT *pVal, HSESSIONENUM hEnum, LPSTR szName, DWORD dwLen); STDMETHOD(CloseEnum)(HSESSIONENUM hEnumHandle); STDMETHOD(IsExpired)(); STDMETHOD(SetTimeout)(unsigned __int64 dwNewTimeout); }; //ISession // ISessionStateService // Interface on the session state service for an ISAPI application. Request // handler objects will use this interface to access user sessions. See // atlsession.h for implementation of this interface. __interface __declspec(uuid("C5740C4F-0C6D-4b43-92C4-2AF778F35DDE")) ISessionStateService : public IUnknown { STDMETHOD(CreateNewSession)(LPSTR szNewID, DWORD *pdwSize, ISession** ppSession); STDMETHOD(CreateNewSessionByName)(LPSTR szNewID, ISession** ppSession); STDMETHOD(GetSession)(LPCSTR szID, ISession **ppSession); STDMETHOD(CloseSession)(LPCSTR szID); }; // ISessionStateControl // Interface used by session state service to get information about the service. // Currently you can get the count of active sessions and the current default // timeout for a session. __interface __declspec(uuid("6C7F5F56-6CBD-49ee-9797-4C837D4C527A")) ISessionStateControl : public IUnknown { STDMETHOD(SetSessionTimeout)(unsigned __int64 nTimeout); STDMETHOD(GetSessionTimeout)(unsigned __int64 *pnTimeout); STDMETHOD(GetSessionCount)(DWORD *pnSessionCount); }; }; // namespace ATL #pragma pack(pop) #endif // __ATLSIFACE_H__
[ "asandman@5d4b435c-4d46-d949-aab2-e601ca53af14" ]
[ [ [ 1, 802 ] ] ]
b8bfe379dc941a6d36c6f098c4ec9113fd7b47dd
ea613c6a4d531be9b5d41ced98df1a91320c59cc
/FingerSuite/Common/AboutView.h
04a1704ca8577f9860d3645eb34f2f0625ac74d0
[]
no_license
f059074251/interested
939f938109853da83741ee03aca161bfa9ce0976
b5a26ad732f8ffdca64cbbadf9625dd35c9cdcb2
refs/heads/master
2021-01-15T14:49:45.217066
2010-09-16T10:42:30
2010-09-16T10:42:30
34,316,088
1
0
null
null
null
null
UTF-8
C++
false
false
3,609
h
// Test99View.h : interface of the CTest99View class // ///////////////////////////////////////////////////////////////////////////// #pragma once #ifndef __cplusplus #error ATL requires C++ compilation (use a .cpp suffix) #endif #ifndef __ATLMISC_H__ #error AboutView.h requires atlmisc.h to be included first #endif // Extracted from MFC 7.0 source code by Ma Weida BOOL AfxExtractSubString(CString& rString, LPCTSTR lpszFullString, int iSubString, TCHAR chSep) { if (lpszFullString == NULL) return FALSE; while (iSubString--) { lpszFullString = _tcschr(lpszFullString, chSep); if (lpszFullString == NULL) { rString.Empty(); // return empty string as well return FALSE; } lpszFullString++; // point past the separator } LPCTSTR lpchEnd = _tcschr(lpszFullString, chSep); int nLen = (lpchEnd == NULL) ? lstrlen(lpszFullString) : (int)(lpchEnd - lpszFullString); ATLASSERT(nLen >= 0); memcpy(rString.GetBufferSetLength(nLen), lpszFullString, nLen*sizeof(TCHAR)); return TRUE; } class CAboutView : public CWindowImpl<CAboutView> { public: DECLARE_WND_CLASS(NULL) BOOL PreTranslateMessage(MSG* pMsg) { pMsg; return FALSE; } void SetCredits(LPCTSTR lpszCredits) { m_strCredits = lpszCredits; } void SetBitmap(HBITMAP hBmp, int x, int y) { m_hBitmap = hBmp; m_ptPos.x = x; m_ptPos.y = y; } BEGIN_MSG_MAP(CAboutView) MESSAGE_HANDLER(WM_PAINT, OnPaint) END_MSG_MAP() // Handler prototypes (uncomment arguments if needed): // LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) // LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) // LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) LRESULT OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { CPaintDC dc(m_hWnd); RECT rc; GetClientRect(&rc); //TODO: Add your drawing code here CFont cOldFont; CFont cFontNormal = dc.GetCurrentFont(); LOGFONT lf; cFontNormal.GetLogFont(lf); lf.lfWeight = FW_BOLD; CFont cFontBold; cFontBold.CreateFontIndirect(&lf); lf.lfHeight -= 2; CFont cFontTitle; cFontTitle.CreateFontIndirect(&lf); dc.SetBkMode(TRANSPARENT); CString strSub; int nCount=0; // draw each line, based on specified type while(AfxExtractSubString(strSub, m_strCredits, nCount++, '\n')) { TCHAR nType = 0; if (!strSub.IsEmpty()) nType = strSub.GetAt(0); switch(nType) { case '\t': // title dc.SetTextColor(RGB(16,140,231)); cOldFont = dc.SelectFont(cFontTitle); strSub.TrimLeft('\t'); dc.DrawText(strSub, strSub.GetLength(), &rc, DT_TOP|DT_CENTER|DT_NOPREFIX | DT_SINGLELINE); dc.SelectFont(cOldFont); break; case '\r': // bold dc.SetTextColor(RGB(0,0,0)); cOldFont = dc.SelectFont(cFontBold); strSub.TrimLeft('\r'); dc.DrawText(strSub, strSub.GetLength(), &rc, DT_TOP|DT_CENTER|DT_NOPREFIX | DT_SINGLELINE); dc.SelectFont(cOldFont); break; default: // normal dc.SetTextColor(RGB(0,0,0)); cOldFont = dc.SelectFont(cFontNormal); dc.DrawText(strSub, strSub.GetLength(), &rc, DT_TOP|DT_CENTER|DT_NOPREFIX | DT_SINGLELINE); dc.SelectFont(cOldFont); break; } // next line TEXTMETRIC tm; dc.GetTextMetricsW(&tm); rc.top += tm.tmHeight; } return 0; } private: CString m_strCredits; HBITMAP m_hBitmap; POINT m_ptPos; };
[ "[email protected]@8d1da77e-e9f6-11de-9c2a-cb0f5ba72f9d" ]
[ [ [ 1, 138 ] ] ]
dcb5287ce96eac2bf24da508bd6a6d94bf0f1a4c
df5277b77ad258cc5d3da348b5986294b055a2be
/Spaceships/View.h
7493ed2b04d90adb8af8ee62231da71401683da0
[]
no_license
beentaken/cs260-last2
147eaeb1ab15d03c57ad7fdc5db2d4e0824c0c22
61b2f84d565cc94a0283cc14c40fb52189ec1ba5
refs/heads/master
2021-03-20T16:27:10.552333
2010-04-26T00:47:13
2010-04-26T00:47:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,905
h
/* the base view class. This is what actually is responsible for drawing to the screen. I really need to do some refactoring to extract the actual rendering responsibility away from the view. the view is only a place to gather and present the objects and actually doing the rendering is an additional responsibility. if I have time I'll fix this but if you're reading this than I probably did not. You probably won't need to change this class */ #pragma once #include "Model.h" class IRenderable; class View { public: View(Screen* screen, Model* m, LPDIRECT3DDEVICE9 d3dd); void DrawScreen(); virtual ~View(void); void SetSprite(LPD3DXSPRITE s); void LogError(int err, string text); LPDIRECT3DDEVICE9 GetDevice(); LPD3DXSPRITE GetSprite(); void PassMessage(Message* msg); void ProcessMessages(); RECT GetViewRect(); LPD3DXFONT GetErrorTextFont(); // currentPosition is an output parameter void* LockBuffer(int size); void UnlockBuffer(int bufferSize); void AddPointToRender(Vertex v); void SetBackground(LPDIRECT3DTEXTURE9 bgtext); protected: virtual void Draw() = 0; virtual void PreRender() = 0; virtual void PostRender() = 0; virtual void HandleMessage(Message* msg) = 0; Screen* screen; Model* _model; LPDIRECT3DDEVICE9 _dd3dDevice; LPD3DXSPRITE _sprite; LPD3DXFONT _errorFont; RECT screenRect; LPDIRECT3DTEXTURE9 background; int pointBufferOffset; void* pointBufferPointer; list<IRenderable*> renderables; list<Vertex> points; list<Message*> messages; //current size of line buffer- the max number of lines that this thing can hold int _lineBufferSize; //current size of point buffer- max number of points that this thing can hold int _pointBufferSize; RECT errRect1; RECT errRect2; RECT errRect3; LPDIRECT3DVERTEXBUFFER9 pointBuffer; LPDIRECT3DVERTEXBUFFER9 lineBuffer; };
[ "ProstheticMind43@af704e40-745a-32bd-e5ce-d8b418a3b9ef" ]
[ [ [ 1, 66 ] ] ]
7d264144738ea7ff654f8c2ebe276034dda49bfd
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Library/CDirDialog.cpp
9de031b8e19d56380199ff846d2b086ecf17f7c9
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
UTF-8
C++
false
false
4,549
cpp
/* CDirDialog.cpp Classe base per la selezione della directory (SDK/MFC). Riadattata e modificata dall'originale di James Spibey per essere usata senza MFC. Luca Piergentili, 14/07/00 [email protected] */ #include "env.h" #include "pragma.h" #include "macro.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "strings.h" #include "window.h" #include "win32api.h" #include <shlobj.h> #include "CDirDialog.h" #include "traceexpr.h" //#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT //#define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG_INFO _TRFLAG_NOTRACE #define _TRACE_FLAG_WARN _TRFLAG_NOTRACE #define _TRACE_FLAG_ERR _TRFLAG_NOTRACE #if (defined(_DEBUG) && defined(_WINDOWS)) && (defined(_AFX) || defined(_AFXDLL)) #ifdef PRAGMA_MESSAGE_VERBOSE #pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): using DEBUG_NEW macro") #endif #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // per l'always on top HWND m_hWnd = NULL; static BOOL m_bAlwaysOnTop = FALSE; /* CDirDialog() */ CDirDialog::CDirDialog(LPCSTR lpcszStartFolder/*=NULL*/,LPCSTR lpcszWindowTitle/*=NULL*/,LPCSTR lpcszTitle/*=NULL*/,BOOL bAlwaysOnTop/*=FALSE*/) { if(!lpcszStartFolder) memset(m_szSelDir,'\0',sizeof(m_szSelDir)); else strcpyn(m_szSelDir,lpcszStartFolder,sizeof(m_szSelDir)); memset(m_szInitDir,'\0',sizeof(m_szInitDir)); if(!lpcszWindowTitle) memset(m_szWindowTitle,'\0',sizeof(m_szWindowTitle)); else strcpyn(m_szWindowTitle,lpcszWindowTitle,sizeof(m_szWindowTitle)); if(!lpcszTitle) memset(m_szTitle,'\0',sizeof(m_szTitle)); else strcpyn(m_szTitle,lpcszTitle,sizeof(m_szTitle)); memset(m_szPathName,'\0',sizeof(m_szPathName)); m_bStatus = FALSE; m_bAlwaysOnTop = bAlwaysOnTop; m_nImageIndex = 0; } /* DoModal() */ int CDirDialog::DoModal(HWND hWnd/*=NULL*/) { if(!strempty(m_szSelDir)) { strrtrim(m_szSelDir); ::RemoveBackslash(m_szSelDir); } LPMALLOC pMalloc; if(::SHGetMalloc(&pMalloc)!=NOERROR) return(IDCANCEL); BROWSEINFO bInfo; LPITEMIDLIST pidl; ::ZeroMemory((PVOID)&bInfo,sizeof(BROWSEINFO)); if(!strempty(m_szInitDir)) { OLECHAR olePath[_MAX_PATH]; ULONG chEaten; ULONG dwAttributes; HRESULT hr; LPSHELLFOLDER pDesktopFolder; // get a pointer to the Desktop's IShellFolder interface if(SUCCEEDED(::SHGetDesktopFolder(&pDesktopFolder))) { // IShellFolder::ParseDisplayName requires the file name be in Unicode MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,m_szInitDir,-1,olePath,_MAX_PATH); // convert the path to an ITEMIDLIST hr = pDesktopFolder->ParseDisplayName(NULL,NULL,olePath,&chEaten,&pidl,&dwAttributes); if(FAILED(hr)) { pMalloc->Free(pidl); pMalloc->Release(); return(IDCANCEL); } bInfo.pidlRoot = pidl; } } bInfo.hwndOwner = m_hWnd = hWnd; bInfo.pszDisplayName = m_szPathName; bInfo.lpszTitle = m_szTitle; bInfo.ulFlags = BIF_USENEWUI | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS | (m_bStatus ? BIF_STATUSTEXT : 0); bInfo.lpfn = &BrowseCtrlCallback; bInfo.lParam = (LPARAM)this; if((pidl = ::SHBrowseForFolder(&bInfo))==NULL) return(IDCANCEL); m_nImageIndex = bInfo.iImage; if(::SHGetPathFromIDList(pidl,m_szPathName)==FALSE) { pMalloc->Free(pidl); pMalloc->Release(); return(IDCANCEL); } pMalloc->Free(pidl); pMalloc->Release(); return(IDOK); } /* BrowseCtrlCallback() */ int __stdcall CDirDialog::BrowseCtrlCallback(HWND hWnd,UINT uMsg,LPARAM lParam,LPARAM lpData) { CDirDialog* pCDirDialog = (CDirDialog*)lpData; if(uMsg==BFFM_INITIALIZED) { if(!strempty(pCDirDialog->m_szSelDir)) ::SendMessage(hWnd,BFFM_SETSELECTION,TRUE,(LPARAM)pCDirDialog->m_szSelDir); if(!strempty(pCDirDialog->m_szWindowTitle)) ::SetWindowText(hWnd,pCDirDialog->m_szWindowTitle); if(m_bAlwaysOnTop) ::SetWindowPos(hWnd,/*HWND_TOPMOST|*/m_hWnd,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); } else if(uMsg==BFFM_SELCHANGED) { LPITEMIDLIST pidl = (LPITEMIDLIST)lParam; char selection[_MAX_PATH]; if(!::SHGetPathFromIDList(pidl,selection)) selection[0] = '\0'; LPSTR lpszStatusText = NULL; BOOL bOk = pCDirDialog->SelChanged(selection,lpszStatusText); if(pCDirDialog->m_bStatus) ::SendMessage(hWnd,BFFM_SETSTATUSTEXT,0,(LPARAM)(LPCSTR)lpszStatusText); ::SendMessage(hWnd,BFFM_ENABLEOK,0,bOk); } return(0); }
[ [ [ 1, 175 ] ] ]
ce67da91e005c431537ea2cef5718ae33d2c9f02
5ed707de9f3de6044543886ea91bde39879bfae6
/ASBaseball/Shared/Source/ASBaseballType.h
395e2cbf93c3a928609a9237c3ce016bb73502d7
[]
no_license
grtvd/asifantasysports
9e472632bedeec0f2d734aa798b7ff00148e7f19
76df32c77c76a76078152c77e582faa097f127a8
refs/heads/master
2020-03-19T02:25:23.901618
1999-12-31T16:00:00
2018-05-31T19:48:19
135,627,290
0
0
null
null
null
null
UTF-8
C++
false
false
13,176
h
/* ASBaseballType.h */ /******************************************************************************/ /******************************************************************************/ #ifndef ASBaseballTypeH #define ASBaseballTypeH #include "ASFantasyType.h" using namespace asfantasy; namespace asbaseball { /******************************************************************************/ /* ID classes */ /* Field classes */ enum TBaseballPositionEnum { pos_Undefined, pos_FirstBaseman, pos_SecondBaseman, pos_ShortStop, pos_ThirdBaseman, pos_Catcher, pos_Outfielder, pos_DesignatedHitter, pos_StartingPitcher, pos_ReliefPitcher // Non-Participating Player Positions //pos_ //none }; #define pos_LastKeyPos pos_ReliefPitcher #define pos_Last pos_ReliefPitcher class TBaseballPosition : public EnumType<TBaseballPositionEnum,pos_Undefined,pos_Last> { public: TBaseballPosition(int t = pos_Undefined) : EnumType<TBaseballPositionEnum,pos_Undefined,pos_Last>(t) {} TBaseballPosition(const char* str); const char* c_str() const; bool isKey() const; bool isOffensive() const; }; enum TBaseballLineupEnum { lut_Undefined, lut_Batter, lut_Pitcher, }; #define lut_Last lut_Pitcher class TBaseballLineup : public EnumType<TBaseballLineupEnum,lut_Undefined,lut_Last> { public: TBaseballLineup(int t = lut_Undefined) : EnumType<TBaseballLineupEnum,lut_Undefined,lut_Last>(t) {} }; /******************************************************************************/ enum TRosterStatusEnum { rst_Undefined, rst_Active, rst_Disabled, rst_Inactive }; #define rst_Last rst_Inactive class TRosterStatus : public EnumType<TRosterStatusEnum,rst_Undefined,rst_Last> { public: TRosterStatus(int t = rst_Undefined) : EnumType<TRosterStatusEnum,rst_Undefined,rst_Last>(t) {} TRosterStatus(const char* str); const char* c_str() const; }; /******************************************************************************/ /* TotalPoints GamesPlayed GamesStarted Errors BattingAverage AtBats Hits Doubles Triples OneRunHomers TwoRunHomers ThreeRunHomers GrandSlams RunsScored RunsBattedIn Sacrifices HitByPicth Walks Strikeouts StolenBases CaughtStealing GroundedDoublePlay HitForCycle EarnedRunAverage Wins Losses Saves InningsPitched HitsAllowed DoublesAllowed TriplesAllowed OneRunHomersAllowed TwoRunHomersAllowed ThreeRunHomersAllowed GrandSlamsAllowed RunsAllowed EarnedRunsAllowed SacrificesAllowed HitBatsmen WalkedBatsmen StruckoutBatsmen WildPitches Balks CompleteGames Shutouts NoHitters PerfectGames */ enum TBaseballPlayerStatEnum { pst_Undefined = 0, //Both pst_TotalPoints, pst_GamesPlayed, pst_GamesStarted, pst_Errors, // Offense pst_BattingAverage, pst_AtBats, pst_Hits, pst_Doubles, pst_Triples, pst_OneRunHomers, pst_TwoRunHomers, pst_ThreeRunHomers, pst_GrandSlams, pst_RunsScored, pst_RunsBattedIn, pst_Sacrifices, pst_HitByPicth, pst_Walks, pst_Strikeouts, pst_StolenBases, pst_CaughtStealing, pst_GroundedDoublePlay, pst_HitForCycle, // Defense pst_EarnedRunAverage, pst_Wins, pst_Losses, pst_Saves, pst_InningsPitched, pst_HitsAllowed, pst_DoublesAllowed, pst_TriplesAllowed, pst_OneRunHomersAllowed, pst_TwoRunHomersAllowed, pst_ThreeRunHomersAllowed, pst_GrandSlamsAllowed, pst_RunsAllowed, pst_EarnedRunsAllowed, pst_SacrificesAllowed, pst_HitBatsmen, pst_WalkedBatsmen, pst_StruckoutBatsmen, pst_WildPitches, pst_Balks, pst_CompleteGames, pst_Shutouts, pst_NoHitters, pst_PerfectGames }; #define pst_Last pst_PerfectGames class TBaseballPlayerStatType : public EnumType<TBaseballPlayerStatEnum, pst_Undefined,pst_Last> { public: TBaseballPlayerStatType(int t = pst_Undefined) : EnumType<TBaseballPlayerStatEnum,pst_Undefined,pst_Last>(t) {} bool isOffensive() const { return(fT < pst_EarnedRunAverage); } }; /******************************************************************************/ class TBaseballTeam : public TTeam { protected: TPlayerIDVector fBatterLineup; TPlayerIDVector fPitcherLineup; protected: TBaseballTeam() {} virtual ~TBaseballTeam() {} public: virtual void clear(); virtual const TPlayerIDVector& lineupConst(TLineup lineup) const; virtual TPlayerIDVector& lineup(TLineup lineup); protected: /* DataSetRecord methods */ virtual void readFromDataSet(TDataSet& dataSet); virtual void writeToDataSet(TDataSet& dataSet); friend class RefCountPtr<TBaseballTeam>; friend class ASBaseballObjectBuilder; }; class TBaseballTeamPtr : public TDataSetRecordPtr<TBaseballTeam,TTeamID> { public: TBaseballTeamPtr(TTeamPtr teamPtr = TTeamPtr()) : TDataSetRecordPtr<TBaseballTeam,TTeamID>( teamPtr.isNull() ? NULL : &dynamic_cast<TBaseballTeam&>(*teamPtr)) {} operator TTeamPtr() { return(TTeamPtr(fT)); } }; /******************************************************************************/ class TBaseballProfPlayer : public TProfPlayer { protected: TBaseballPosition fPositionPrimary; TBaseballPosition fPositionSecondary; TRosterStatus fRosterStatus; protected: TBaseballProfPlayer() {} virtual ~TBaseballProfPlayer() {} public: virtual void clear(); virtual int getPosition() const { return(fPositionPrimary); } virtual void setPosition(int position) { fPositionPrimary = position; setHasChanged(); } int getPositionSecondary() const { return(fPositionSecondary); } void setPositionSecondary(int position) { fPositionSecondary = position; setHasChanged(); } void setRosterStatus(TRosterStatus rosterStatus) { fRosterStatus = rosterStatus; setHasChanged(); } TRosterStatus getRosterStatus(void) const { return (fRosterStatus); } virtual const char* getRosterStatusString() const { return(fRosterStatus.c_str()); } virtual const char* getInjuryStatusString() const { return(""); } protected: /* DataSetRecord methods */ virtual void readFromDataSet(TDataSet& dataSet); virtual void writeToDataSet(TDataSet& dataSet); virtual void validateForUpdate(); friend class RefCountPtr<TBaseballProfPlayer>; friend class ASBaseballObjectBuilder; }; class TBaseballProfPlayerPtr : public TDataSetRecordPtr<TBaseballProfPlayer,TPlayerID> { public: TBaseballProfPlayerPtr(TProfPlayerPtr profPlayerPtr = TProfPlayerPtr()) : TDataSetRecordPtr<TBaseballProfPlayer,TPlayerID>( profPlayerPtr.isNull() ? NULL : &dynamic_cast<TBaseballProfPlayer&>(*profPlayerPtr)) {} operator TProfPlayerPtr() { return(TProfPlayerPtr(fT)); } }; /******************************************************************************/ /* GamesPlayed GamesStarted AtBats Singles Doubles Triples OneRunHomers TwoRunHomers ThreeRunHomers GrandSlams RunsScored RunsBattedIn SacrificeHits SacrificeFlies HitByPicth UnintentWalks IntentWalks Strikeouts StolenBases CaughtStealing Errors GroundedDoublePlay HitForCycle */ class TOffGameStatDetail { public: short fGamesPlayed; short fGamesStarted; short fAtBats; short fSingles; short fDoubles; short fTriples; short fOneRunHomers; short fTwoRunHomers; short fThreeRunHomers; short fGrandSlams; short fRunsScored; short fRunsBattedIn; short fSacrificeHits; short fSacrificeFlies; short fHitByPicth; short fUnintentWalks; short fIntentWalks; short fStrikeouts; short fStolenBases; short fCaughtStealing; short fErrors; short fGroundedDoublePlay; short fHitForCycle; public: TOffGameStatDetail() { clear(); } virtual void clear(); short calcTotalPoints() const; double getStat(int playerStatType); void sumStats(const TOffGameStatDetail& offGameStatDetail); }; /******************************************************************************/ /* Wins Losses Saves BlownSaves Holds GamesPlayed GamesStarted CompleteGames GamesFinished QualityStarts Shutouts NoHitters PerfectGames OutsPitched BattersFaced SinglesAllowed DoublesAllowed TriplesAllowed OneRunHomersAllowed TwoRunHomersAllowed ThreeRunHomersAllowed GrandSlamsAllowed UnearnedRunsAllowed EarnedRunsAllowed SacrificeHitsAllowed SacrificeFliesAllowed HitBatsmen UnintentWalkedBatsmen IntentWalkedBatsmen StruckoutBatsmen WildPitches Balks Errors */ class TDefGameStatDetail { public: short fWins; short fLosses; short fSaves; short fBlownSaves; short fHolds; short fGamesPlayed; short fGamesStarted; short fCompleteGames; short fGamesFinished; short fQualityStarts; short fShutouts; short fNoHitters; short fPerfectGames; short fOutsPitched; short fBattersFaced; short fSinglesAllowed; short fDoublesAllowed; short fTriplesAllowed; short fOneRunHomersAllowed; short fTwoRunHomersAllowed; short fThreeRunHomersAllowed; short fGrandSlamsAllowed; short fUnearnedRunsAllowed; short fEarnedRunsAllowed; short fSacrificeHitsAllowed; short fSacrificeFliesAllowed; short fHitBatsmen; short fUnintentWalkedBatsmen; short fIntentWalkedBatsmen; short fStruckoutBatsmen; short fWildPitches; short fBalks; short fErrors; public: TDefGameStatDetail() { clear(); } virtual void clear(); short calcTotalPoints() const; double getStat(int playerStatType); void sumStats(const TDefGameStatDetail& defGameStatDetail); }; /******************************************************************************/ class TBaseballOffGameStat : public TOffGameStat { protected: TBaseballPosition fPosition; TOffGameStatDetail fOffGameStatDetail; protected: TBaseballOffGameStat() {} virtual ~TBaseballOffGameStat() {} public: virtual void clear(); int getPosition() const { return(fPosition); } void setPosition(int position) { fPosition = position; setHasChanged(); } TOffGameStatDetail& offGameStatDetail() { setHasChanged(); return(fOffGameStatDetail); } const TOffGameStatDetail& offGameStatDetail() const { return(fOffGameStatDetail); } virtual void calcTotalPoints() { fTotalPoints = fOffGameStatDetail.calcTotalPoints(); setHasChanged(); } virtual double getStat(int playerStatType); static CStr31 getDefaultStatStr(int playerStatType); virtual CStr31 getStatStr(int playerStatType); virtual void sumStats(const TOffGameStatPtr offGameStatPtr); protected: /* DataSetRecord methods */ virtual void readFromDataSet(TDataSet& dataSet); virtual void writeToDataSet(TDataSet& dataSet); virtual void validateForUpdate(); friend class RefCountPtr<TBaseballOffGameStat>; friend class ASBaseballObjectBuilder; }; class TBaseballOffGameStatPtr : public TDataSetRecordPtr<TBaseballOffGameStat, TPlayerStatID> { public: TBaseballOffGameStatPtr(TOffGameStatPtr offGameStatPtr = TOffGameStatPtr()) : TDataSetRecordPtr<TBaseballOffGameStat,TPlayerStatID>( offGameStatPtr.isNull() ? NULL : &dynamic_cast<TBaseballOffGameStat&>(*offGameStatPtr)) {} operator TOffGameStatPtr() { return(TOffGameStatPtr(fT)); } }; /******************************************************************************/ class TBaseballDefGameStat : public TDefGameStat { protected: TBaseballPosition fPosition; TDefGameStatDetail fDefGameStatDetail; protected: TBaseballDefGameStat() {} virtual ~TBaseballDefGameStat() {} public: virtual void clear(); int getPosition() const { return(fPosition); } void setPosition(int position) { fPosition = position; setHasChanged(); } TDefGameStatDetail& defGameStatDetail() { setHasChanged(); return(fDefGameStatDetail); } const TDefGameStatDetail& defGameStatDetail() const { return(fDefGameStatDetail); } virtual void calcTotalPoints() { fTotalPoints = fDefGameStatDetail.calcTotalPoints(); setHasChanged(); } virtual double getStat(int playerStatType); static CStr31 getDefaultStatStr(int playerStatType); virtual CStr31 getStatStr(int playerStatType); virtual void sumStats(const TDefGameStatPtr defGameStatPtr); protected: /* DataSetRecord methods */ virtual void readFromDataSet(TDataSet& dataSet); virtual void writeToDataSet(TDataSet& dataSet); virtual void validateForUpdate(); friend class RefCountPtr<TBaseballDefGameStat>; friend class ASBaseballObjectBuilder; }; class TBaseballDefGameStatPtr : public TDataSetRecordPtr<TBaseballDefGameStat, TPlayerStatID> { public: TBaseballDefGameStatPtr(TDefGameStatPtr defGameStatPtr = TDefGameStatPtr()) : TDataSetRecordPtr<TBaseballDefGameStat,TPlayerStatID>( defGameStatPtr.isNull() ? NULL : &dynamic_cast<TBaseballDefGameStat&>(*defGameStatPtr)) {} operator TDefGameStatPtr() { return(TDefGameStatPtr(fT)); } }; /******************************************************************************/ }; //namespace asbaseball #endif //ASBaseballTypeH /******************************************************************************/ /******************************************************************************/
[ [ [ 1, 575 ] ] ]
2f7d3fb85175631593474e0744247c4f2c79285e
b308f1edaab2be56eb66b7c03b0bf4673621b62f
/Code/Game/GameDll/SPAnalyst.cpp
49246814e5e809a1ba3dd6168521625484c35a5f
[]
no_license
blockspacer/project-o
14e95aa2692930ee90d098980a7595759a8a1f74
403ec13c10757d7d948eafe9d0a95a7f59285e90
refs/heads/master
2021-05-31T16:46:36.814786
2011-09-16T14:34:07
2011-09-16T14:34:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,139
cpp
//////////////////////////////////////////////////////////////////////////// // // Crytek Engine Source File. // Copyright (C), Crytek Studios, 2007. // ------------------------------------------------------------------------- // File name: SPAnalyst.cpp // Version: v1.00 // Created: 07/07/2006 by AlexL // Compilers: Visual Studio.NET // Description: SPAnalyst to track/serialize some SP stats // ------------------------------------------------------------------------- // History: // //////////////////////////////////////////////////////////////////////////// #include "StdAfx.h" #include "SPAnalyst.h" #include <ISerialize.h> #include <Game.h> #include <ISaveGame.h> CSPAnalyst::CSPAnalyst() : m_bEnabled(false), m_bChainLoad(false) { IGameFramework* pGF = g_pGame->GetIGameFramework(); pGF->GetILevelSystem()->AddListener(this); pGF->RegisterListener(this, "CSPAnalyst", FRAMEWORKLISTENERPRIORITY_GAME); } CSPAnalyst::~CSPAnalyst() { IGameFramework* pGF = g_pGame->GetIGameFramework(); if (m_bEnabled) pGF->GetIGameplayRecorder()->UnregisterListener(this); pGF->GetILevelSystem()->RemoveListener(this); pGF->UnregisterListener(this); } void CSPAnalyst::Enable(bool bEnable) { if (m_bEnabled != bEnable) { if (bEnable) { Reset(); g_pGame->GetIGameFramework()->GetIGameplayRecorder()->RegisterListener(this); } else g_pGame->GetIGameFramework()->GetIGameplayRecorder()->UnregisterListener(this); m_bEnabled = bEnable; } } bool CSPAnalyst::IsPlayer(EntityId entityId) const { // fast path, if already known if (m_gameAnalysis.player.entityId == entityId) return true; // slow path, only first time if (IActor *pActor=g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(entityId)) return pActor->IsPlayer(); return false; } void CSPAnalyst::NewPlayer(IEntity* pEntity) { m_gameAnalysis.player = PlayerAnalysis(pEntity->GetId()); m_gameAnalysis.player.name = pEntity->GetName(); } CSPAnalyst::PlayerAnalysis* CSPAnalyst::GetPlayer(EntityId entityId) { if (m_gameAnalysis.player.entityId == entityId) return &m_gameAnalysis.player; return 0; } void CSPAnalyst::OnGameplayEvent(IEntity *pEntity, const GameplayEvent &event) { if(!gEnv->bServer) return; EntityId entityId = pEntity ? pEntity->GetId() : 0; if (entityId && IsPlayer(entityId)) ProcessPlayerEvent(pEntity, event); switch (event.event) { case eGE_GameStarted: { const float t = gEnv->pTimer->GetCurrTime(); // CryLogAlways("[CSPAnalyst]: Game Started at %f", t); // if the levelStartTime was serialized, don't touch it if (m_gameAnalysis.levelStartTime == 0.0f) m_gameAnalysis.levelStartTime = gEnv->pTimer->GetFrameStartTime(); // if the gameStartTime was serialized, don't touch it if (m_gameAnalysis.gameStartTime == 0.0f) m_gameAnalysis.gameStartTime = m_gameAnalysis.levelStartTime; } // called in SP as well break; case eGE_GameEnd: { int a = 0;(void)a; } // not called in SP yet break; default: break; } } void CSPAnalyst::ProcessPlayerEvent(IEntity* pEntity, const GameplayEvent& event) { assert (pEntity != 0); const EntityId entityId = pEntity->GetId(); switch (event.event) { case eGE_Connected: { NewPlayer(pEntity); const float t = gEnv->pTimer->GetCurrTime(); // CryLogAlways("[CSPAnalyst]: Connected at %f", t); } break; case eGE_Kill: if (PlayerAnalysis* pA = GetPlayer(entityId)) ++pA->kills; break; case eGE_Death: if (PlayerAnalysis* pA = GetPlayer(entityId)) ++pA->deaths; default: break; } } void CSPAnalyst::PlayerAnalysis::Serialize(TSerialize ser) { ser.BeginGroup("PA"); ser.Value("kills", kills); ser.Value("deaths", deaths); ser.EndGroup(); } void CSPAnalyst::Serialize(TSerialize ser) { if (ser.BeginOptionalGroup("SPAnalyst", true)) { ser.Value("levelStartTime", m_gameAnalysis.levelStartTime); ser.Value("gameStartTime", m_gameAnalysis.gameStartTime); m_gameAnalysis.player.Serialize(ser); ser.EndGroup(); } } void CSPAnalyst::Reset() { m_gameAnalysis = GameAnalysis(); } void CSPAnalyst::OnLoadingStart(ILevelInfo *pLevelInfo) { if (pLevelInfo == 0) return; // in any case, reset the level start time, so it will either be restored from SaveGame or // set in eGE_GameStarted event handling m_gameAnalysis.levelStartTime = CTimeValue(0.0f); m_bChainLoad = false; } void CSPAnalyst::OnSaveGame(ISaveGame* pSaveGame) { if (m_bEnabled == false || pSaveGame == 0) return; CTimeValue now = gEnv->pTimer->GetFrameStartTime(); pSaveGame->AddMetadata("sp_kills", m_gameAnalysis.player.kills); pSaveGame->AddMetadata("sp_deaths", m_gameAnalysis.player.deaths); pSaveGame->AddMetadata("sp_levelPlayTime", (int)((now-m_gameAnalysis.levelStartTime).GetSeconds())); pSaveGame->AddMetadata("sp_gamePlayTime", (int)((now-m_gameAnalysis.gameStartTime).GetSeconds())); } void CSPAnalyst::OnLevelEnd(const char *nextLevel) { m_bChainLoad = true; }
[ [ [ 1, 192 ] ] ]
1ea6339b7f6d7662cadd892f19768446582a6238
3182b05c41f13237825f1ee59d7a0eba09632cd5
/add/GUI/GuiCellArray.cpp
b0810e7ae68e411d3be1c093e8609ee2dbfaa0a3
[]
no_license
adhistac/ee-client-2-0
856e8e6ce84bfba32ddd8b790115956a763eec96
d225fc835fa13cb51c3e0655cb025eba24a8cdac
refs/heads/master
2021-01-17T17:13:48.618988
2010-01-04T17:35:12
2010-01-04T17:35:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,707
cpp
#include "GuiCellArray.h" #include "../RPGPack/RPGBook.h" #include "console/consoleTypes.h" #include "gfx/gfxDrawUtil.h" #include "gui/core/guiCanvas.h" #include "../RPGPack/RPGBaseData.h" IMPLEMENT_CONOBJECT(guiCellArray); bool guiCellArray::isValidPosition( U8 page,U8 slot ) { return page >= 0 && page < m_nPages && slot >= 0 && slot < m_nColumnsPerPage * m_nRowsPerPage; } U8 guiCellArray::getSlotByLocalPosition( Point2I pos ) { U8 row = pos.y / (m_nCellSizeY + m_nCellPadingY); U8 column = pos.x / (m_nCellSizeX + m_nCellPadingX); return row * m_nColumnsPerPage + column; } F32 guiCellArray::getRatioOfCoolDown(const U8 & idx) { return m_pBook ? m_pBook->getRatioOfCDTime(idx) : 0; } void guiCellArray::initPersistFields() { Parent::initPersistFields(); addGroup("guiCellArray"); addField("RowsPerPage", TypeS8, Offset(m_nRowsPerPage, guiCellArray)); addField("ColumnsPerPage", TypeS8, Offset(m_nColumnsPerPage, guiCellArray)); addField("Pages", TypeS8, Offset(m_nPages, guiCellArray)); addField("xPad", TypeS8, Offset(m_nCellPadingX, guiCellArray)); addField("yPad", TypeS8, Offset(m_nCellPadingY, guiCellArray)); addField("cellSizeX", TypeS8, Offset(m_nCellSizeX, guiCellArray)); addField("cellSizeY", TypeS8, Offset(m_nCellSizeY, guiCellArray)); addField("locked", TypeBool , Offset(m_bLocked, guiCellArray)); addField("clientOnly", TypeBool , Offset(m_bClientOnly, guiCellArray)); endGroup("guiCellArray"); } U8 guiCellArray::getPickedIndex() { return _nPickedIndex; } U8 guiCellArray::getCurrentPage() { return m_nCurrentPage; } void guiCellArray::setPickedIndex( U8 idx ) { _nPickedIndex = idx; } void guiCellArray::clearPickedIndex() { _nPickedIndex = -1; } void guiCellArray::setRolloverIndex( U8 idx ) { if (_nRolloveIndex >= 0) { m_nCellItems[_nRolloveIndex]._statu = CellItem::Item_Normal; } _nRolloveIndex = idx; if (_nRolloveIndex >= 0) { m_nCellItems[_nRolloveIndex]._statu = CellItem::Item_Rollover; } } void guiCellArray::clearRolloverIndex() { setRolloverIndex(-1); } RPGBook * guiCellArray::getPlayerBook() { return m_pBook; } U8 guiCellArray::getIndex( U8 page,U8 slot ) { if (isValidPosition(page,slot)) { return page * m_nRowsPerPage * m_nColumnsPerPage + slot; } return -1; } U8 guiCellArray::getSlotByGlobalPosition( Point2I pos ) { return getSlotByLocalPosition(globalToLocalCoord(pos)); } void guiCellArray::sendDragEvent( GuiControl* target, const char* event,Point2I mousePoint ) { if(!target || !target->isMethod(event)) return; /* function guiCellArray::onControlDropped(%this,%srcarray,%srcPickedIndex,%globalMouseX,%globalMouseY) */ Con::executef(target, event, Con::getIntArg(this->getId()),\ Con::getIntArg(this->getPickedIndex()), \ Con::getIntArg(mousePoint.x), \ Con::getIntArg(mousePoint.y)); } GuiControl* guiCellArray::findDragTarget( Point2I mousePoint, const char* method ) { // If there are any children and we have a parent. GuiControl* parent = (GuiControl*)getRoot(); //if (size() && parent) if(parent) { //mVisible = false; GuiControl* dropControl = parent->findHitControl(mousePoint); //mVisible = true; while( dropControl ) { if (dropControl->isMethod(method)) return dropControl; else dropControl = dropControl->getParent(); } } return NULL; } void guiCellArray::onRender( Point2I offset, const RectI &updateRect ) { //draw lines Point2I ptUperLeft = updateRect.point; Point2I ptLowerRight = ptUperLeft + updateRect.extent; Point2I ptDrawStart = ptUperLeft; Point2I ptDrawEnd = ptDrawStart; ColorI color(255,0,0); ptDrawEnd.x += m_nCellSizeX * m_nColumnsPerPage; ptDrawEnd.x += m_nCellPadingX * (m_nColumnsPerPage - 1); for (int n = 0 ; n <= m_nRowsPerPage ; n++) { //GFX->getDrawUtil()->drawLine(ptDrawStart,ptDrawEnd,color); ptDrawStart.y += m_nCellSizeY; ptDrawEnd.y += m_nCellSizeY; //GFX->getDrawUtil()->drawLine(ptDrawStart,ptDrawEnd,color); ptDrawStart.y += m_nCellPadingY; ptDrawEnd.y += m_nCellPadingY; } ptDrawStart = ptDrawEnd = ptUperLeft; ptDrawEnd.y += m_nCellSizeY * m_nRowsPerPage; ptDrawEnd.y += m_nCellPadingY * (m_nRowsPerPage - 1); for (int n = 0 ; n <= m_nColumnsPerPage ; n++) { //GFX->getDrawUtil()->drawLine(ptDrawStart,ptDrawEnd,color); ptDrawStart.x += m_nCellSizeX; ptDrawEnd.x += m_nCellSizeX; //GFX->getDrawUtil()->drawLine(ptDrawStart,ptDrawEnd,color); ptDrawStart.x += m_nCellPadingX; ptDrawEnd.x += m_nCellPadingX; } //draw items from book if (m_pBook) { F32 ratio = 0;//getRatioOfCoolDown(); U8 idx = 0; //Point2I pt = ptUperLeft; RectI rect,rect2; rect.point = ptUperLeft; rect.extent = Point2I(m_nCellSizeX,m_nCellSizeY); RPGBaseData * pRPGData = NULL; Point2I center; Point2I diff(4,4); ColorI color(0,0,0,128); GFX->getDrawUtil()->clearBitmapModulation(); for (int n = 0 ; n < m_nRowsPerPage ; n++) { for (int m = 0 ; m < m_nColumnsPerPage ; m++) { idx = n * m_nColumnsPerPage + m; rect.point.x = ptUperLeft.x + m * (m_nCellSizeX + m_nCellPadingX); rect.point.y = ptUperLeft.y + n * (m_nCellSizeY + m_nCellPadingY); rect2 = rect; rect2.point += diff; rect2.extent -= diff * 2; if (mTextureObject) { GFX->getDrawUtil()->drawBitmapStretch(mTextureObject,rect); } pRPGData = m_pBook->getRpgBaseData(idx); ratio = getRatioOfCoolDown(idx); if (pRPGData) { if(m_nCellItems[idx]._statu == CellItem::Item_Normal || m_nCellItems[idx]._statu == CellItem::Item_Rollover) { GFX->getDrawUtil()->drawBitmapStretch(m_nCellItems[idx]._textureHandle,rect2); if (mFabs(ratio) > 0.01 && mFabs(ratio) < 0.99) { center.x = rect2.point.x + rect2.extent.x / 2; center.y = rect2.point.y + rect2.extent.y / 2; GFX->getDrawUtil()->drawCDRectFill(center,rect2.extent,M_2PI * ratio,color); } } } } } } renderChildControls(offset, updateRect); } void guiCellArray::onMouseDown( const GuiEvent &event ) { if (m_bLocked) return; GuiCanvas* canvas = getRoot(); AssertFatal(canvas, "guiCellArray wasn't added to the gui before the drag started."); if (canvas->getMouseLockedControl()) { GuiEvent event; canvas->getMouseLockedControl()->onMouseLeave(event); canvas->mouseUnlock(canvas->getMouseLockedControl()); } canvas->mouseLock(this); canvas->setFirstResponder(this); U8 slot = getSlotByGlobalPosition(event.mousePoint); if (isValidPosition(m_nCurrentPage,slot)) { U8 n = getIndex(m_nCurrentPage,slot); m_nCellItems[n]._statu = CellItem::Item_PickedUp; setPickedIndex(n); if (isItemEmpty(n)) { return; } GuiCanvas* Canvas = getRoot(); GuiCursor * pCursor = Canvas->getCurrentCursor(); if (pCursor) { pCursor->setPickedBmp(m_nCellItems[n]._bmpPath); } } } void guiCellArray::onMouseUp( const GuiEvent &event ) { if (m_bLocked) return; mouseUnlock(); GuiCanvas* Canvas = getRoot(); GuiCursor * pCursor = Canvas->getCurrentCursor(); if (pCursor) { pCursor->clearPickedBmp(); } GuiControl* target = findDragTarget(event.mousePoint, "onControlDropped"); if (target) { sendDragEvent(target, "onControlDropped",event.mousePoint); } else { cancelMove(); } } void guiCellArray::onRightMouseDown( const GuiEvent &event ) { if (m_bLocked) return; U8 slot = getSlotByGlobalPosition(event.mousePoint); if (isValidPosition(m_nCurrentPage,slot)) { U8 n = getIndex(m_nCurrentPage,slot); F32 ratio = getRatioOfCoolDown(n); if (ratio < 1.f && ratio > 0) { return; } Con::executef(this,"onRightMouseDown",Con::getIntArg(n)); } } void guiCellArray::onMouseMove( const GuiEvent &event ) { if (NULL == m_pBook) { return; } Parent::onMouseMove(event); U8 slot = getSlotByGlobalPosition(event.mousePoint); if (isValidPosition(m_nCurrentPage,slot)) { U8 n = getIndex(m_nCurrentPage,slot); if (_nRolloveIndex == n) { return; } RPGBaseData * pRPGDataOld = m_pBook->getRpgBaseData(_nRolloveIndex); if (pRPGDataOld) { Con::executef(this,"onLeaveSlot",Con::getIntArg(pRPGDataOld->getId())); } setRolloverIndex(n); if (isItemEmpty(n)) { return; } RPGBaseData * pRPGData = m_pBook->getRpgBaseData(n); if (pRPGData) { Con::executef(this,"onEnterSlot",Con::getIntArg(pRPGData->getId())); } } } void guiCellArray::onMouseLeave( const GuiEvent &event ) { clearRolloverIndex(); Con::executef(this,"onLeaveSlot"); } void guiCellArray::cancelMove() { if (_nPickedIndex != -1) { m_nCellItems[_nPickedIndex]._statu = CellItem::Item_Normal; } clearPickedIndex(); } void guiCellArray::setBook( RPGBook * pBook ) { m_pBook = pBook; refreshItems(); } void guiCellArray::pageUp() { if (m_nCurrentPage > 0 && m_nCurrentPage <= m_nPages - 1) { --m_nCurrentPage; } } void guiCellArray::pageDown() { if (m_nCurrentPage >= 0 && m_nCurrentPage < m_nPages - 1) { ++m_nCurrentPage; } } void guiCellArray::refreshItems() { RPGBaseData * pRPGData = NULL; int idx = 0; if (NULL == m_pBook) { return; } for (int n = 0 ; n < m_nRowsPerPage ; n++) { for (int m = 0 ; m < m_nColumnsPerPage ; m++) { idx = n * m_nColumnsPerPage + m; pRPGData = m_pBook->getRpgBaseData(idx); if (pRPGData) { if (dStrcmp(pRPGData->getIconName(),m_nCellItems[idx]._bmpPath) != 0) { dStrcpy(m_nCellItems[idx]._bmpPath,pRPGData->getIconName()); if(m_nCellItems[idx]._bmpPath[0] == 0) m_nCellItems[idx]._textureHandle = NULL; else m_nCellItems[idx]._textureHandle.set(m_nCellItems[idx]._bmpPath,&GFXDefaultGUIProfile,"cell item bmp"); } } m_nCellItems[idx]._statu = CellItem::Item_Normal; } } } bool guiCellArray::isItemEmpty( U8 index ) { RPGBook * pBook = getPlayerBook(); if (pBook) { return pBook->isItemEmpty(index); } return true; } guiCellArray::guiCellArray():m_pBook(NULL),m_nPages(0),m_nCurrentPage(0),\ m_nRowsPerPage(0),m_nColumnsPerPage(0),m_nCellSizeX(42),m_nCellSizeY(42),\ _nPickedIndex(-1),m_nCellPadingX(0),m_nCellPadingY(0),_nRolloveIndex(-1),\ m_bLocked(false),m_bClientOnly(false) { } guiCellArray * guiCellArray::getBookGUI( const U8 & bookType ) { guiCellArray * pGUI = NULL; char guiName[128]; switch(bookType) { case BOOK_PACK: dStrcpy(guiName,"backpack"); break; case BOOK_SHOTCUTBAR1: dStrcpy(guiName,"shortcut1_gui"); break; default: dStrcpy(guiName,"nothing"); break; } pGUI = dynamic_cast<guiCellArray*>(Sim::findObject(guiName)); return pGUI; } ConsoleMethod(guiCellArray,getCurrentPage,S32,2,2,"return current page") { return object->getCurrentPage(); } ConsoleMethod(guiCellArray,getIndex,S32,4,4,"%page,%slot") { return object->getIndex(dAtoi(argv[2]),dAtoi(argv[3])); } ConsoleMethod(guiCellArray,getSlotByGlobalPosition,S32,4,4,"%x,%y") { return object->getSlotByGlobalPosition(Point2I(dAtoi(argv[2]),dAtoi(argv[3]))); } ConsoleMethod(guiCellArray,getPlayerBook,S32,2,2,"return the rpgbook") { RPGBook * pBook = object->getPlayerBook(); return pBook ? pBook->getId() : -1; } ConsoleMethod(guiCellArray,isItemEmpty,bool,3,3,"%idx") { return ((guiCellArray*)object)->isItemEmpty(dAtoi(argv[2])); }
[ [ [ 1, 462 ] ] ]
0c9842207fc79de210d4db15e3ed1a3e5f56d6cb
1e299bdc79bdc75fc5039f4c7498d58f246ed197
/stdobj/ThreadPool.cpp
44f6d6937f4f181a9c1d5e21d34e4f7422cc62c9
[]
no_license
moosethemooche/Certificate-Server
5b066b5756fc44151b53841482b7fa603c26bf3e
887578cc2126bae04c09b2a9499b88cb8c7419d4
refs/heads/master
2021-01-17T06:24:52.178106
2011-07-13T13:27:09
2011-07-13T13:27:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,857
cpp
//-------------------------------------------------------------------------------- // // Copyright (c) 1999 MarkCare Solutions // // Programming by Rich Schonthal // //-------------------------------------------------------------------------------- #include "stdafx.h" #include "ThreadPool.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //-------------------------------------------------------------------------------- IMPLEMENT_DYNCREATE(CThreadPool, CWinThread) //-------------------------------------------------------------------------------- BEGIN_MESSAGE_MAP(CThreadPool, CWinThread) //{{AFX_MSG_MAP(CThreadPool) //}}AFX_MSG_MAP ON_THREAD_MESSAGE(TPMSG_INIT, DoInit) ON_THREAD_MESSAGE(TPMSG_MESSAGE, DoMsg) END_MESSAGE_MAP() //-------------------------------------------------------------------------------- CThreadPool::CThreadPool() { } //-------------------------------------------------------------------------------- CThreadPool::~CThreadPool() { } //-------------------------------------------------------------------------------- BOOL CThreadPool::InitInstance() { return TRUE; } //-------------------------------------------------------------------------------- int CThreadPool::ExitInstance() { MSG msg; while(PeekMessage(&msg, (HWND) -1, TPMSG_MESSAGE, TPMSG_MESSAGE, PM_REMOVE)) delete (CThreadPoolMsg*) msg.wParam; CSingleLock lock(&m_waiting.m_mutex, false); if(! lock.Lock(INFINITE)) return -1; CSingleLock lock2(&m_active.m_mutex, false); if(! lock2.Lock(INFINITE)) return -1; // stop all threads // wait for them to exit int nSizeA = m_active.GetCount(); int nSizeW = m_waiting.GetCount(); int nSize = nSizeA + nSizeW; if(nSize > 0) { POSITION pos = m_active.GetHeadPosition(); HANDLE* pHands = new HANDLE[nSize]; CWinThread* pThread = NULL; for(int i = 0; i < nSizeA; i++) { pThread = m_active.GetNext(pos); pHands[i] = pThread->m_hThread; pThread->PostThreadMessage(WM_QUIT, 0, 0); } pos = m_waiting.GetHeadPosition(); for(; i < nSize; i++) { pThread = m_waiting.GetNext(pos); pHands[i] = pThread->m_hThread; pThread->PostThreadMessage(WM_QUIT, 0, 0); } ::WaitForMultipleObjects(nSize, pHands, true, 60000); } return CWinThread::ExitInstance(); } //-------------------------------------------------------------------------------- int CThreadPool::GetActiveCount() { CSingleLock lock(&m_active.m_mutex, false); if(! lock.Lock(10000)) return -1; return m_active.GetCount(); } //-------------------------------------------------------------------------------- int CThreadPool::GetWaitingCount() { CSingleLock lock(&m_waiting.m_mutex, false); if(! lock.Lock(10000)) return -1; return m_waiting.GetCount(); } //-------------------------------------------------------------------------------- int CThreadPool::GetPoolSize() { CSingleLock lock(&m_waiting.m_mutex, false); if(! lock.Lock(10000)) return -1; CSingleLock lock2(&m_active.m_mutex, false); if(! lock2.Lock(10000)) return -1; #ifdef _DEBUG TRACE(_T("waiting = %d active = %d\n"), m_waiting.GetCount(), m_active.GetCount()); #endif return m_waiting.GetCount() + m_active.GetCount(); } //-------------------------------------------------------------------------------- bool CThreadPool::SetThreadActive(CWinThread* pThread) { CSingleLock lock(&m_waiting.m_mutex, false); if(! lock.Lock(10000)) return false; CSingleLock lock2(&m_active.m_mutex, false); if(! lock2.Lock(10000)) return false; POSITION pos = m_waiting.Find(pThread); if(pos != NULL) m_waiting.RemoveAt(pos); pos = m_active.Find(pThread); if(pos != NULL) m_active.RemoveAt(pos); return m_active.AddHead(pThread) != NULL; } //-------------------------------------------------------------------------------- bool CThreadPool::SetThreadWaiting(CWinThread* pThread) { CSingleLock lock(&m_waiting.m_mutex, false); if(! lock.Lock(10000)) return false; CSingleLock lock2(&m_active.m_mutex, false); if(! lock2.Lock(10000)) return false; POSITION pos = m_waiting.Find(pThread); if(pos != NULL) m_waiting.RemoveAt(pos); pos = m_active.Find(pThread); if(pos != NULL) m_active.RemoveAt(pos); return m_waiting.AddHead(pThread) != NULL; } //-------------------------------------------------------------------------------- CWinThread* CThreadPool::GetNextWaiting() { CSingleLock lock(&m_waiting.m_mutex, false); if(! lock.Lock(10000)) return NULL; if(m_waiting.GetCount() == 0) return NULL; POSITION pos = m_waiting.GetHeadPosition(); if(pos == NULL) return NULL; CWinThread* pThread = m_waiting.GetAt(pos); m_waiting.RemoveAt(pos); return pThread; } //-------------------------------------------------------------------------------- void CThreadPool::DoInit(DWORD nCount, CRuntimeClass* pClass) { CSingleLock lock(&m_waiting.m_mutex, false); if(! lock.Lock(10000)) return; for(UINT i = 0; i < nCount; i++) m_waiting.AddTail(::AfxBeginThread(pClass)); } //-------------------------------------------------------------------------------- void CThreadPool::DoMsg(CThreadPoolMsg* pMsg, LPARAM) { // attempt to move a thread from waiting to active, then send it the msg // if there are no avail waiting threads, then keep sending ourselves the msg // until a thread becomes available CWinThread* pThread = GetNextWaiting(); if(pThread == NULL) { ::Sleep(20); PostThreadMessage(TPMSG_MESSAGE, (WPARAM) pMsg, 0); return; } SetThreadActive(pThread); pThread->PostThreadMessage(pMsg->m_nMsg, pMsg->m_wparam, pMsg->m_lparam); delete pMsg; }
[ [ [ 1, 220 ] ] ]
c73f89f6675fcb7610aa2cab596db73fa315b329
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/algorithm/string/predicate.hpp
f58c7feae9e954f6ae3bb55f7251bb38c38b36e3
[ "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
16,003
hpp
// Boost string_algo library predicate.hpp header file ---------------------------// // Copyright Pavol Droba 2002-2003. Use, modification and // distribution is subject to 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) // See http://www.boost.org for updates, documentation, and revision history. #ifndef BOOST_STRING_PREDICATE_HPP #define BOOST_STRING_PREDICATE_HPP #include <boost/algorithm/string/config.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/range/iterator.hpp> #include <boost/range/const_iterator.hpp> #include <boost/algorithm/string/compare.hpp> #include <boost/algorithm/string/find.hpp> #include <boost/algorithm/string/detail/predicate.hpp> /*! \file boost/algorithm/string/predicate.hpp Defines string-related predicates. The predicates determine whether a substring is contained in the input string under various conditions: a string starts with the substring, ends with the substring, simply contains the substring or if both strings are equal. Additionaly the algorithm \c all() checks all elements of a container to satisfy a condition. All predicates provide the strong exception guarantee. */ namespace boost { namespace algorithm { // starts_with predicate -----------------------------------------------// //! 'Starts with' predicate /*! This predicate holds when the test string is a prefix of the Input. In other words, if the input starts with the test. When the optional predicate is specified, it is used for character-wise comparison. \param Input An input sequence \param Test A test sequence \param Comp An element comparison predicate \return The result of the test \note This function provides the strong exception-safety guarantee */ template<typename Range1T, typename Range2T, typename PredicateT> inline bool starts_with( const Range1T& Input, const Range2T& Test, PredicateT Comp) { typedef BOOST_STRING_TYPENAME range_const_iterator<Range1T>::type Iterator1T; typedef BOOST_STRING_TYPENAME range_const_iterator<Range2T>::type Iterator2T; Iterator1T InputEnd=end(Input); Iterator2T TestEnd=end(Test); Iterator1T it=begin(Input); Iterator2T pit=begin(Test); for(; it!=InputEnd && pit!=TestEnd; ++it,++pit) { if( !(Comp(*it,*pit)) ) return false; } return pit==TestEnd; } //! 'Starts with' predicate /*! \overload */ template<typename Range1T, typename Range2T> inline bool starts_with( const Range1T& Input, const Range2T& Test) { return starts_with(Input, Test, is_equal()); } //! 'Starts with' predicate ( case insensitive ) /*! This predicate holds when the test string is a prefix of the Input. In other words, if the input starts with the test. Elements are compared case insensitively. \param Input An input sequence \param Test A test sequence \param Loc A locale used for case insensitive comparison \return The result of the test \note This function provides the strong exception-safety guarantee */ template<typename Range1T, typename Range2T> inline bool istarts_with( const Range1T& Input, const Range2T& Test, const std::locale& Loc=std::locale()) { return starts_with(Input, Test, is_iequal(Loc)); } // ends_with predicate -----------------------------------------------// //! 'Ends with' predicate /*! This predicate holds when the test string is a suffix of the Input. In other words, if the input ends with the test. When the optional predicate is specified, it is used for character-wise comparison. \param Input An input sequence \param Test A test sequence \param Comp An element comparison predicate \return The result of the test \note This function provides the strong exception-safety guarantee */ template<typename Range1T, typename Range2T, typename PredicateT> inline bool ends_with( const Range1T& Input, const Range2T& Test, PredicateT Comp) { typedef BOOST_STRING_TYPENAME range_const_iterator<Range1T>::type Iterator1T; typedef BOOST_STRING_TYPENAME boost::detail:: iterator_traits<Iterator1T>::iterator_category category; return detail:: ends_with_iter_select( begin(Input), end(Input), begin(Test), end(Test), Comp, category()); } //! 'Ends with' predicate /*! \overload */ template<typename Range1T, typename Range2T> inline bool ends_with( const Range1T& Input, const Range2T& Test) { return ends_with(Input, Test, is_equal()); } //! 'Ends with' predicate ( case insensitive ) /*! This predicate holds when the test container is a suffix of the Input. In other words, if the input ends with the test. Elements are compared case insensitively. \param Input An input sequence \param Test A test sequence \param Loc A locale used for case insensitive comparison \return The result of the test \note This function provides the strong exception-safety guarantee */ template<typename Range1T, typename Range2T> inline bool iends_with( const Range1T& Input, const Range2T& Test, const std::locale& Loc=std::locale()) { return ends_with(Input, Test, is_iequal(Loc)); } // contains predicate -----------------------------------------------// //! 'Contains' predicate /*! This predicate holds when the test container is contained in the Input. When the optional predicate is specified, it is used for character-wise comparison. \param Input An input sequence \param Test A test sequence \param Comp An element comparison predicate \return The result of the test \note This function provides the strong exception-safety guarantee */ template<typename Range1T, typename Range2T, typename PredicateT> inline bool contains( const Range1T& Input, const Range2T& Test, PredicateT Comp) { if (empty(Test)) { // Empty range is contained always return true; } // Use the temporary variable to make VACPP happy bool bResult=(first_finder(Test,Comp)(begin(Input), end(Input))); return bResult; } //! 'Contains' predicate /*! \overload */ template<typename Range1T, typename Range2T> inline bool contains( const Range1T& Input, const Range2T& Test) { return contains(Input, Test, is_equal()); } //! 'Contains' predicate ( case insensitive ) /*! This predicate holds when the test container is contained in the Input. Elements are compared case insensitively. \param Input An input sequence \param Test A test sequence \param Loc A locale used for case insensitive comparison \return The result of the test \note This function provides the strong exception-safety guarantee */ template<typename Range1T, typename Range2T> inline bool icontains( const Range1T& Input, const Range2T& Test, const std::locale& Loc=std::locale()) { return contains(Input, Test, is_iequal(Loc)); } // equals predicate -----------------------------------------------// //! 'Equals' predicate /*! This predicate holds when the test container is equal to the input container i.e. all elements in both containers are same. When the optional predicate is specified, it is used for character-wise comparison. \param Input An input sequence \param Test A test sequence \param Comp An element comparison predicate \return The result of the test \note This is a two-way version of \c std::equal algorithm \note This function provides the strong exception-safety guarantee */ template<typename Range1T, typename Range2T, typename PredicateT> inline bool equals( const Range1T& Input, const Range2T& Test, PredicateT Comp) { typedef BOOST_STRING_TYPENAME range_const_iterator<Range1T>::type Iterator1T; typedef BOOST_STRING_TYPENAME range_const_iterator<Range2T>::type Iterator2T; Iterator1T InputEnd=end(Input); Iterator2T TestEnd=end(Test); Iterator1T it=begin(Input); Iterator2T pit=begin(Test); for(; it!=InputEnd && pit!=TestEnd; ++it,++pit) { if( !(Comp(*it,*pit)) ) return false; } return (pit==TestEnd) && (it==InputEnd); } //! 'Equals' predicate /*! \overload */ template<typename Range1T, typename Range2T> inline bool equals( const Range1T& Input, const Range2T& Test) { return equals(Input, Test, is_equal()); } //! 'Equals' predicate ( case insensitive ) /*! This predicate holds when the test container is equal to the input container i.e. all elements in both containers are same. Elements are compared case insensitively. \param Input An input sequence \param Test A test sequence \param Loc A locale used for case insensitive comparison \return The result of the test \note This is a two-way version of \c std::equal algorithm \note This function provides the strong exception-safety guarantee */ template<typename Range1T, typename Range2T> inline bool iequals( const Range1T& Input, const Range2T& Test, const std::locale& Loc=std::locale()) { return equals(Input, Test, is_iequal(Loc)); } // lexicographical_compare predicate -----------------------------// //! Lexicographical compare predicate /*! This predicate is an overload of std::lexicographical_compare for range arguments It check whether the first argument is lexicographically less then the second one. If the optional predicate is specified, it is used for character-wise comparison \param Arg1 First argument \param Arg2 Second argument \param Pred Comparison predicate \return The result of the test \note This function provides the strong exception-safety guarantee */ template<typename Range1T, typename Range2T, typename PredicateT> inline bool lexicographical_compare( const Range1T& Arg1, const Range2T& Arg2, PredicateT Pred) { return std::lexicographical_compare( begin(Arg1), end(Arg1), begin(Arg2), end(Arg2), Pred); } //! Lexicographical compare predicate /*! \overload */ template<typename Range1T, typename Range2T> inline bool lexicographical_compare( const Range1T& Arg1, const Range2T& Arg2) { return std::lexicographical_compare( begin(Arg1), end(Arg1), begin(Arg2), end(Arg2), is_less()); } //! Lexicographical compare predicate (case-insensitive) /*! This predicate is an overload of std::lexicographical_compare for range arguments. It check whether the first argument is lexicographically less then the second one. Elements are compared case insensitively \param Arg1 First argument \param Arg2 Second argument \return The result of the test \note This function provides the strong exception-safety guarantee */ template<typename Range1T, typename Range2T> inline bool ilexicographical_compare( const Range1T& Arg1, const Range2T& Arg2) { return std::lexicographical_compare( begin(Arg1), end(Arg1), begin(Arg2), end(Arg2), is_iless()); } // all predicate -----------------------------------------------// //! 'All' predicate /*! This predicate holds it all its elements satisfy a given condition, represented by the predicate. \param Input An input sequence \param Pred A predicate \return The result of the test \note This function provides the strong exception-safety guarantee */ template<typename RangeT, typename PredicateT> inline bool all( const RangeT& Input, PredicateT Pred) { typedef BOOST_STRING_TYPENAME range_const_iterator<RangeT>::type Iterator1T; Iterator1T InputEnd=end(Input); for( Iterator1T It=begin(Input); It!=InputEnd; ++It) { if (!Pred(*It)) return false; } return true; } } // namespace algorithm // pull names to the boost namespace using algorithm::starts_with; using algorithm::istarts_with; using algorithm::ends_with; using algorithm::iends_with; using algorithm::contains; using algorithm::icontains; using algorithm::equals; using algorithm::iequals; using algorithm::all; using algorithm::lexicographical_compare; using algorithm::ilexicographical_compare; } // namespace boost #endif // BOOST_STRING_PREDICATE_HPP
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 463 ] ] ]
22bb3099bc55e541dd9cc882d8c2336d2857442a
b6cdddcfcd908188888a3864b1f0becf0ee2ceee
/QtApp/SaWatch/src/SaWatch.cpp
42fa3fa2d6bad8d9ff11bce3e598b74300bb14e1
[]
no_license
himanshu2090/syncany
698c37c51a72309154dd454365ffc498e767d450
f60bb2266fc1e99de390171edea890292beee467
refs/heads/master
2021-01-21T07:53:47.966909
2009-05-18T13:13:44
2009-05-18T13:13:44
34,249,471
0
0
null
null
null
null
GB18030
C++
false
false
2,884
cpp
// SaWatch.cpp : Defines the entry point for the console application. // #pragma warning(disable:4786) #pragma warning(disable:4996) #include "SaWatch.h" #include "DWLib.h" #include <windows.h> #include "../3part/NTServiceLib/NTService.cpp" #include "../3part/sqllite3/sqlite3.h" #include <stdio.h> #include <string> #include "../bin/sqlite3.h" #pragma comment (lib,"DWLib.lib") #pragma comment (lib,"sqlite3.lib") ///////////////////////////////////////////////////////////////////////////// // The one and only application object sqlite3* gSqlDB; char* gCurDir; HANDLE hDbMutex; HANDLE hExitEvent; ////////////////////////////////////////////////////////////////////////// void PrintChangesOnScreen(bool IsDir, char ChangeType, char* FileName[]) { switch(ChangeType) { case 'A': if(IsDir) printf("DIR-Added:%s\n",FileName[0]); else printf("FILE-Added:%s\n",FileName[0]); break; case 'M': if(IsDir) printf("DIR-Modified:%s\n",FileName[0]); else printf("FILE-Modified:%s\n",FileName[0]); break; case 'R': if(IsDir) printf("DIR-Removed:%s\n",FileName[0]); else printf("FILE-Removed:%s\n",FileName[0]); break; case 'N': if(IsDir) printf("DIR-Renamed:%s -> %s\n",FileName[0],FileName[1]); else printf("FILE-Renamed:%s -> %s\n",FileName[0],FileName[1]); break; default: break; } } // 实现NT Service框架必须实现的函数 class SaWatchNTService : public CNTService { public: SaWatchNTService() : CNTService("SaWatch"){} int RunService(int argc, char* argv[]) { int rc =0; printf("Service is starting...\n"); hExitEvent = CreateEvent(NULL,0,0,0); RegChangeNotifyCallBack(PrintChangesOnScreen,false); ///程序进入了运行状态; do { //轮询数据库中要监视的目录列表并监视之 int nDirCount = GetWatchingDirCount(); SaWatchingDir** pdirs=NULL; pdirs = (SaWatchingDir**)calloc(sizeof(SaWatchingDir),nDirCount); int nItem = GetWatchingDirList(pdirs,nDirCount); SaWatchingDir* pItem = ((SaWatchingDir*)pdirs); for(int i=0;i<nItem;i++) { EnableWatchDir(pItem->Dir,pItem->IncludeFilter,pItem->ExcludeFilter); pItem++; } if(pdirs) free(pdirs); }while(WAIT_TIMEOUT == WaitForSingleObject(hExitEvent,10000)); //等待退出事件 CloseHandle( hExitEvent); CleanApp(); return rc; } void StopService() { printf("Service is stopping...\n"); SetEvent(hExitEvent); //发信号退出程序 } }; int main(int argc, char* argv[]) { SaWatchNTService *service = new SaWatchNTService(); if (service == NULL) { printf("Error: Service class derived from CNTService doesn't instance, please check your code.\n"); return ERROR_INVALID_FUNCTION; } return service->EnterService(argc, argv); }
[ "ttylikl@1da26e48-1f5d-11de-b56b-c9554f25afe1" ]
[ [ [ 1, 121 ] ] ]
8e921be83abc3efcdae7b6648d11c970a2e84e99
968aa9bac548662b49af4e2b873b61873ba6f680
/imgtools/imgcheck/libimgutils/inc/imagereader.h
ff654456237f1954dbc3baed5e6dc5311ffffcfe
[]
no_license
anagovitsyn/oss.FCL.sftools.dev.build
b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3
f458a4ce83f74d603362fe6b71eaa647ccc62fee
refs/heads/master
2021-12-11T09:37:34.633852
2010-12-01T08:05:36
2010-12-01T08:05:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,601
h
/* * Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "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: * @internalComponent * @released * */ #ifndef IMAGEREADER_H #define IMAGEREADER_H #include "typedefs.h" class TRomNode; /** Base class to read and process the image(ROFS/ROM/E32) @internalComponent @released */ class ImageReader { protected: string iImgFileName; ifstream iInputStream; StringList iExecutableList; StringList iHiddenExeList; unsigned int iImageSize; ExeVsIdDataMap iExeVsIdData; ExeNamesVsDepListMap iImageVsDepList; bool iExeAvailable; public: ImageReader(const char* aFile); virtual ~ImageReader(void); virtual void ReadImage(void) = 0; virtual void ProcessImage(void) = 0; virtual void PrepareExecutableList(void); virtual ExeNamesVsDepListMap& GatherDependencies(void) = 0; virtual void PrepareExeVsIdMap(void) = 0; virtual const ExeVsIdDataMap& GetExeVsIdMap(void) const = 0; const StringList& GetExecutableList(void) const; const StringList& GetHiddenExeList(void) const; const char* ImageName(void) const ; static EImageType ReadImageType(const string aImageName); bool ExecutableAvailable(void); }; #endif //IMAGEREADER_H
[ "none@none" ]
[ [ [ 1, 63 ] ] ]
92f4ab08fdc694c099319714de94b92750fd500b
fad6f9883d4ad2686c196dc532a9ecb9199500ee
/NXP-LPC/CommTest/CommTest/LogData.cpp
779ae4b4181171ae3ed7b1e42623f2a1702511b5
[]
no_license
aquarius20th/nxp-lpc
fe83d6a140d361a1737d950ff728c6ea9a16a1dd
4abfb804daf0ac9c59bd90d879256e7a3c1b2f30
refs/heads/master
2021-01-10T13:54:40.237682
2009-12-22T14:54:59
2009-12-22T14:54:59
48,420,260
0
0
null
null
null
null
GB18030
C++
false
false
5,663
cpp
#include "stdafx.h" #include "LogData.h" #include "LogDataApi.h" #include "LogDataExtApi.h" #pragma comment(lib,"..\\lib\\LogEx.lib") CLogStrMgr g_LogStrMgr; CLogStrMgr::CLogStrMgr() { m_bWriteDB = true; } CLogStrMgr::~CLogStrMgr() { FreeMem( ); } void CLogStrMgr::FreeMem( ) { std::deque<CLogStr *>::iterator iter = m_arrBuffer.begin(); for (; iter != m_arrBuffer.end(); ++iter) { delete *iter; } m_arrBuffer.clear(); for (iter = m_arrFreeBuffer.begin(); iter != m_arrFreeBuffer.end(); ++iter) { delete *iter; } m_arrFreeBuffer.clear(); } BOOL CLogStrMgr::ReleaseBuffer(CLogStr *pBuff) { ASSERT(pBuff); if(pBuff==NULL) return FALSE; std::deque<CLogStr *>::iterator iter; iter = std::find(m_arrBuffer.begin(), m_arrBuffer.end(),pBuff ); if (iter != m_arrBuffer.end()) { m_arrBuffer.erase( iter); } //添加到空闲列表中 if( m_arrFreeBuffer.size() <MAX_LOG_STR_LINE) { m_arrFreeBuffer.push_back( pBuff ); } else { // Delete the buffer. if ( pBuff!=NULL ) delete pBuff; } pBuff=NULL; return TRUE; } /********************************************************************************************************* ** 函数名称: AllocateBuffer ** 函数名称: CLogStrMgr::AllocateBuffer ** ** 功能描述: ** ** 输 入: ** ** 输 出: CLogStr* ** ** 全局变量: ** 调用模块: 无 ** ** 作 者: LiJin ** 日 期: 2009年7月20日 ** 备 注: **------------------------------------------------------------------------------------------------------- ** 修改人: ** 日 期: ** 备 注: **------------------------------------------------------------------------------------------------------ ********************************************************************************************************/ CLogStr* CLogStrMgr::AllocateBuffer( ) { CLogStr *pMsg = NULL; if(!m_arrFreeBuffer.empty()) { pMsg= m_arrFreeBuffer.front(); m_arrFreeBuffer.pop_front(); } if (pMsg == NULL) {//创建一个新的 pMsg= new CLogStr(); } ASSERT(pMsg); if (pMsg == NULL) return NULL; m_arrBuffer.push_back(pMsg); return pMsg; } void CLogStrMgr:: LogString(TCHAR * szModuleName, SYSTEMTIME st, TCHAR * lpszTxt ,int nStrType) { CLogStr *pData = NULL; CSingleLock QueueLock(&m_Lock); QueueLock.Lock( ); if (QueueLock.IsLocked()) { if (m_arrBuffer.size() < MAX_LOG_STR_LINE ) { pData = AllocateBuffer(); if(pData) { // memcpy(&pData->ST,&st,sizeof(st)); memcpy_s(&pData->ST,sizeof(pData->ST),&st,sizeof(st)); // pData->LogStr = lpszTxt; _tcsncpy_s(pData->LogStr,LOG_STR_LEN,lpszTxt,min(LOG_STR_LEN,_tcslen(lpszTxt))); _tcsncpy_s(pData->ModuleName,MODULE_NAME_LEN,szModuleName,min(MODULE_NAME_LEN,_tcslen(szModuleName))); pData->StrType = nStrType; } } } QueueLock.Unlock(); } void CLogStrMgr::LogString(TCHAR * szModuleName, TCHAR * lpszTxt ,int nStrType) { SYSTEMTIME st; GetLocalTime(&st); CLogStr *pData = NULL; CSingleLock QueueLock(&m_Lock); QueueLock.Lock( ); if (QueueLock.IsLocked()) { if (m_arrBuffer.size() < MAX_LOG_STR_LINE ) { pData = AllocateBuffer(); if(pData) { // memcpy(&pData->ST,&st,sizeof(st)); memcpy_s(&pData->ST,sizeof(pData->ST),&st,sizeof(st)); // pData->LogStr = lpszTxt; _tcsncpy_s(pData->LogStr,LOG_STR_LEN,lpszTxt,min(LOG_STR_LEN,_tcslen(lpszTxt))); _tcsncpy_s(pData->ModuleName,MODULE_NAME_LEN,szModuleName,min(MODULE_NAME_LEN,_tcslen(szModuleName))); pData->StrType = nStrType; } } } QueueLock.Unlock(); } int CLogStrMgr::GetLogStr(CLogStr *pBuff ) { ASSERT(pBuff); if (pBuff == NULL) return 0; CLogStr *pTmStr = NULL; CSingleLock QueueLock(&m_Lock); QueueLock.Lock( ); if (QueueLock.IsLocked()) { if (!m_arrBuffer.empty() ) { pTmStr = m_arrBuffer.front(); if(pTmStr) { pBuff->StrType = pTmStr->StrType ; //pBuff->LogStr = pTmStr->LogStr; memcpy(&pBuff->ST,&pTmStr->ST,sizeof(pTmStr->ST)); _tcsncpy_s(pBuff->LogStr,LOG_STR_LEN,pTmStr->LogStr,min(LOG_STR_LEN,_tcslen(pTmStr->LogStr))); } delete pTmStr; m_arrBuffer.pop_front(); } else { QueueLock.Unlock(); return FALSE; } } QueueLock.Unlock(); return TRUE; } void EnableWriteDB(bool bFlag) { g_LogStrMgr.m_bWriteDB = bFlag; } void LogString( TCHAR* lpszTxt ,int nStrType) { TCHAR szModuleName [] = _T("MAIN"); g_LogStrMgr.LogString(szModuleName, lpszTxt,nStrType); if (g_LogStrMgr.m_bWriteDB) { LogStringEx(szModuleName,lpszTxt,nStrType); } } void LogStringTm( SYSTEMTIME st, TCHAR* lpszTxt ,int nStrType) { TCHAR szModuleName [] = _T("MAIN"); g_LogStrMgr.LogString(szModuleName,st,lpszTxt,nStrType); if (g_LogStrMgr.m_bWriteDB) { LogStringTmEx(szModuleName,st,lpszTxt,nStrType); } } bool RegisterLog(TCHAR *szModuleName ) { return ::RegisterLogEx(szModuleName); } void UnregisterLog( TCHAR *szModuleName ) { ::UnregisterLogEx(szModuleName); } void AppLogString( TCHAR *szModuleName, TCHAR *lpszTxt, int nStrType ) { g_LogStrMgr.LogString(szModuleName, lpszTxt,nStrType); if (g_LogStrMgr.m_bWriteDB) { LogStringEx(szModuleName,lpszTxt,nStrType); } } void AppLogStringTm (TCHAR *szModuleName,SYSTEMTIME st, TCHAR* lpszTxt ,int nStrType) { g_LogStrMgr.LogString(szModuleName,st,lpszTxt,nStrType); if (g_LogStrMgr.m_bWriteDB) { LogStringTmEx(szModuleName,st,lpszTxt,nStrType); } }
[ "lijin.unix@13de9a6c-71d3-11de-b374-81e7cb8b6ca2" ]
[ [ [ 1, 249 ] ] ]
5d218ca1ba7bd6a4dc6187f343a0bd07f15488ac
20777f7a9f3d2f82fd9e0b66826458e2ac42a0b0
/mila/lexan.cpp
066f56dc598c09778b70cb41434e7cd25851b1eb
[]
no_license
cejkato2/MI-GEN
bd85751a8d3fc771363d2ea7c99580b6beec5c79
cc7ddb9bd717a977fbd9e611a1daf4a72386b287
refs/heads/master
2020-05-03T16:42:41.988574
2011-06-03T07:49:25
2011-06-03T07:49:25
1,828,430
0
0
null
null
null
null
UTF-8
C++
false
false
3,719
cpp
/* lexan.cpp */ #include "lexan.h" #include "vstup.h" #include <stdlib.h> #include <string.h> #include <stdio.h> LexSymbol Symb; char Ident[MaxLenIdent]; /* atribut symbolu IDENT */ int Cislo; /* atribut symbolu NUMB */ static int Znak; // vstupni znak static char Vstup; // vstupni symbol void CtiVstup(void) { Znak = CtiZnak(); if (Znak>='A' && Znak<='Z' || Znak>='a' && Znak<='z') Vstup = 'p'; else if (Znak>='0' && Znak<='9') Vstup = 'c'; else if (Znak == EOF) Vstup = 'e'; else if (Znak <= ' ') Vstup = 'm'; else Vstup = Znak; } const struct {char* slovo; LexSymbol symb;} TabKS[] = { {"var", kwVAR}, {"const", kwCONST}, {"begin", kwBEGIN}, {"end", kwEND}, {"if", kwIF}, {"then", kwTHEN}, {"else", kwELSE}, {"while", kwWHILE}, {"do", kwDO}, {"write", kwWRITE}, {NULL, EOI} }; LexSymbol KlicoveSlovo(char* id) { int i = 0; while (TabKS[i].slovo) if (strcmp(id, TabKS[i].slovo)==0) return TabKS[i].symb; else i++; return IDENT; } void Chyba(const char* text) { printf("\n%s\n", text); exit(1); } const char *LexSymboly[] = { "ident", "cislo", "+", "-", "*", "/", "=", "<>", "<", ">", "<=", ">=", "(", ")", ":=", ",", ";", "var", "const", "begin", "end", "if", "then", "else", "while", "do", "write" }; void ChybaSrovnani(LexSymbol s) { printf("chyba pri srovnani, ocekava se %s\n", LexSymboly[s]); exit(1); } void CtiSymb(void) { int delkaId; q0: while (Vstup=='m') CtiVstup(); switch (Vstup) { case 'e': Symb = EOI; break; case '{': CtiVstup(); while (Vstup!='}' && Vstup!='e') CtiVstup(); if (Vstup=='e') Chyba("neocekavany konec souboru v komentari"); else { CtiVstup(); goto q0; } case 'p': delkaId = 1; Ident[0] = Znak; CtiVstup(); while (Vstup=='p' || Vstup=='c') { Ident[delkaId] = Znak; delkaId++; CtiVstup(); } Ident[delkaId] = 0; Symb = KlicoveSlovo(Ident); break; case 'c': Cislo = Znak - '0'; CtiVstup(); while (Vstup=='c') { Cislo = 10 * Cislo + Znak - '0'; CtiVstup(); } Symb = NUMB; break; case ',': Symb = COMMA; CtiVstup(); break; case ';': Symb = SEMICOLON; CtiVstup(); break; case '+': Symb = PLUS; CtiVstup(); break; case '-': Symb = MINUS; CtiVstup(); break; case '*': Symb = TIMES; CtiVstup(); break; case '/': Symb = DIVIDE; CtiVstup(); break; case '=': Symb = EQ; CtiVstup(); break; case '<': CtiVstup(); switch (Vstup) { case '>': Symb = NEQ; CtiVstup(); break; case '=': Symb = LTE; CtiVstup(); break; default: Symb = LT; } break; case '>': CtiVstup(); if (Vstup=='=') { Symb = GTE; CtiVstup(); } else Symb = GT; break; case '(': Symb = LPAR; CtiVstup(); break; case ')': Symb = RPAR; CtiVstup(); break; case ':': CtiVstup(); if (Vstup=='=') { Symb = ASSGN; CtiVstup(); break; } default: Chyba("nedovoleny znak"); } } void InitLexan(char *jmeno) { InitVstup(jmeno); CtiVstup(); }
[ [ [ 1, 189 ] ] ]
83deacfcdf42cae36c9fc8a7f3b539a14959a433
629e4fdc23cb90c0144457e994d1cbb7c6ab8a93
/lib/graphics/texture/texture.cpp
758432c314b4741df084ecf66f462b7cdc28976e
[]
no_license
akin666/ice
4ed846b83bcdbd341b286cd36d1ef5b8dc3c0bf2
7cfd26a246f13675e3057ff226c17d95a958d465
refs/heads/master
2022-11-06T23:51:57.273730
2011-12-06T22:32:53
2011-12-06T22:32:53
276,095,011
0
0
null
null
null
null
UTF-8
C++
false
false
1,339
cpp
/* * Texture.cpp * * Created on: 25.7.2011 * Author: akin */ #include "texture.h" namespace ice { Texture::Texture() : parent(NULL) { } Texture::Texture( const Texture& other ) : parent( other.parent ), pixelDimension( other.pixelDimension ), pixelPosition( other.pixelPosition) { } Texture::~Texture() { } int Texture::getWidth() const { return pixelDimension.x; } int Texture::getHeight() const { return pixelDimension.y; } glm::ivec2& Texture::getDimension() { return pixelDimension; } glm::ivec2& Texture::getPosition() { return pixelPosition; } glm::vec2 Texture::getMax() { glm::vec2 max( pixelPosition + pixelDimension ); glm::vec2 div( parent->getDimension() ); return max / div; } glm::vec2 Texture::getMin() { glm::vec2 min( pixelPosition ); glm::vec2 div( parent->getDimension() ); return min / div; } GTexture *Texture::getG() { return parent; } void Texture::bind() { parent->bind(); } void Texture::release() { parent->release(); } void Texture::setTexture( GTexture *texture ) { parent = texture; } unsigned int Texture::getId() const { if( parent == NULL ) return 0; return parent->getTextureId(); } } /* namespace ice */
[ "akin@lich" ]
[ [ [ 1, 90 ] ] ]
40d651f8d8acc6bd550152ca71e25cd5c4059635
6f796044ae363f9ca58c66423c607e3b59d077c7
/source/GuiBase/TextRender.h
b1ec6eb765ff06dcd126971ce3660f2873baeb38
[]
no_license
Wiimpathy/bluemsx-wii
3a68d82ac82268a3a1bf1b5ca02115ed5e61290b
fde291e57fe93c0768b375a82fc0b62e645bd967
refs/heads/master
2020-05-02T22:46:06.728000
2011-10-06T20:57:54
2011-10-06T20:57:54
178,261,485
2
0
null
2019-03-28T18:32:30
2019-03-28T18:32:30
null
UTF-8
C++
false
false
2,045
h
/*************************************************************** * * Copyright (C) 2008-2011 Tim Brugman * * Based on code of "DragonMinded" * * This file may be licensed under the terms of of the * GNU General Public License Version 2 (the ``GPL''). * * Software distributed under the License is distributed * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either * express or implied. See the GPL for the specific language * governing rights and limitations. * * You should have received a copy of the GPL along with this * program. If not, go to http://www.gnu.org/licenses/gpl.html * or write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************/ #ifndef __TEXTRENDER_H #define __TEXTRENDER_H #define DEFAULT_X 0 #define DEFAULT_Y 0 #define DEFAULT_Y_CUSHION 2 #define DEFAULT_TAB_SPACE 50 #include "GuiAtom.h" #include <stdint.h> #include <string> #include <ft2build.h> #include FT_FREETYPE_H #include <gccore.h> using std::string; class TextRender : public GuiAtom { public: TextRender(); ~TextRender(); void SetFont(string font); void SetFont(const unsigned char* font, int size); void SetColor(GXColor c); void SetSize(int s); void SetYSpacing(int s); void SetBuffer(uint8_t *buf, int width, int height, int bufwidth); void RenderSimple(const char *out, bool center = false, int *sx = NULL, int *sy = NULL); void Render(const char *fmt, ...); void GetTextSize(int *sx, int *sy, bool center, const char *fmt, ...); private: void Blit(FT_Bitmap *bmp, int bmpWidth, int bmpHeight); FT_Library m_library; FT_Face m_face; uint8_t *m_buf; int m_width; int m_height; int m_bufwidth; int m_fontheight; int m_yspacing; GXColor m_color; }; #endif
[ "[email protected]", "timbrug@c2eab908-c631-11dd-927d-974589228060" ]
[ [ [ 1, 20 ], [ 30, 31 ], [ 40, 40 ], [ 42, 49 ], [ 52, 54 ], [ 56, 68 ] ], [ [ 21, 29 ], [ 32, 39 ], [ 41, 41 ], [ 50, 51 ], [ 55, 55 ], [ 69, 72 ] ] ]
0394245aed860563f77130d03acafb5221493bfc
d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546
/hlsdk-2.3-p3/Quake 4 SDK/Quake 4 SDK/source/mpgame/mp/GameState.cpp
566e436c4b3a5eea7b9c5899017d322056863def
[]
no_license
joropito/amxxgroup
637ee71e250ffd6a7e628f77893caef4c4b1af0a
f948042ee63ebac6ad0332f8a77393322157fa8f
refs/heads/master
2021-01-10T09:21:31.449489
2010-04-11T21:34:27
2010-04-11T21:34:27
47,087,485
1
0
null
null
null
null
UTF-8
C++
false
false
97,027
cpp
//---------------------------------------------------------------- // GameState.cpp // // Copyright 2002-2005 Raven Software //---------------------------------------------------------------- #include "../../idlib/precompiled.h" #pragma hdrstop #include "GameState.h" /* =============================================================================== rvGameState Game state info for deathmatch, team deathmatch =============================================================================== */ /* ================ rvGameState::rvGameState ================ */ rvGameState::rvGameState( bool allocPrevious ) { Clear(); if( allocPrevious ) { previousGameState = new rvGameState( false ); } else { previousGameState = NULL; } trackPrevious = allocPrevious; } /* ================ rvGameState::~rvGameState ================ */ rvGameState::~rvGameState( void ) { Clear(); delete previousGameState; previousGameState = NULL; } /* ================ rvGameState::Clear ================ */ void rvGameState::Clear( void ) { currentState = INACTIVE; nextState = INACTIVE; nextStateTime = 0; fragLimitTimeout = 0; } /* ================ rvGameState::SendState ================ */ void rvGameState::SendState( const idMessageSender &sender, int clientNum ) { idBitMsg outMsg; byte msgBuf[MAX_GAME_MESSAGE_SIZE]; assert( (gameLocal.isServer || gameLocal.isRepeater) && trackPrevious ); if( clientNum == -1 && (*this) == (*previousGameState) ) { return; } outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_GAMESTATE ); WriteState( outMsg ); sender.Send( outMsg ); // don't update the state if we are working for a single client if ( clientNum == -1 ) { outMsg.ReadByte(); // pop off the msg ID ReceiveState( outMsg ); } } /* =============== rvGameState::WriteState =============== */ void rvGameState::WriteState( idBitMsg &msg ) { PackState( msg ); } /* ================ rvGameState::SendInitialState ================ */ void rvGameState::SendInitialState( const idMessageSender &sender, int clientNum ) { rvGameState* previousState = previousGameState; rvGameState invalidState; previousGameState = &invalidState; SendState( sender, clientNum ); previousGameState = previousState; } /* ================ rvGameState::ReceiveState ================ */ void rvGameState::ReceiveState( const idBitMsg& msg ) { if ( !BaseUnpackState( msg ) ) { return; } if ( gameLocal.localClientNum >= 0 ) { GameStateChanged(); } (*previousGameState) = (*this); } /* ================ rvGameState::PackState ================ */ void rvGameState::PackState( idBitMsg& outMsg ) { // server and client changing their rvGameState subclass by guesswork // you can't rely on it being in sync at all times, so read and verify the type first outMsg.WriteByte( gameLocal.gameType ); // for now, we only transmit 3 bytes. If we need to sync more data, we should // only transmit the diff outMsg.WriteByte( currentState ); outMsg.WriteByte( nextState ); outMsg.WriteLong( nextStateTime ); } /* ================ rvGameState::BaseUnpackState ================ */ bool rvGameState::BaseUnpackState( const idBitMsg& inMsg ) { gameType_t t = (gameType_t)inMsg.ReadByte(); if ( t != gameLocal.gameType ) { common->Warning( "rvGameState::UnpackState: client gametype (%d) is out of sync with server (%d). Ignoring", gameLocal.gameType, t ); return false; } currentState = (mpGameState_t)inMsg.ReadByte(); nextState = (mpGameState_t)inMsg.ReadByte(); nextStateTime = inMsg.ReadLong(); return true; } /* ================ rvGameState::GameStateChanged ================ */ void rvGameState::GameStateChanged( void ) { idPlayer* player = gameLocal.GetLocalPlayer(); if ( !player ) { if ( gameLocal.IsServerDemoPlaying() && gameLocal.GetDemoFollowClient() >= 0 ) { player = static_cast< idPlayer * >( gameLocal.entities[ gameLocal.GetDemoFollowClient() ] ); } } if ( !player ) { gameLocal.Warning( "rvGameState::GameStateChanged() - NULL local player\n" ) ; return; } // Check for a currentState change if( currentState != previousGameState->currentState ) { if( currentState == WARMUP ) { if( gameLocal.gameType != GAME_TOURNEY ) { player->GUIMainNotice( common->GetLocalizedString( "#str_107706" ), true ); } soundSystem->SetActiveSoundWorld( true ); // reset stats on the client-side if( gameLocal.isClient ) { statManager->Init(); } } else if( currentState == COUNTDOWN ) { if( gameLocal.gameType != GAME_TOURNEY ) { player->GUIMainNotice( common->GetLocalizedString( "#str_107706" ), true ); } soundSystem->SetActiveSoundWorld(true); if( gameLocal.gameType != GAME_TOURNEY && previousGameState->currentState != INACTIVE ) { gameLocal.mpGame.RemoveAnnouncerSound( AS_GENERAL_PREPARE_TO_FIGHT ); gameLocal.mpGame.RemoveAnnouncerSound( AS_GENERAL_THREE ); gameLocal.mpGame.RemoveAnnouncerSound( AS_GENERAL_TWO ); gameLocal.mpGame.RemoveAnnouncerSound( AS_GENERAL_ONE ); gameLocal.mpGame.ScheduleAnnouncerSound( AS_GENERAL_PREPARE_TO_FIGHT, gameLocal.time ); gameLocal.mpGame.ScheduleAnnouncerSound( AS_GENERAL_THREE, nextStateTime - 3000 ); gameLocal.mpGame.ScheduleAnnouncerSound( AS_GENERAL_TWO, nextStateTime - 2000 ); gameLocal.mpGame.ScheduleAnnouncerSound( AS_GENERAL_ONE, nextStateTime - 1000 ); } } else if( currentState == GAMEON ) { if ( !player->vsMsgState ) { player->GUIMainNotice( "" ); player->GUIFragNotice( "" ); } else { player->vsMsgState = false; } if( gameLocal.gameType != GAME_TOURNEY ) { gameLocal.mpGame.ScheduleAnnouncerSound( AS_GENERAL_FIGHT, gameLocal.time ); } //if ( gameLocal.gameType == GAME_DEADZONE ) { // if ( player->team == TEAM_MARINE ) // gameLocal.mpGame.ScheduleAnnouncerSound( AS_TEAM_JOIN_MARINE, gameLocal.time ); // else // gameLocal.mpGame.ScheduleAnnouncerSound( AS_TEAM_JOIN_STROGG, gameLocal.time ); //} cvarSystem->SetCVarString( "ui_ready", "Not Ready" ); soundSystem->SetActiveSoundWorld( true ); // clear stats on client if( gameLocal.isClient ) { statManager->Init(); } } else if( currentState == SUDDENDEATH ) { soundSystem->SetActiveSoundWorld( true ); gameLocal.mpGame.ScheduleAnnouncerSound( AS_GENERAL_SUDDEN_DEATH, gameLocal.time ); gameLocal.GetLocalPlayer()->GUIMainNotice( common->GetLocalizedString( "#str_104287" ) ); } else if( currentState == GAMEREVIEW ) { // RITUAL BEGIN gameLocal.mpGame.isBuyingAllowedRightNow = false; // RITUAL END gameLocal.mpGame.ShowStatSummary(); } gameLocal.mpGame.ScheduleTimeAnnouncements( ); } } /* ================ rvGameState::SpawnDeadZonePowerup ================ */ void rvGameState::SpawnDeadZonePowerup( void ) { idEntity *ent; riDeadZonePowerup* spawnSpot = 0; int count = 0; for ( ent = gameLocal.spawnedEntities.Next(); ent != NULL; ent = ent->spawnNode.Next() ) { // If its not a DeadZone powerup then skip it if ( !ent->IsType( riDeadZonePowerup::GetClassType() ) ) { continue; } // Make sure its the right type first riDeadZonePowerup* flag; flag = static_cast<riDeadZonePowerup*>(ent); if ( flag->powerup != POWERUP_DEADZONE || flag->IsVisible() ) { continue; } if ( flag->spawnArgs.GetBool("dropped", "0") && !flag->IsVisible() ) { flag->PostEventMS( &EV_Remove, 0 ); } else { count++; if ( !(rand()%(count)) ) { spawnSpot = flag; } } } if ( spawnSpot ) { spawnSpot->PostEventMS( &EV_RespawnItem, 0 ); spawnSpot->srvReady = 1; // Go ahead and set this, so the loop works properly. } else { gameLocal.Error("Couldn't find enough dead zone spawn spots for the number of dead zone artifacts specified in the map def!"); } } /* ================ rvGameState::Run ================ */ void rvGameState::Run( void ) { if ( currentState == INACTIVE ) { #ifdef _XENON if(Live()->RoundsPlayed() < cvarSystem->GetCVarInteger("si_matchRounds")) #endif { NewState( WARMUP ); } } if ( nextState != INACTIVE && gameLocal.time > nextStateTime ) { NewState( nextState ); nextState = INACTIVE; } switch( currentState ) { case INACTIVE: break; case GAMEREVIEW: { if ( nextState == INACTIVE ) { statManager->SendAllStats(); nextState = NEXTGAME; // allow a little extra time in tourney since we have to display end brackets if( gameLocal.gameType == GAME_TOURNEY ) { nextStateTime = gameLocal.time + 5000 + (1000 * cvarSystem->GetCVarInteger( "g_gameReviewPause" )); } else { nextStateTime = gameLocal.time + (1000 * cvarSystem->GetCVarInteger( "g_gameReviewPause" )); } } break; } case NEXTGAME: { // the core will force a restart at 12 hours max // but it's nicer if we can wait for a game transition to perform the restart so the game is not interrupted // perform a restart once we are past 8 hours if ( networkSystem->ServerGetServerTime() > 8*60*60*1000 ) { gameLocal.sessionCommand = "nextMap"; return; } if ( nextState == INACTIVE ) { // game rotation, new map, gametype etc. // only cycle in tourney if tourneylimit is higher than the specified value if( gameLocal.gameType != GAME_TOURNEY || ((rvTourneyGameState*)this)->GetTourneyCount() >= gameLocal.serverInfo.GetInt( "si_tourneyLimit" ) ) { // whether we switch to the next map or not, reset the tourney count if( gameLocal.gameType == GAME_TOURNEY ) { ((rvTourneyGameState*)this)->SetTourneyCount( 0 ); } if ( gameLocal.NextMap() ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, "serverMapRestart\n" ); return; } } NewState( WARMUP ); // put everyone back in from endgame spectate for ( int i = 0; i < gameLocal.numClients; i++ ) { idEntity *ent = gameLocal.entities[ i ]; if ( ent && ent->IsType( idPlayer::GetClassType() ) ) { if ( !static_cast< idPlayer * >( ent )->wantSpectate ) { gameLocal.mpGame.CheckRespawns( static_cast<idPlayer *>( ent ) ); } } } } break; } case WARMUP: { // check to see if we actually want to do a warmup, or if we fall through //RAVEN BEGIN //asalmon: Live has its own rules for ending warm up #ifdef _XENON if(!Live()->RollCall()) { break; } #endif //RAVEN END if( !gameLocal.serverInfo.GetBool( "si_warmup" ) && gameLocal.gameType != GAME_TOURNEY ) { // tourney always needs a warmup, to ensure that at least 2 players get seeded for the tournament. NewState( GAMEON ); } else if ( gameLocal.mpGame.AllPlayersReady() ) { NewState( COUNTDOWN ); nextState = GAMEON; nextStateTime = gameLocal.time + 1000 * gameLocal.serverInfo.GetInt( "si_countDown" ); } break; } case COUNTDOWN: { break; } } } /* ================ rvGameState::NewState ================ */ void rvGameState::NewState( mpGameState_t newState ) { idBitMsg outMsg; byte msgBuf[MAX_GAME_MESSAGE_SIZE]; int i; assert( (newState != currentState) && gameLocal.isServer ); switch( newState ) { case WARMUP: { // asalmon: start the stat manager as soon as the game starts statManager->Init(); statManager->BeginGame(); // if shuffle is on, shuffle the teams around if( gameLocal.IsTeamGame() && gameLocal.serverInfo.GetBool( "si_shuffle" ) ) { gameLocal.mpGame.ShuffleTeams(); } // allow damage in warmup //gameLocal.mpGame.EnableDamage( false ); //asalmon: clear out lingering team scores. gameLocal.mpGame.ClearTeamScores(); if( gameLocal.gameType != GAME_TOURNEY ) { for( i = 0; i < gameLocal.numClients; i++ ) { idEntity *ent = gameLocal.entities[ i ]; if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { continue; } ((idPlayer*)ent)->JoinInstance( 0 ); } } break; } case GAMEON: { // allow damage in warmup //gameLocal.mpGame.EnableDamage( true ); gameLocal.LocalMapRestart(); // RITUAL BEGIN // squirrel: Buying & Deadzone for( i = 0; i < gameLocal.numClients; i++ ) { idEntity *ent = gameLocal.entities[ i ]; if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { continue; } idPlayer* player = static_cast< idPlayer* >(ent); player->inventory.carryOverWeapons = 0; player->ResetCash(); // If the buy menu is up during a server restart, // make sure to refresh it. gameLocal.mpGame.RedrawLocalBuyMenu(); } if ( gameLocal.mpGame.IsBuyingAllowedInTheCurrentGameMode() ) { gameLocal.mpGame.isBuyingAllowedRightNow = true; // Give all the clients full ammo since this is the start of the round. for( int i = 0; i < gameLocal.numClients; i++ ) { idPlayer* p = (idPlayer*)gameLocal.entities[ i ]; if( p == NULL || !p->IsType( idPlayer::GetClassType() ) ) continue; GiveStuffToPlayer(p, "ammo", ""); p->inventory.weapons |= p->inventory.carryOverWeapons & CARRYOVER_WEAPONS_MASK; } } if ( gameLocal.gameType == GAME_DEADZONE ) { // Spawn the powerups! const char *mapName = gameLocal.serverInfo.GetString( "si_map" ); const idDict *mapDict = fileSystem->GetMapDecl( mapName ); if ( mapDict ) gameLocal.mpGame.deadZonePowerupCount = mapDict->GetInt("deadZonePowerupCount", "3"); else gameLocal.mpGame.deadZonePowerupCount = 3; int pcount = gameLocal.mpGame.deadZonePowerupCount; if ( pcount == -1 ) pcount = 3; // Good default. pcount = idMath::ClampInt(1, 12, pcount); for ( int i = 0; i<pcount; i++ ) { SpawnDeadZonePowerup(); } } // RITUAL END // asalmon: reset the stats when the warmup period is over statManager->Init(); statManager->BeginGame(); outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_RESTART ); outMsg.WriteBits( 0, 1 ); networkSystem->ServerSendReliableMessage( -1, outMsg ); gameLocal.mpGame.SetMatchStartedTime( gameLocal.time ); fragLimitTimeout = 0; // write server initial reliable messages to give everyone new base for( i = 0; i < MAX_CLIENTS; i++ ) { // dont send this to server - we have all the data already and this will // just trigger extra gamestate detection if ( gameLocal.entities[ i ] && i != gameLocal.localClientNum ) { gameLocal.mpGame.ServerWriteInitialReliableMessages( serverReliableSender.To( i, true ), i ); } } if ( gameLocal.isRepeater ) { gameLocal.mpGame.ServerWriteInitialReliableMessages( repeaterReliableSender.To( -1 ), ENTITYNUM_NONE ); } for( i = 0; i < gameLocal.numClients; i++ ) { idEntity *ent = gameLocal.entities[ i ]; if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { continue; } idPlayer *p = static_cast<idPlayer *>( ent ); p->SetLeader( false ); // don't carry the flag from previous games gameLocal.mpGame.SetPlayerScore( p, 0 ); gameLocal.mpGame.SetPlayerTeamScore( p, 0 ); // in normal gameplay modes, spawn the player in. For tourney, the tourney manager handles spawning if( gameLocal.gameType != GAME_TOURNEY ) { p->JoinInstance( 0 ); // in team games, let UserInfoChanged() spawn people on the right teams if( !gameLocal.IsTeamGame() || p->team != -1 ) { p->ServerSpectate( static_cast<idPlayer *>(ent)->wantSpectate ); } } } gameLocal.mpGame.ClearTeamScores(); cvarSystem->SetCVarString( "ui_ready", "Not Ready" ); gameLocal.mpGame.switchThrottle[ 1 ] = 0; // passby the throttle break; } case GAMEREVIEW: { statManager->EndGame(); //statManager->DebugPrint(); nextState = INACTIVE; // used to abort a game. cancel out any upcoming state change for( i = 0; i < gameLocal.numClients; i++ ) { idEntity *ent = gameLocal.entities[ i ]; // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { // RAVEN END continue; } // RITUAL BEGIN // squirrel: support for Buying in multiplayer idPlayer* player = static_cast< idPlayer* >(ent); player->inventory.carryOverWeapons = 0; player->ResetCash(); player->forcedReady = false; player->ServerSpectate( true ); static_cast< idPlayer *>( ent )->forcedReady = false; static_cast<idPlayer *>(ent)->ServerSpectate( true ); // RITUAL END } break; } case SUDDENDEATH: { gameLocal.mpGame.PrintMessageEvent( -1, MSG_SUDDENDEATH ); //unmark all leaders, so we make sure we only let the proper people respawn for( i = 0; i < gameLocal.numClients; i++ ) { idEntity *ent = gameLocal.entities[ i ]; if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { continue; } idPlayer *p = static_cast<idPlayer *>( ent ); p->SetLeader( false ); // don't carry the flag from previous games } // only restart in team games if si_suddenDeathRestart is set. if( !gameLocal.IsTeamGame() || gameLocal.serverInfo.GetBool( "si_suddenDeathRestart" ) ) { gameLocal.LocalMapRestart(); } // Mark everyone tied for the lead as leaders i = 0; idPlayer* leader = gameLocal.mpGame.GetRankedPlayer( i ); if( leader ) { int highScore = gameLocal.mpGame.GetScore( leader ); while( leader ) { if( gameLocal.mpGame.GetScore( leader ) < highScore ) { break; } leader->SetLeader( true ); leader = gameLocal.mpGame.GetRankedPlayer( ++i ); } } // RITUAL BEGIN // squirrel: Buying & Deadzone /// Reset players' cash and inventory if si_suddenDeathRestart is set if( !gameLocal.IsTeamGame() || gameLocal.serverInfo.GetBool( "si_suddenDeathRestart" ) ) { for( i = 0; i < gameLocal.numClients; i++ ) { idEntity *ent = gameLocal.entities[ i ]; if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { continue; } idPlayer* player = static_cast< idPlayer* >(ent); player->inventory.carryOverWeapons = 0; player->ResetCash(); } } if ( gameLocal.mpGame.IsBuyingAllowedInTheCurrentGameMode() ) { gameLocal.mpGame.isBuyingAllowedRightNow = true; // Give all the clients full ammo since this is the start of the round. for( int i = 0; i < gameLocal.numClients; i++ ) { idPlayer* p = (idPlayer*)gameLocal.entities[ i ]; if( p == NULL || !p->IsType( idPlayer::GetClassType() ) ) continue; GiveStuffToPlayer(p, "ammo", ""); p->inventory.weapons |= p->inventory.carryOverWeapons & CARRYOVER_WEAPONS_MASK; } } if ( gameLocal.gameType == GAME_DEADZONE ) { // Spawn the powerups! const char *mapName = gameLocal.serverInfo.GetString( "si_map" ); const idDict *mapDict = fileSystem->GetMapDecl( mapName ); if ( mapDict ) gameLocal.mpGame.deadZonePowerupCount = mapDict->GetInt("deadZonePowerupCount", "3"); else gameLocal.mpGame.deadZonePowerupCount = 3; int pcount = gameLocal.mpGame.deadZonePowerupCount; if ( pcount == -1 ) pcount = 3; // Good default. pcount = idMath::ClampInt(1, 12, pcount); for ( int i = 0; i<pcount; i++ ) { SpawnDeadZonePowerup(); } } // RITUAL END if ( gameLocal.gameType == GAME_DM ) { //send all the non-leaders to spectatormode? for( i = 0; i < gameLocal.numClients; i++ ) { idEntity *ent = gameLocal.entities[ i ]; // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { // RAVEN END continue; } if ( static_cast< idPlayer *>( ent )->IsLeader() ) { static_cast<idPlayer *>(ent)->ServerSpectate( false ); continue; } static_cast< idPlayer *>( ent )->forcedReady = false; static_cast<idPlayer *>(ent)->ServerSpectate( true ); } } break; } default: { break; } } currentState = newState; } /* ================ rvGameState::ClientDisconnect ================ */ void rvGameState::ClientDisconnect( idPlayer* player ) { return; } /* ================ rvGameState::Spectate ================ */ void rvGameState::Spectate( idPlayer* player ) { if( player->spectating && player->wantSpectate ) { gameLocal.mpGame.ClearFrags( player->entityNumber ); } return; } /* ================ rvGameState::operator== ================ */ bool rvGameState::operator==( const rvGameState& rhs ) const { return ( ( currentState == rhs.currentState ) && ( nextState == rhs.nextState ) && ( nextStateTime == rhs.nextStateTime ) ); } /* ================ rvGameState::operator!= ================ */ bool rvGameState::operator!=( const rvGameState& rhs ) const { return ( ( currentState != rhs.currentState ) || ( nextState != rhs.nextState ) || ( nextStateTime != rhs.nextStateTime ) ); } /* ================ rvGameState::operator= ================ */ rvGameState& rvGameState::operator=( const rvGameState& rhs ) { currentState = rhs.currentState; nextState = rhs.nextState; nextStateTime = rhs.nextStateTime; return (*this); } /* =============== rvGameState::WriteNetworkInfo =============== */ void rvGameState::WriteNetworkInfo( idFile *file, int clientNum ) { idBitMsg msg; byte msgBuf[ MAX_GAME_MESSAGE_SIZE ]; msg.Init( msgBuf, sizeof( msgBuf ) ); msg.BeginWriting(); WriteState( msg ); file->WriteInt( msg.GetSize() ); file->Write( msg.GetData(), msg.GetSize() ); } /* =============== rvGameState::ReadNetworkInfo =============== */ void rvGameState::ReadNetworkInfo( idFile *file, int clientNum ) { idBitMsg msg; byte msgBuf[ MAX_GAME_MESSAGE_SIZE ]; int size; file->ReadInt( size ); msg.Init( msgBuf, size ); msg.SetSize( size ); file->Read( msg.GetData(), size ); ReceiveState( msg ); } /* =============================================================================== rvDMGameState Game state info for DM =============================================================================== */ rvDMGameState::rvDMGameState( bool allocPrevious ) : rvGameState( allocPrevious ) { trackPrevious = allocPrevious; } void rvDMGameState::Run( void ) { idPlayer* player = NULL; rvGameState::Run(); switch( currentState ) { case GAMEON: { player = gameLocal.mpGame.FragLimitHit(); bool tiedForFirst = false; idPlayer* first = gameLocal.mpGame.GetRankedPlayer( 0 ); idPlayer* second = gameLocal.mpGame.GetRankedPlayer( 1 ); if( player == NULL ) { if( first && second && gameLocal.mpGame.GetScore( first ) == gameLocal.mpGame.GetScore( second ) ) { tiedForFirst = true; } } if ( player ) { // delay between detecting frag limit and ending game. let the death anims play if ( !fragLimitTimeout ) { common->DPrintf( "enter FragLimit timeout, player %d is leader\n", player->entityNumber ); fragLimitTimeout = gameLocal.time + FRAGLIMIT_DELAY; } if ( gameLocal.time > fragLimitTimeout ) { NewState( GAMEREVIEW ); gameLocal.mpGame.PrintMessageEvent( -1, MSG_FRAGLIMIT, player->entityNumber ); } } else if ( fragLimitTimeout ) { // frag limit was hit and cancelled. means the two teams got even during FRAGLIMIT_DELAY // enter sudden death, the next frag leader will win // // jshepard: OR it means that the winner killed himself during the fraglimit delay, and the // game needs to roll on. if( first && second && (gameLocal.mpGame.GetScore( first ) == gameLocal.mpGame.GetScore( second )) ) { //this is a tie... if( gameLocal.mpGame.GetScore( first ) >= gameLocal.serverInfo.GetInt( "si_fragLimit" ) ) { //and it must be tied at fraglimit, so sudden death. NewState( SUDDENDEATH ); } } //otherwise, just keep playing as normal. fragLimitTimeout = 0; } else if ( gameLocal.mpGame.TimeLimitHit() ) { gameLocal.mpGame.PrintMessageEvent( -1, MSG_TIMELIMIT ); if( tiedForFirst ) { // if tied at timelimit hit, goto sudden death fragLimitTimeout = 0; NewState( SUDDENDEATH ); } else { // or just end the game NewState( GAMEREVIEW ); } } else if( tiedForFirst && gameLocal.serverInfo.GetInt( "si_fragLimit" ) > 0 && gameLocal.mpGame.GetScore( first ) >= gameLocal.serverInfo.GetInt( "si_fragLimit" ) ) { // check for the rare case that two players both hit the fraglimit the same frame // two people tied at fraglimit, advance to sudden death after a delay fragLimitTimeout = gameLocal.time + FRAGLIMIT_DELAY; } break; } case SUDDENDEATH: { player = gameLocal.mpGame.FragLeader(); if ( player ) { if ( !fragLimitTimeout ) { common->DPrintf( "enter sudden death FragLeader timeout, player %d is leader\n", player->entityNumber ); fragLimitTimeout = gameLocal.time + FRAGLIMIT_DELAY; } if ( gameLocal.time > fragLimitTimeout ) { NewState( GAMEREVIEW ); gameLocal.mpGame.PrintMessageEvent( -1, MSG_FRAGLIMIT, player->entityNumber ); } } else if ( fragLimitTimeout ) { gameLocal.mpGame.PrintMessageEvent( -1, MSG_HOLYSHIT ); fragLimitTimeout = 0; } break; } } } /* =============================================================================== rvTeamDMGameState Game state info for Team DM =============================================================================== */ rvTeamDMGameState::rvTeamDMGameState( bool allocPrevious ) : rvGameState( allocPrevious ) { trackPrevious = allocPrevious; } void rvTeamDMGameState::Run( void ) { rvGameState::Run(); switch( currentState ) { case GAMEON: { int team = ( ( gameLocal.mpGame.GetScoreForTeam( TEAM_MARINE ) >= gameLocal.serverInfo.GetInt( "si_fragLimit" ) ) ? TEAM_MARINE : ( ( gameLocal.mpGame.GetScoreForTeam( TEAM_STROGG ) >= gameLocal.serverInfo.GetInt( "si_fragLimit" ) ) ? TEAM_STROGG : -1 ) ); if( gameLocal.serverInfo.GetInt( "si_fragLimit" ) <= 0 ) { // no fraglimit team = -1; } bool tiedForFirst = gameLocal.mpGame.GetScoreForTeam( TEAM_MARINE ) == gameLocal.mpGame.GetScoreForTeam( TEAM_STROGG ); if ( team >= 0 && !tiedForFirst ) { if ( !fragLimitTimeout ) { common->DPrintf( "enter FragLimit timeout, team %d is leader\n", team ); fragLimitTimeout = gameLocal.time + FRAGLIMIT_DELAY; } if ( gameLocal.time > fragLimitTimeout ) { NewState( GAMEREVIEW ); gameLocal.mpGame.PrintMessageEvent( -1, MSG_FRAGLIMIT, team ); } } else if ( fragLimitTimeout ) { // frag limit was hit and cancelled. means the two teams got even during FRAGLIMIT_DELAY // enter sudden death, the next frag leader will win // // jshepard: OR it means that the winner killed himself during the fraglimit delay, and the // game needs to roll on. if( tiedForFirst ) { //this is a tie if( gameLocal.mpGame.GetScoreForTeam( TEAM_MARINE ) >= gameLocal.serverInfo.GetInt( "si_fragLimit" ) ) { //and it's tied at the fraglimit. NewState( SUDDENDEATH ); } //not a tie, game on. fragLimitTimeout = 0; } } else if ( gameLocal.mpGame.TimeLimitHit() ) { gameLocal.mpGame.PrintMessageEvent( -1, MSG_TIMELIMIT ); if( tiedForFirst ) { // if tied at timelimit hit, goto sudden death fragLimitTimeout = 0; NewState( SUDDENDEATH ); } else { // or just end the game NewState( GAMEREVIEW ); } } else if( tiedForFirst && team >= 0 ) { // check for the rare case that two teams both hit the fraglimit the same frame // two people tied at fraglimit, advance to sudden death after a delay fragLimitTimeout = gameLocal.time + FRAGLIMIT_DELAY; } break; } case SUDDENDEATH: { int team = gameLocal.mpGame.GetScoreForTeam( TEAM_MARINE ) > gameLocal.mpGame.GetScoreForTeam( TEAM_STROGG ) ? TEAM_MARINE : TEAM_STROGG; bool tiedForFirst = false; if( gameLocal.mpGame.GetScoreForTeam( TEAM_MARINE ) == gameLocal.mpGame.GetScoreForTeam( TEAM_STROGG ) ) { team = -1; tiedForFirst = true; } if ( team >= 0 && !tiedForFirst ) { if ( !fragLimitTimeout ) { common->DPrintf( "enter sudden death FragLeader timeout, team %d is leader\n", team ); fragLimitTimeout = gameLocal.time + FRAGLIMIT_DELAY; } if ( gameLocal.time > fragLimitTimeout ) { NewState( GAMEREVIEW ); gameLocal.mpGame.PrintMessageEvent( -1, MSG_FRAGLIMIT, team ); } } else if ( fragLimitTimeout ) { gameLocal.mpGame.PrintMessageEvent( -1, MSG_HOLYSHIT ); fragLimitTimeout = 0; } break; } } } /* =============================================================================== rvCTFGameState Game state info for CTF =============================================================================== */ /* ================ rvCTFGameState::rvCTFGameState ================ */ rvCTFGameState::rvCTFGameState( bool allocPrevious ) : rvGameState( false ) { Clear(); if( allocPrevious ) { previousGameState = new rvCTFGameState( false ); } else { previousGameState = NULL; } trackPrevious = allocPrevious; } /* ================ rvCTFGameState::Clear ================ */ void rvCTFGameState::Clear( void ) { rvGameState::Clear(); // mekberg: clear previous game state. if ( previousGameState ) { previousGameState->Clear( ); } for( int i = 0; i < TEAM_MAX; i++ ) { flagStatus[ i ].state = FS_AT_BASE; flagStatus[ i ].clientNum = -1; } for( int i = 0; i < MAX_AP; i++ ) { apState[ i ] = AS_NEUTRAL; } } /* ================ rvCTFGameState::SendState ================ */ void rvCTFGameState::SendState( const idMessageSender &sender, int clientNum ) { idBitMsg outMsg; byte msgBuf[MAX_GAME_MESSAGE_SIZE]; assert( (gameLocal.isServer || gameLocal.isRepeater) && trackPrevious && IsType( rvCTFGameState::GetClassType() ) ); if( clientNum == -1 && (rvCTFGameState&)(*this) == (rvCTFGameState&)(*previousGameState) ) { return; } outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_GAMESTATE ); WriteState( outMsg ); sender.Send( outMsg ); // don't update the state if we are working for a single client if ( clientNum == -1 ) { outMsg.ReadByte(); // pop off the msg ID ReceiveState( outMsg ); } } /* =============== rvCTFGameState::WriteState =============== */ void rvCTFGameState::WriteState( idBitMsg &msg ) { // send off base info rvGameState::PackState( msg ); // add CTF info PackState( msg ); } /* ================ rvCTFGameState::ReceiveState ================ */ void rvCTFGameState::ReceiveState( const idBitMsg& msg ) { assert( IsType( rvCTFGameState::GetClassType() ) ); if ( !rvGameState::BaseUnpackState( msg ) ) { return; } UnpackState( msg ); if ( gameLocal.localClientNum >= 0 ) { GameStateChanged(); } (rvCTFGameState&)(*previousGameState) = (rvCTFGameState&)(*this); } /* ================ rvCTFGameState::PackState ================ */ void rvCTFGameState::PackState( idBitMsg& outMsg ) { // use indexing to pack in info int index = 0; for( int i = 0; i < TEAM_MAX; i++ ) { if( flagStatus[ i ] != ((rvCTFGameState*)previousGameState)->flagStatus[ i ] ) { outMsg.WriteByte( index ); outMsg.WriteByte( flagStatus[ i ].state ); outMsg.WriteByte( flagStatus[ i ].clientNum ); } index++; } for( int i = 0; i < MAX_AP; i++ ) { if( apState[ i ] != ((rvCTFGameState*)previousGameState)->apState[ i ] ) { outMsg.WriteByte( index ); outMsg.WriteByte( apState[ i ] ); } index++; } } /* ================ rvCTFGameState::UnpackState ================ */ void rvCTFGameState::UnpackState( const idBitMsg& inMsg ) { while( inMsg.GetRemainingData() ) { int index = inMsg.ReadByte(); if( index >= 0 && index < TEAM_MAX ) { flagStatus[ index ].state = (flagState_t)inMsg.ReadByte(); flagStatus[ index ].clientNum = inMsg.ReadByte(); } else if( index >= TEAM_MAX && index < ( TEAM_MAX + MAX_AP ) ) { apState[ index - TEAM_MAX ] = (apState_t)inMsg.ReadByte(); } else { gameLocal.Error( "rvCTFGameState::UnpackState() - Unknown data identifier '%d'\n", index ); } } } /* ================ rvCTFGameState::SendInitialState ================ */ void rvCTFGameState::SendInitialState( const idMessageSender &sender, int clientNum ) { assert( IsType( rvCTFGameState::GetClassType() ) ); rvCTFGameState* previousState = (rvCTFGameState*)previousGameState; rvCTFGameState invalidState; previousGameState = &invalidState; SendState( sender, clientNum ); previousGameState = previousState; } /* ================ rvCTFGameState::GameStateChanged ================ */ void rvCTFGameState::GameStateChanged( void ) { // detect any base state changes rvGameState::GameStateChanged(); // CTF specific stuff idPlayer* player = gameLocal.GetLocalPlayer(); if ( !player ) { if ( gameLocal.IsServerDemoPlaying() && gameLocal.GetDemoFollowClient() >= 0 ) { player = static_cast< idPlayer * >( gameLocal.entities[ gameLocal.GetDemoFollowClient() ] ); } } if ( !player ) { gameLocal.Warning( "rvCTFGameState::GameStateChanged() - NULL local player\n" ) ; return; } bool noSounds = false; for( int i = 0; i < TEAM_MAX; i++ ) { if( flagStatus[ i ] == ((rvCTFGameState*)previousGameState)->flagStatus[ i ] ) { continue; } // don't play flag messages when flag state changes as a result of the gamestate changing if( currentState != ((rvCTFGameState*)previousGameState)->currentState && ((rvCTFGameState*)previousGameState)->currentState != INACTIVE ) { continue; } if ( ((rvCTFGameState*)previousGameState)->currentState == INACTIVE ) { noSounds = true; } // flagTeam - used to tell the HUD which flag to update int flagTeam = i; // in one flag CTF flagTeam is set to whichever team has the flag if( gameLocal.gameType == GAME_1F_CTF || gameLocal.gameType == GAME_ARENA_1F_CTF ) { if( flagStatus[ i ].state == FS_TAKEN_MARINE ) { flagTeam = TEAM_MARINE; } else if( flagStatus[ i ].state == FS_TAKEN_STROGG ) { flagTeam = TEAM_STROGG; } } if( flagStatus[ i ].state == FS_DROPPED && !noSounds ) { if ( !player->spectating ) { if( flagTeam == player->team ) { // our flag was dropped, so the enemy dropped it gameLocal.mpGame.ScheduleAnnouncerSound ( AS_CTF_ENEMY_DROPS_FLAG, gameLocal.time, -1, true ); } else { gameLocal.mpGame.ScheduleAnnouncerSound ( AS_CTF_YOUR_TEAM_DROPS_FLAG, gameLocal.time, -1, true ); } } if( player->mphud ) { player->mphud->SetStateInt( "team", flagTeam ); player->mphud->HandleNamedEvent( "flagDrop" ); if ( !player->spectating ) { if ( flagTeam == player->team ) { player->mphud->SetStateString( "main_notice_text", common->GetLocalizedString( "#str_107723" ) ); } else { player->mphud->SetStateString( "main_notice_text", common->GetLocalizedString( "#str_104420" ) ); } player->mphud->HandleNamedEvent( "main_notice" ); } } } else if( flagStatus[ i ].state == FS_AT_BASE ) { if( ((rvCTFGameState*)previousGameState)->flagStatus[ i ].state == FS_TAKEN && !noSounds ) { // team scores if ( !player->spectating ) { if( flagTeam == player->team ) { if( gameLocal.mpGame.CanCapture( gameLocal.mpGame.OpposingTeam( flagTeam ) ) ) { gameLocal.mpGame.ScheduleAnnouncerSound ( AS_TEAM_ENEMY_SCORES, gameLocal.time ); } } else { if( gameLocal.mpGame.CanCapture( gameLocal.mpGame.OpposingTeam( flagTeam ) ) ) { gameLocal.mpGame.ScheduleAnnouncerSound ( AS_TEAM_YOU_SCORE, gameLocal.time ); } } } } else if( ((rvCTFGameState*)previousGameState)->flagStatus[ i ].state == FS_DROPPED && !noSounds ) { // flag returned if ( !player->spectating ) { if( flagTeam == player->team ) { gameLocal.mpGame.ScheduleAnnouncerSound ( AS_CTF_YOUR_FLAG_RETURNED, gameLocal.time, -1, true ); } else { gameLocal.mpGame.ScheduleAnnouncerSound ( AS_CTF_ENEMY_RETURNS_FLAG, gameLocal.time, -1, true ); } } } if( player->mphud ) { player->mphud->SetStateInt( "team", flagTeam ); player->mphud->HandleNamedEvent( "flagReturn" ); } } else if( flagStatus[ i ].state == FS_TAKEN || flagStatus[ i ].state == FS_TAKEN_STROGG || flagStatus[ i ].state == FS_TAKEN_MARINE ) { // flag taken if( flagTeam == player->team ) { if ( !player->spectating ) { if ( !noSounds ) { gameLocal.mpGame.ScheduleAnnouncerSound ( AS_CTF_ENEMY_HAS_FLAG, gameLocal.time, -1, true ); } } if ( !player->spectating ) { if ( player->mphud ) { player->mphud->SetStateString( "main_notice_text", common->GetLocalizedString( "#str_107722" ) ); player->mphud->HandleNamedEvent( "main_notice" ); } } } else { if ( flagStatus[ i ].clientNum == gameLocal.localClientNum ) { if ( !noSounds ) { gameLocal.mpGame.ScheduleAnnouncerSound ( AS_CTF_YOU_HAVE_FLAG, gameLocal.time, -1, true ); } if ( !player->spectating ) { // shouchard: inform the GUI that you've taken the flag player->mphud->SetStateString( "main_notice_text", common->GetLocalizedString( "#str_104419" ) ); player->mphud->HandleNamedEvent( "main_notice" ); } } else if ( !noSounds ) { if ( !player->spectating ) { gameLocal.mpGame.ScheduleAnnouncerSound ( AS_CTF_YOUR_TEAM_HAS_FLAG, gameLocal.time, -1, true ); } } } if( player->mphud ) { player->mphud->SetStateInt( "team", flagTeam ); player->mphud->HandleNamedEvent ( "flagTaken" ); } } } } /* ================ rvCTFGameState::Run ================ */ void rvCTFGameState::Run( void ) { // run common stuff rvGameState::Run(); switch( currentState ) { case GAMEON: { int team = ( ( gameLocal.mpGame.GetScoreForTeam( TEAM_MARINE ) >= gameLocal.serverInfo.GetInt( "si_captureLimit" ) ) ? TEAM_MARINE : ( ( gameLocal.mpGame.GetScoreForTeam( TEAM_STROGG ) >= gameLocal.serverInfo.GetInt( "si_captureLimit" ) ) ? TEAM_STROGG : -1 ) ); if( gameLocal.serverInfo.GetInt( "si_captureLimit" ) <= 0 ) { // no capture limit games team = -1; } bool tiedForFirst = gameLocal.mpGame.GetScoreForTeam( TEAM_MARINE ) == gameLocal.mpGame.GetScoreForTeam( TEAM_STROGG ); if ( team >= 0 && !tiedForFirst ) { if ( !fragLimitTimeout ) { common->DPrintf( "enter capture limit timeout, team %d is leader\n", team ); fragLimitTimeout = gameLocal.time + CAPTURELIMIT_DELAY; } if ( gameLocal.time > fragLimitTimeout ) { NewState( GAMEREVIEW ); gameLocal.mpGame.PrintMessageEvent( -1, MSG_CAPTURELIMIT, team ); } } else if ( fragLimitTimeout ) { // frag limit was hit and cancelled. means the two teams got even during FRAGLIMIT_DELAY // enter sudden death, the next frag leader will win // OR the winner lost a point in the frag delay, and there's no tie, so no one wins, game on. if( tiedForFirst && ( gameLocal.mpGame.GetScoreForTeam( TEAM_MARINE ) >= gameLocal.serverInfo.GetInt( "si_captureLimit" ) )) { NewState( SUDDENDEATH ); } fragLimitTimeout = 0; } else if ( gameLocal.mpGame.TimeLimitHit() ) { gameLocal.mpGame.PrintMessageEvent( -1, MSG_TIMELIMIT ); if( tiedForFirst ) { // if tied at timelimit hit, goto sudden death fragLimitTimeout = 0; NewState( SUDDENDEATH ); } else { // or just end the game NewState( GAMEREVIEW ); } } else if( tiedForFirst && team >= 0 ) { // check for the rare case that two teams both hit the fraglimit the same frame // two people tied at fraglimit, advance to sudden death after a delay fragLimitTimeout = gameLocal.time + CAPTURELIMIT_DELAY; } break; } case SUDDENDEATH: { int team = gameLocal.mpGame.GetScoreForTeam( TEAM_MARINE ) > gameLocal.mpGame.GetScoreForTeam( TEAM_STROGG ) ? TEAM_MARINE : TEAM_STROGG; bool tiedForFirst = false; if( gameLocal.mpGame.GetScoreForTeam( TEAM_MARINE ) == gameLocal.mpGame.GetScoreForTeam( TEAM_STROGG ) ) { team = -1; tiedForFirst = true; } if ( team >= 0 && !tiedForFirst ) { if ( !fragLimitTimeout ) { common->DPrintf( "enter sudden death FragLeader timeout, team %d is leader\n", team ); fragLimitTimeout = gameLocal.time + CAPTURELIMIT_DELAY; } if ( gameLocal.time > fragLimitTimeout ) { NewState( GAMEREVIEW ); gameLocal.mpGame.PrintMessageEvent( -1, MSG_CAPTURELIMIT, team ); } } else if ( fragLimitTimeout ) { gameLocal.mpGame.PrintMessageEvent( -1, MSG_HOLYSHIT ); fragLimitTimeout = 0; } break; } } } /* ================ rvCTFGameState::SetFlagState ================ */ void rvCTFGameState::SetFlagState( int flag, flagState_t newState ) { if ( !gameLocal.isServer ) { return; } assert( gameLocal.isServer && ( flag >= 0 && flag < TEAM_MAX ) && IsType( rvCTFGameState::GetClassType() ) ); flagStatus[ flag ].state = newState; } /* ================ rvCTFGameState::SetFlagCarrier ================ */ void rvCTFGameState::SetFlagCarrier( int flag, int clientNum ) { assert( gameLocal.isServer && ( flag >= 0 && flag < TEAM_MAX ) && (clientNum >= 0 && clientNum < MAX_CLIENTS) && IsType( rvCTFGameState::GetClassType() ) ); flagStatus[ flag ].clientNum = clientNum; } /* ================ rvCTFGameState::operator== ================ */ bool rvCTFGameState::operator==( const rvCTFGameState& rhs ) const { if( (rvGameState&)(*this) != (rvGameState&)rhs ) { return false; } for( int i = 0; i < TEAM_MAX; i++ ) { if( flagStatus[ i ] != rhs.flagStatus[ i ] ) { return false; } } for( int i = 0; i < MAX_AP; i++ ) { if( apState[ i ] != rhs.apState[ i ] ) { return false; } } return true; } /* ================ rvCTFGameState::operator= ================ */ rvCTFGameState& rvCTFGameState::operator=( const rvCTFGameState& rhs ) { (rvGameState&)(*this) = (rvGameState&)rhs; for( int i = 0; i < TEAM_MAX; i++ ) { flagStatus[ i ] = rhs.flagStatus[ i ]; } for( int i = 0; i < MAX_AP; i++ ) { apState[ i ] = rhs.apState[ i ]; } return (*this); } /* =============================================================================== rvTourneyGameState Game state info for tourney =============================================================================== */ /* ================ rvTourneyGameState::rvTourneyGameState ================ */ rvTourneyGameState::rvTourneyGameState( bool allocPrevious ) : rvGameState( false ) { Clear(); if( allocPrevious ) { previousGameState = new rvTourneyGameState( false ); } else { previousGameState = NULL; } packTourneyHistory = false; trackPrevious = allocPrevious; } /* ================ rvTourneyGameState::Clear ================ */ void rvTourneyGameState::Clear( void ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); // mekberg: clear previous game state. if ( previousGameState ) { previousGameState->Clear(); } rvGameState::Clear(); tourneyState = TS_INVALID; for( int i = 0; i < MAX_ARENAS; i++ ) { arenas[ i ].Clear( false ); arenas[ i ].SetArenaID( i ); } for( int i = 0; i < MAX_ROUNDS; i++ ) { for( int j = 0; j < MAX_ARENAS; j++ ) { tourneyHistory[ i ][ j ].playerOne[ 0 ] = '\0'; tourneyHistory[ i ][ j ].playerTwo[ 0 ] = '\0'; tourneyHistory[ i ][ j ].playerOneNum = -1; tourneyHistory[ i ][ j ].playerTwoNum = -1; tourneyHistory[ i ][ j ].playerOneScore = -1; tourneyHistory[ i ][ j ].playerTwoScore = -1; } } startingRound = 0; maxRound = 0; round = -1; byeArena = -1; tourneyCount = 0; roundTimeout = 0; } /* ================ rvTourneyGameState::Reset ================ */ void rvTourneyGameState::Reset( void ) { for( int i = 0; i < MAX_ARENAS; i++ ) { arenas[ i ].Clear( false ); arenas[ i ].SetArenaID( i ); } for( int i = 0; i < MAX_ROUNDS; i++ ) { for( int j = 0; j < MAX_ARENAS; j++ ) { tourneyHistory[ i ][ j ].playerOne[ 0 ] = '\0'; tourneyHistory[ i ][ j ].playerTwo[ 0 ] = '\0'; tourneyHistory[ i ][ j ].playerOneNum = -1; tourneyHistory[ i ][ j ].playerTwoNum = -1; tourneyHistory[ i ][ j ].playerOneScore = -1; tourneyHistory[ i ][ j ].playerTwoScore = -1; } } startingRound = 0; maxRound = 0; round = -1; byeArena = -1; roundTimeout = 0; } /* ================ rvTourneyGameState::Run ================ */ void rvTourneyGameState::Run( void ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); rvGameState::Run(); switch( currentState ) { case GAMEON: { // check to see if we need to advance to the next round if( nextState == GAMEREVIEW ) { return; } bool roundDone = true; for( int i = 0; i < MAX_ARENAS; i++ ) { if( arenas[ i ].GetState() == AS_INACTIVE ) { continue; } arenas[ i ].UpdateState(); if( arenas[ i ].GetState() != AS_DONE ) { // check to see if we're done roundDone = false; } } if( roundDone && !roundTimeout ) { roundTimeout = gameLocal.time + FRAGLIMIT_DELAY; } if( roundDone && gameLocal.time > roundTimeout ) { int pastRound = round - 1; //rounds are 1 indexed idList<rvPair<idPlayer*, int> > advancingPlayers; round++; roundTimeout = 0; assert( round >= 2 ); // copy over tourney history for the previous round UpdateTourneyHistory( pastRound ); // transmit history forceTourneyHistory = true; // add who will advance to the next round for( int i = 0; i < MAX_ARENAS; i++ ) { if( arenas[ i ].GetState() == AS_DONE && arenas[ i ].GetWinner() ) { advancingPlayers.Append( rvPair<idPlayer*, int>( arenas[ i ].GetWinner(), i ) ); gameLocal.mpGame.AddPlayerWin( arenas[ i ].GetWinner(), 1 ); } } // when only one player advances, that player has won the tournament if( advancingPlayers.Num() == 1 ) { idPlayer* winner = advancingPlayers[ 0 ].First(); assert( winner ); for( int i = 0; i < MAX_ARENAS; i++ ) { arenas[ i ].Clear(); } gameLocal.Printf( "Round %d: player %d (%s) has won the tourney!\n", round - 1, winner->entityNumber, gameLocal.userInfo[ winner->entityNumber ].GetString( "ui_name" ) ); // award 5 wins for winning the entire tournament gameLocal.mpGame.AddPlayerWin( winner, 5 ); nextState = GAMEREVIEW; nextStateTime = gameLocal.time + 5000; return; } // see if we have to swap a player from the byeArena this round bool swapBye = false; int thisByeArena = -1; if( byeArena >= 0 ) { // look at the bye arena from the round that just ended thisByeArena = byeArena / (round - 1); // if the bye arena is playing in the next round, there's no need to switch players if( !(thisByeArena % 2) ) { if( arenas[ thisByeArena ].GetState() == AS_DONE && arenas[ thisByeArena + 1 ].GetState() == AS_DONE ) { assert( arenas[ thisByeArena ].GetWinner() && arenas[ thisByeArena + 1 ].GetWinner() ); swapBye = false; } else { swapBye = true; } } else { if( arenas[ thisByeArena ].GetState() == AS_DONE && arenas[ thisByeArena - 1 ].GetState() == AS_DONE ) { assert( arenas[ thisByeArena ].GetWinner() && arenas[ thisByeArena - 1 ].GetWinner() ); swapBye = false; } else { swapBye = true; } } } idPlayer* oldByePlayer = NULL; idPlayer* newByePlayer = NULL; if( swapBye ) { oldByePlayer = arenas[ thisByeArena ].GetWinner(); // pick a new bye player only from players who will be fighting next round // i.e., don't swap the bye player with a player who will have a disconnect bye this upcoming round idList<rvPair<idPlayer*, int> > nextRoundPlayers; for ( int i = 0; i < MAX_ARENAS; i += 2 ) { if( arenas[ i ].GetState() == AS_DONE && arenas[ i ].GetWinner() && arenas[ i + 1 ].GetState() == AS_DONE && arenas[ i + 1 ].GetWinner() ) { nextRoundPlayers.Append( rvPair<idPlayer*, int>( arenas[ i ].GetWinner(), i ) ); nextRoundPlayers.Append( rvPair<idPlayer*, int>( arenas[ i + 1 ].GetWinner(), i + 1 ) ); } } if ( nextRoundPlayers.Num() ) { newByePlayer = nextRoundPlayers[ gameLocal.random.RandomInt( nextRoundPlayers.Num() ) ].First(); } } // assign arenas for the next round for ( int i = 0; i < MAX_ARENAS; i += 2 ) { idPlayer* advanceOne = arenas[ i ].GetWinner(); idPlayer* advanceTwo = arenas[ i + 1 ].GetWinner(); // #13266 - bug: bystander from prev round is spectator in his match arena after round change // we call rvTourneyInstance::Clear when setting up rounds (below), which sets it's players as spectator // if the former bystander is placed in one of the new arenas and is still referenced in the bye arena then he'll get set spectating // so just clear him up once identified // #13631 - we used to call RemovePlayer before entering that loop, but that was messing up the selection of the next bystander // so have to do it inside the loop now, just before it happens if ( ( i == thisByeArena || i + 1 == thisByeArena ) && arenas[ thisByeArena ].HasPlayer( oldByePlayer ) ) { arenas[ thisByeArena ].RemovePlayer( oldByePlayer ); } arenas[ i ].Clear(); arenas[ i + 1 ].Clear(); // assign new arenas, swapping oldByePlayer with newByePlayer if ( newByePlayer && oldByePlayer ) { if ( advanceOne == newByePlayer ) { advanceOne = oldByePlayer; } else if ( advanceTwo == newByePlayer ) { advanceTwo = oldByePlayer; } else if ( advanceOne == oldByePlayer ) { advanceOne = newByePlayer; } else if ( advanceTwo == oldByePlayer ) { advanceTwo = newByePlayer; } } if ( advanceOne || advanceTwo ) { arenas[ (i / 2) ].AddPlayers( advanceOne, advanceTwo ); if ( advanceOne ) { advanceOne->JoinInstance( (i / 2) ); advanceOne->ServerSpectate( false ); } if ( advanceTwo ) { advanceTwo->JoinInstance( (i / 2) ); advanceTwo->ServerSpectate( false ); } gameLocal.Printf( "Round %d: Arena %d is starting play with players %d (%s) and %d (%s)\n", round, (i / 2), advanceOne ? advanceOne->entityNumber : -1, advanceOne ? advanceOne->GetUserInfo()->GetString( "ui_name" ) : "NULL", advanceTwo ? advanceTwo->entityNumber : -1, advanceTwo ? advanceTwo->GetUserInfo()->GetString( "ui_name" ) : "NULL" ); arenas[ (i / 2) ].Ready(); } } // once the new round is setup, go through and make sure all the spectators are in valid arena for( int i = 0; i < gameLocal.numClients; i++ ) { idPlayer* p = (idPlayer*)gameLocal.entities[ i ]; // re-select our arena since round changed if( p && p->spectating ) { rvTourneyArena& thisArena = arenas[ p->GetArena() ]; if( thisArena.GetState() != AS_WARMUP ) { p->JoinInstance( GetNextActiveArena( p->GetArena() ) ); } } } } break; } } } /* ================ rvTourneyGameState::NewState ================ */ void rvTourneyGameState::NewState( mpGameState_t newState ) { assert( (newState != currentState) && gameLocal.isServer ); switch( newState ) { case WARMUP: { Reset(); // force everyone to spectate for( int i = 0; i < MAX_CLIENTS; i++ ) { if( gameLocal.entities[ i ] ) { ((idPlayer*)gameLocal.entities[ i ])->ServerSpectate( true ); } } break; } case GAMEON: { tourneyCount++; SetupInitialBrackets(); break; } } rvGameState::NewState( newState ); } /* ================ rvTourneyGameState::GameStateChanged ================ */ void rvTourneyGameState::GameStateChanged( void ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); rvGameState::GameStateChanged(); idPlayer* localPlayer = gameLocal.GetLocalPlayer(); int oldRound = ((rvTourneyGameState*)previousGameState)->round; if( round != oldRound ) { if ( round > maxRound && gameLocal.GetLocalPlayer() ) { gameLocal.GetLocalPlayer()->ForceScoreboard( true, gameLocal.time + 5000 ); gameLocal.mpGame.ScheduleAnnouncerSound( AS_TOURNEY_DONE, gameLocal.time ); } // we're starting a new round gameLocal.mpGame.tourneyGUI.RoundStart(); // skip announce if the round number doesn't make sense if ( round >= 1 && round <= MAX_ROUNDS ) { // play the sound a bit after round restart to let spawn sounds settle gameLocal.mpGame.ScheduleAnnouncerSound( (announcerSound_t)( AS_TOURNEY_PRELIMS + round - 1 ), gameLocal.time + 1500); } } for( int i = 0; i < MAX_ARENAS; i++ ) { rvTourneyArena& thisArena = arenas[ i ]; rvTourneyArena& previousArena = ((rvTourneyGameState*)previousGameState)->arenas[ i ]; if( ((thisArena.GetPlayers()[ 0 ] != previousArena.GetPlayers()[ 0 ]) || (thisArena.GetPlayers()[ 1 ] != previousArena.GetPlayers()[ 1 ]) || (round != ((rvTourneyGameState*)previousGameState)->round )) /*&& !((thisArena.GetPlayers()[ 0 ] == NULL && thisArena.GetPlayers()[ 1 ] != NULL) || (thisArena.GetPlayers()[ 0 ] != NULL && thisArena.GetPlayers()[ 1 ] == NULL) ) */) { // don't re-init arenas that have changed and been done for a while if( thisArena.GetState() != AS_DONE || previousArena.GetState() != AS_DONE ) { gameLocal.mpGame.tourneyGUI.ArenaStart( i ); } if( localPlayer && thisArena.GetPlayers()[ 0 ] == localPlayer ) { gameLocal.mpGame.tourneyGUI.ArenaSelect( i, TGH_PLAYER_ONE ); } if( localPlayer && thisArena.GetPlayers()[ 1 ] == localPlayer ) { gameLocal.mpGame.tourneyGUI.ArenaSelect( i, TGH_PLAYER_TWO ); } } if( localPlayer->GetArena() == thisArena.GetArenaID() && thisArena.GetState() == AS_SUDDEN_DEATH && thisArena.GetState() != previousArena.GetState() ) { gameLocal.mpGame.ScheduleAnnouncerSound( AS_GENERAL_SUDDEN_DEATH, gameLocal.time, thisArena.GetArenaID() ); gameLocal.GetLocalPlayer()->GUIMainNotice( common->GetLocalizedString( "#str_104287" ) ); } if( thisArena.GetState() == AS_DONE && thisArena.GetState() != previousArena.GetState() ) { if( thisArena.GetWinner() != previousArena.GetWinner() && thisArena.GetWinner() == gameLocal.GetLocalPlayer() ) { if( round >= maxRound ) { gameLocal.mpGame.ScheduleAnnouncerSound( AS_TOURNEY_WON, gameLocal.time ); } else { gameLocal.mpGame.ScheduleAnnouncerSound( AS_TOURNEY_ADVANCE, gameLocal.time ); } } else if( thisArena.GetLoser() != previousArena.GetLoser() && thisArena.GetLoser() == gameLocal.GetLocalPlayer() ) { gameLocal.mpGame.ScheduleAnnouncerSound( AS_TOURNEY_ELIMINATED, gameLocal.time ); } if( previousArena.GetWinner() == NULL && thisArena.GetWinner() != NULL ) { gameLocal.mpGame.tourneyGUI.ArenaDone( i ); } // on the client, add this result to our tourneyHistory //if( gameLocal.isClient && thisArena.GetPlayers()[ 0 ] && thisArena.GetPlayers()[ 1 ] && (round - 1 ) >= 0 && (round - 1) < MAX_ROUNDS ) { // tourneyHistory[ round - 1 ][ i ].playerOneScore = gameLocal.mpGame.GetTeamScore( thisArena.GetPlayers()[ 0 ] ); // tourneyHistory[ round - 1 ][ i ].playerTwoScore = gameLocal.mpGame.GetTeamScore( thisArena.GetPlayers()[ 1 ] ); //} } if( localPlayer && (thisArena.GetState() == AS_WARMUP) && (thisArena.GetState() != previousArena.GetState()) && localPlayer->GetArena() == thisArena.GetArenaID() ) { gameLocal.mpGame.RemoveAnnouncerSound( AS_GENERAL_PREPARE_TO_FIGHT ); gameLocal.mpGame.RemoveAnnouncerSound( AS_GENERAL_THREE ); gameLocal.mpGame.RemoveAnnouncerSound( AS_GENERAL_TWO ); gameLocal.mpGame.RemoveAnnouncerSound( AS_GENERAL_ONE ); int warmupEndTime = gameLocal.time + ( gameLocal.serverInfo.GetInt( "si_countdown" ) * 1000 ) + 5000; gameLocal.mpGame.ScheduleAnnouncerSound( AS_GENERAL_PREPARE_TO_FIGHT, gameLocal.time + 5000 ); gameLocal.mpGame.ScheduleAnnouncerSound( AS_GENERAL_THREE, warmupEndTime - 3000 ); gameLocal.mpGame.ScheduleAnnouncerSound( AS_GENERAL_TWO, warmupEndTime - 2000 ); gameLocal.mpGame.ScheduleAnnouncerSound( AS_GENERAL_ONE, warmupEndTime - 1000 ); localPlayer->vsMsgState = true; localPlayer->GUIMainNotice( va( "%s^0 vs. %s^0", thisArena.GetPlayerName( 0 ), thisArena.GetPlayerName( 1 ) ), true ); } if( (thisArena.GetState() == AS_ROUND) && (thisArena.GetState() != previousArena.GetState()) ) { if( localPlayer && localPlayer->GetArena() == thisArena.GetArenaID() ) { gameLocal.mpGame.ScheduleAnnouncerSound( AS_GENERAL_FIGHT, gameLocal.time ); gameLocal.mpGame.ScheduleTimeAnnouncements(); } } } if( ((rvTourneyGameState*)previousGameState)->currentState != currentState ) { if( currentState == WARMUP ) { gameLocal.mpGame.tourneyGUI.PreTourney(); } else if( currentState == COUNTDOWN ) { if( currentState == COUNTDOWN && ((rvTourneyGameState*)previousGameState)->currentState != INACTIVE ) { gameLocal.mpGame.ScheduleAnnouncerSound( AS_TOURNEY_START, gameLocal.time); } } else if( currentState == GAMEON ) { gameLocal.mpGame.tourneyGUI.TourneyStart(); } } if( packTourneyHistory ) { // apply history gameLocal.mpGame.tourneyGUI.SetupTourneyHistory( startingRound, round - 1, tourneyHistory ); packTourneyHistory = false; } if( localPlayer && localPlayer->spectating ) { rvTourneyArena& thisArena = arenas[ localPlayer->GetArena() ]; if( thisArena.GetPlayers()[ 0 ] == NULL || thisArena.GetPlayers()[ 1 ] == NULL || (localPlayer->spectating && localPlayer->spectator != thisArena.GetPlayers()[ 0 ]->entityNumber && localPlayer->spectator != thisArena.GetPlayers()[ 1 ]->entityNumber) ) { gameLocal.mpGame.tourneyGUI.ArenaSelect( localPlayer->GetArena(), TGH_BRACKET ); } else if ( thisArena.GetPlayers()[ 0 ] == localPlayer || (localPlayer->spectating && thisArena.GetPlayers()[ 0 ]->entityNumber == localPlayer->spectator) ) { gameLocal.mpGame.tourneyGUI.ArenaSelect( localPlayer->GetArena(), TGH_PLAYER_ONE ); } else if ( thisArena.GetPlayers()[ 1 ] == localPlayer || (localPlayer->spectating && thisArena.GetPlayers()[ 1 ]->entityNumber == localPlayer->spectator) ) { gameLocal.mpGame.tourneyGUI.ArenaSelect( localPlayer->GetArena(), TGH_PLAYER_TWO ); } } } /* ================ msgTourney_t Identifiers for transmitted state ================ */ typedef enum { MSG_TOURNEY_TOURNEYSTATE, MSG_TOURNEY_STARTINGROUND, MSG_TOURNEY_ROUND, MSG_TOURNEY_MAXROUND, MSG_TOURNEY_HISTORY, MSG_TOURNEY_TOURNEYCOUNT, MSG_TOURNEY_ARENAINFO } msgTourney_t; /* ================ rvTourneyGameState::PackState ================ */ void rvTourneyGameState::PackState( idBitMsg& outMsg ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); if ( tourneyState != ((rvTourneyGameState*)previousGameState)->tourneyState ) { outMsg.WriteByte( MSG_TOURNEY_TOURNEYSTATE ); outMsg.WriteByte( tourneyState ); } if ( startingRound != ((rvTourneyGameState*)previousGameState)->startingRound ) { outMsg.WriteByte( MSG_TOURNEY_STARTINGROUND ); outMsg.WriteByte( startingRound ); } if( round != ((rvTourneyGameState*)previousGameState)->round ) { outMsg.WriteByte( MSG_TOURNEY_ROUND ); outMsg.WriteByte( round ); } if( maxRound != ((rvTourneyGameState*)previousGameState)->maxRound ) { outMsg.WriteByte( MSG_TOURNEY_MAXROUND ); outMsg.WriteByte( maxRound ); } for ( int i = 0; i < MAX_ARENAS; i++ ) { if ( arenas[ i ] != ((rvTourneyGameState*)previousGameState)->arenas[ i ] ) { outMsg.WriteByte( MSG_TOURNEY_ARENAINFO + i ); arenas[ i ].PackState( outMsg ); } } if ( packTourneyHistory || forceTourneyHistory ) { if ( forceTourneyHistory ) { common->Warning( "forcing down tourney history\n" ); } // don't write out uninitialized tourney history if ( startingRound > 0 && round > 1 ) { outMsg.WriteByte( MSG_TOURNEY_HISTORY ); // client might not yet have startingRound or round outMsg.WriteByte( startingRound ); outMsg.WriteChar( round ); outMsg.WriteByte( maxRound ); for( int i = startingRound - 1; i <= Min( (round - 1), (maxRound - 1) ); i++ ) { for( int j = 0; j < MAX_ARENAS / (i + 1); j++ ) { outMsg.WriteString( tourneyHistory[ i ][ j ].playerOne, MAX_TOURNEY_HISTORY_NAME_LEN ); outMsg.WriteChar( idMath::ClampChar( tourneyHistory[ i ][ j ].playerOneScore ) ); outMsg.WriteString( tourneyHistory[ i ][ j ].playerTwo, MAX_TOURNEY_HISTORY_NAME_LEN ); outMsg.WriteChar( idMath::ClampChar( tourneyHistory[ i ][ j ].playerTwoScore ) ); outMsg.WriteChar( tourneyHistory[ i ][ j ].playerOneNum ); outMsg.WriteChar( tourneyHistory[ i ][ j ].playerTwoNum ); } } packTourneyHistory = false; } } if ( tourneyCount != ((rvTourneyGameState*)previousGameState)->tourneyCount ) { outMsg.WriteByte( MSG_TOURNEY_TOURNEYCOUNT ); outMsg.WriteByte( tourneyCount ); } } /* ================ rvTourneyGameState::UnpackState ================ */ void rvTourneyGameState::UnpackState( const idBitMsg& inMsg ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); while( inMsg.GetRemainingData() ) { int index = inMsg.ReadByte(); switch( index ) { case MSG_TOURNEY_TOURNEYSTATE: { tourneyState = (tourneyState_t)inMsg.ReadByte(); break; } case MSG_TOURNEY_STARTINGROUND: { startingRound = inMsg.ReadByte(); break; } case MSG_TOURNEY_ROUND: { round = inMsg.ReadByte(); // not a great way of doing this, should clamp the values if ( round == 255 ) { round = -1; } break; } case MSG_TOURNEY_MAXROUND: { maxRound = inMsg.ReadByte(); if ( maxRound == 255 ) { maxRound = -1; } break; } case MSG_TOURNEY_HISTORY: { int startRound = inMsg.ReadByte(); int rnd = inMsg.ReadChar(); int maxr = inMsg.ReadByte(); assert( rnd >= 1 ); // something is uninitialized for( int i = startRound - 1; i <= Min( (rnd - 1), (maxr - 1) ); i++ ) { for( int j = 0; j < MAX_ARENAS / (i + 1); j++ ) { inMsg.ReadString( tourneyHistory[ i ][ j ].playerOne, MAX_TOURNEY_HISTORY_NAME_LEN ); tourneyHistory[ i ][ j ].playerOneScore = inMsg.ReadChar(); inMsg.ReadString( tourneyHistory[ i ][ j ].playerTwo, MAX_TOURNEY_HISTORY_NAME_LEN ); tourneyHistory[ i ][ j ].playerTwoScore = inMsg.ReadChar(); tourneyHistory[ i ][ j ].playerOneNum = inMsg.ReadChar(); tourneyHistory[ i ][ j ].playerTwoNum = inMsg.ReadChar(); if( tourneyHistory[ i ][ j ].playerOneNum < 0 || tourneyHistory[ i ][ j ].playerOneNum >= MAX_CLIENTS ) { tourneyHistory[ i ][ j ].playerOneNum = -1; } if( tourneyHistory[ i ][ j ].playerTwoNum < 0 || tourneyHistory[ i ][ j ].playerTwoNum >= MAX_CLIENTS ) { tourneyHistory[ i ][ j ].playerTwoNum = -1; } } } // client side (and listen server) no reason to check for history change all the time packTourneyHistory = true; break; } case MSG_TOURNEY_TOURNEYCOUNT: { tourneyCount = inMsg.ReadByte(); break; } default: { if ( index >= MSG_TOURNEY_ARENAINFO && index < MSG_TOURNEY_ARENAINFO + MAX_ARENAS ) { arenas[ index - MSG_TOURNEY_ARENAINFO ].UnpackState( inMsg ); } else { gameLocal.Error( "rvTourneyGameState::UnpackState() - Unknown data identifier '%d'\n", index ); } break; } } } } /* ================ rvTourneyGameState::SendState ================ */ void rvTourneyGameState::SendState( const idMessageSender &sender, int clientNum ) { idBitMsg outMsg; byte msgBuf[MAX_GAME_MESSAGE_SIZE]; assert( (gameLocal.isServer || gameLocal.isRepeater) && trackPrevious && IsType( rvTourneyGameState::GetClassType() ) ); if ( clientNum == -1 && (rvTourneyGameState&)(*this) == (rvTourneyGameState&)(*previousGameState) ) { return; } outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_GAMESTATE ); WriteState( outMsg ); if( clientNum == -1 && forceTourneyHistory ) { forceTourneyHistory = false; } sender.Send( outMsg ); // don't update the state if we are working for a single client if ( clientNum == -1 ) { outMsg.ReadByte(); // pop off the msg ID ReceiveState( outMsg ); } } /* =============== rvTourneyGameState::WriteState =============== */ void rvTourneyGameState::WriteState( idBitMsg &msg ) { // send off base info rvGameState::PackState( msg ); // add Tourney info PackState( msg ); } /* ================ rvTourneyGameState::ReceiveState ================ */ void rvTourneyGameState::ReceiveState( const idBitMsg& msg ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); if ( !rvGameState::BaseUnpackState( msg ) ) { return; } UnpackState( msg ); if ( gameLocal.localClientNum >= 0 ) { GameStateChanged(); } (rvTourneyGameState&)(*previousGameState) = (rvTourneyGameState&)(*this); } /* ================ rvTourneyGameState::SendInitialState ================ */ void rvTourneyGameState::SendInitialState( const idMessageSender &sender, int clientNum ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); rvTourneyGameState* previousState = (rvTourneyGameState*)previousGameState; rvTourneyGameState invalidState; previousGameState = &invalidState; // if the tourney has been going on, transmit the tourney history if( round > 0 ) { // comparing the tourney history for all state changes is wasteful when we really just want to send it to new clients packTourneyHistory = true; } SendState( sender, clientNum ); previousGameState = previousState; } /* ================ rvTourneyGameState::operator== ================ */ bool rvTourneyGameState::operator==( const rvTourneyGameState& rhs ) const { assert( IsType( rvTourneyGameState::GetClassType() ) && rhs.IsType( rvTourneyGameState::GetClassType() ) ); if( (rvGameState&)(*this) != (rvGameState&)rhs ) { return false; } if( round != rhs.round || startingRound != rhs.startingRound || maxRound != rhs.maxRound || tourneyState != rhs.tourneyState ) { return false; } for( int i = 0; i < MAX_ARENAS; i++ ) { if( arenas[ i ] != rhs.arenas[ i ] ) { return false; } } return true; } /* ================ rvTourneyGameState::operator= ================ */ rvTourneyGameState& rvTourneyGameState::operator=( const rvTourneyGameState& rhs ) { assert( IsType( rvTourneyGameState::GetClassType() ) && rhs.IsType( rvTourneyGameState::GetClassType() ) ); (rvGameState&)(*this) = (rvGameState&)rhs; round = rhs.round; startingRound = rhs.startingRound; maxRound = rhs.maxRound; tourneyState = rhs.tourneyState; for( int i = 0; i < MAX_ARENAS; i++ ) { arenas[ i ] = rhs.arenas[ i ]; } return (*this); } /* ================ rvTourneyGameState::GetNumArenas Returns number of active arenas ================ */ int rvTourneyGameState::GetNumArenas( void ) const { assert( IsType( rvTourneyGameState::GetClassType() ) ); int num = 0; for( int i = 0; i < MAX_ARENAS; i++ ) { if( arenas[ i ].GetState() != AS_INACTIVE && arenas[ i ].GetState() != AS_DONE ) { num++; } } return num; } /* ================ rvTourneyGameState::SetupInitialBrackets Sets up the brackets for a new match. fragCount in playerstate is the player's persistant frag count over an entire level. In teamFragCount we store this rounds score. Initial bracket seeds are random ================ */ void rvTourneyGameState::SetupInitialBrackets( void ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); idList<idPlayer*> unseededPlayers; int numRankedPlayers = gameLocal.mpGame.GetNumRankedPlayers(); // all this crazy math does is figure out: // 8 arenas to 4 rounds ( round 1: 8 arenas, round 2: 4 arenas, round 3: 2 arenas, round 4: 1 arena ) // 16 arenas to 5 rounds ( round 1: 16 arenas, round 2: 8 arenas, round 3: 4 arenas, round 4: 2 arenas, round 5: 1 arena ) // etc int newMaxRound = idMath::ILog2( Max( idMath::CeilPowerOfTwo( MAX_ARENAS * 2 ), 2 ) ); // we start at a round appropriate for our # of people // If you have 1-2 players, start in maxRound, if you have 3-4 players start in maxRound - 1, if you have 5-8 players // start in maxRound - 2, if you have 9 - 16 players start in maxRound - 3, etc. int newRound = newMaxRound - idMath::ILog2( Max( idMath::CeilPowerOfTwo( gameLocal.mpGame.GetNumRankedPlayers() ), 2 ) ) + 1; round = newRound; maxRound = newMaxRound; startingRound = round; for( int i = 0; i < numRankedPlayers; i++ ) { unseededPlayers.Append( gameLocal.mpGame.GetRankedPlayer( i ) ); } int numArenas = 0; while ( unseededPlayers.Num() > 1 ) { idPlayer* playerOne = unseededPlayers[ gameLocal.random.RandomInt( unseededPlayers.Num() ) ]; unseededPlayers.Remove( playerOne ); idPlayer* playerTwo = unseededPlayers[ gameLocal.random.RandomInt( unseededPlayers.Num() ) ]; unseededPlayers.Remove( playerTwo ); rvTourneyArena& arena = arenas[ numArenas ]; arena.Clear(); arena.AddPlayers( playerOne, playerTwo ); // place the players in the correct instance playerOne->JoinInstance( numArenas ); playerTwo->JoinInstance( numArenas ); playerOne->ServerSpectate( false ); playerTwo->ServerSpectate( false ); gameLocal.mpGame.SetPlayerTeamScore( playerOne, 0 ); gameLocal.mpGame.SetPlayerTeamScore( playerTwo, 0 ); gameLocal.Printf( "rvTourneyGameState::SetupInitialBrackets() - %s will face %s in arena %d\n", playerOne->GetUserInfo()->GetString( "ui_name" ), playerTwo->GetUserInfo()->GetString( "ui_name" ), numArenas ); // this arena is ready to play arena.Ready(); numArenas++; } assert( unseededPlayers.Num() == 0 || unseededPlayers.Num() == 1 ); if( unseededPlayers.Num() ) { assert( unseededPlayers[ 0 ] ); // the mid player gets a bye unseededPlayers[ 0 ]->SetTourneyStatus( PTS_UNKNOWN ); unseededPlayers[ 0 ]->ServerSpectate( true ); arenas[ numArenas ].AddPlayers( unseededPlayers[ 0 ], NULL ); arenas[ numArenas ].Ready(); // mark the ancestor arena of the bye player byeArena = numArenas * startingRound; } else { byeArena = -1; } } /* ================ rvTourneyGameState::ClientDisconnect A player has disconnected from the server ================ */ void rvTourneyGameState::ClientDisconnect( idPlayer* player ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); if( gameLocal.isClient ) { return; } // go through the tourney history and copy over the disconnecting player's name if( startingRound > 0 && round <= MAX_ROUNDS ) { for( int i = startingRound - 1; i < round - 1; i++ ) { for( int j = 0; j < MAX_ARENAS / (i + 1); j++ ) { if( tourneyHistory[ i ][ j ].playerOneNum == player->entityNumber ) { idStr::Copynz( tourneyHistory[ i ][ j ].playerOne, player->GetUserInfo()->GetString( "ui_name" ), MAX_TOURNEY_HISTORY_NAME_LEN ); tourneyHistory[ i ][ j ].playerOneNum = -1; } else if( tourneyHistory[ i ][ j ].playerTwoNum == player->entityNumber ) { idStr::Copynz( tourneyHistory[ i ][ j ].playerTwo, player->GetUserInfo()->GetString( "ui_name" ), MAX_TOURNEY_HISTORY_NAME_LEN ); tourneyHistory[ i ][ j ].playerTwoNum = -1; } } } // copy over the current rounds info if the player is playing for( int i = 0; i < MAX_ARENAS; i++ ) { if( arenas[ i ].GetPlayers()[ 0 ] == player ) { tourneyHistory[ round - 1 ][ i ].playerOneNum = -1; idStr::Copynz( tourneyHistory[ round - 1 ][ i ].playerOne, player->GetUserInfo()->GetString( "ui_name" ), MAX_TOURNEY_HISTORY_NAME_LEN ); tourneyHistory[ round - 1 ][ i ].playerOneScore = gameLocal.mpGame.GetTeamScore( player ); } else if( arenas[ i ].GetPlayers()[ 1 ] == player ) { tourneyHistory[ round - 1 ][ i ].playerTwoNum = -1; idStr::Copynz( tourneyHistory[ round - 1 ][ i ].playerTwo, player->GetUserInfo()->GetString( "ui_name" ), MAX_TOURNEY_HISTORY_NAME_LEN ); tourneyHistory[ round - 1 ][ i ].playerTwoScore = gameLocal.mpGame.GetTeamScore( player ); } } // retransmit tourney history to everyone packTourneyHistory = true; } RemovePlayer( player ); // give RemovePlayer() a chance to update tourney history if needed if( packTourneyHistory ) { for( int i = 0; i < gameLocal.numClients; i++ ) { if( i == player->entityNumber ) { continue; } if( gameLocal.entities[ i ] ) { packTourneyHistory = true; SendState( serverReliableSender.To( i, true ), i ); } } if ( gameLocal.isRepeater ) { packTourneyHistory = true; SendState( repeaterReliableSender.To( -1 ), ENTITYNUM_NONE ); } packTourneyHistory = false; } } /* ================ rvTourneyGameState::Spectate ================ */ void rvTourneyGameState::Spectate( idPlayer* player ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); assert( gameLocal.isServer || player->IsFakeClient() ); if( player->spectating && player->wantSpectate ) { RemovePlayer( player ); } } /* ================ rvTourneyGameState::RemovePlayer Removes the specified player from the arena ================ */ void rvTourneyGameState::RemovePlayer( idPlayer* player ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); if( round < 1 || round > maxRound ) { return; } for( int i = 0; i < MAX_ARENAS; i++ ) { idPlayer** players = GetArenaPlayers( i ); if( players[ 0 ] == player || players[ 1 ] == player ) { rvTourneyArena& arena = arenas[ i ]; idPlayer* remainingPlayer = players[ 0 ] == player ? players[ 1 ] : players[ 0 ]; bool arenaInProgress = arena.GetState() == AS_ROUND || arena.GetState() == AS_WARMUP || arena.GetState() == AS_SUDDEN_DEATH; bool remainingIsWinner = (remainingPlayer == arena.GetWinner()); int remainingIndex = (remainingPlayer == arena.GetPlayers()[ 0 ]) ? 0 : 1; arena.RemovePlayer( player ); // both players have disconnected from this arena, or the winner has disconnected, just return if( (!arena.GetPlayers()[ 0 ] && !arena.GetPlayers()[ 1 ]) || (!arenaInProgress && remainingPlayer && !remainingIsWinner) ) { arena.Clear(); tourneyHistory[ round - 1 ][ i ].playerOneNum = -1; tourneyHistory[ round - 1 ][ i ].playerOne[ 0 ] = '\0'; tourneyHistory[ round - 1 ][ i ].playerTwoNum = -1; tourneyHistory[ round - 1 ][ i ].playerTwo[ 0 ] = '\0'; return; } assert( remainingPlayer ); // if this arena is in progress, try restarting // ATVI DevTrack #13196 - do not put the bye player into a game with the abandonned player anymore // if ( arenaInProgress && byeArena >= 0 && arenas[ byeArena / round ].GetWinner() ) { if ( 0 ) { idPlayer* byePlayer = arenas[ byeArena / round ].GetWinner(); // reset history for this new round tourneyHistory[ round - 1 ][ i ].playerOneNum = -1; tourneyHistory[ round - 1 ][ i ].playerOne[ 0 ] = '\0'; tourneyHistory[ round - 1 ][ i ].playerTwoNum = -1; tourneyHistory[ round - 1 ][ i ].playerTwo[ 0 ] = '\0'; arena.Clear(); arenas[ byeArena / round ].Clear(); arena.AddPlayers( remainingPlayer, byePlayer ); // place the players in the correct instance remainingPlayer->JoinInstance( i ); byePlayer->JoinInstance( i ); remainingPlayer->ServerSpectate( false ); byePlayer->ServerSpectate( false ); gameLocal.mpGame.SetPlayerTeamScore( remainingPlayer, 0 ); gameLocal.mpGame.SetPlayerTeamScore( byePlayer, 0 ); gameLocal.Printf( "rvTourneyManager::RemovePlayer() - %s will face %s in arena %d\n", remainingPlayer->GetUserInfo()->GetString( "ui_name" ), byePlayer->GetUserInfo()->GetString( "ui_name" ), i ); byeArena = -1; // this arena is ready to play arena.Ready(); } else { // if the arena was in progress and didn't get a bye player to step in, this becomes a bye // arena - clear the tourney history if( arenaInProgress ) { tourneyHistory[ round - 1 ][ i ].playerOneNum = -1; tourneyHistory[ round - 1 ][ i ].playerOne[ 0 ] = '\0'; tourneyHistory[ round - 1 ][ i ].playerOneScore = -1; tourneyHistory[ round - 1 ][ i ].playerTwoNum = -1; tourneyHistory[ round - 1 ][ i ].playerTwo[ 0 ] = '\0'; tourneyHistory[ round - 1 ][ i ].playerTwoScore = -1; } else { // since the player is disconnecting, write the history for this round if( remainingIndex == 0 ) { tourneyHistory[ round - 1 ][ i ].playerOneNum = remainingPlayer->entityNumber; tourneyHistory[ round - 1 ][ i ].playerOne[ 0 ] = '\0'; tourneyHistory[ round - 1 ][ i ].playerOneScore = gameLocal.mpGame.GetTeamScore( remainingPlayer ); } else { tourneyHistory[ round - 1 ][ i ].playerTwoNum = remainingPlayer->entityNumber; tourneyHistory[ round - 1 ][ i ].playerTwo[ 0 ] = '\0'; tourneyHistory[ round - 1 ][ i ].playerTwoScore = gameLocal.mpGame.GetTeamScore( remainingPlayer ); } } } return; } } } int rvTourneyGameState::GetNextActiveArena( int arena ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); for( int i = arena + 1; i < MAX_ARENAS; i++ ) { if( arenas[ i ].GetState() != AS_INACTIVE && arenas[ i ].GetState() != AS_DONE ) { return i; } } for( int i = 0; i < arena; i++ ) { if( arenas[ i ].GetState() != AS_INACTIVE && arenas[ i ].GetState() != AS_DONE ) { return i; } } return arena; } int rvTourneyGameState::GetPrevActiveArena( int arena ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); for( int i = arena - 1; i >= 0; i-- ) { if( arenas[ i ].GetState() != AS_INACTIVE && arenas[ i ].GetState() != AS_DONE ) { return i; } } for( int i = MAX_ARENAS - 1; i > arena; i-- ) { if( arenas[ i ].GetState() != AS_INACTIVE && arenas[ i ].GetState() != AS_DONE ) { return i; } } return arena; } void rvTourneyGameState::SpectateCycleNext( idPlayer* player ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); assert( gameLocal.isServer || player->IsFakeClient() ); rvTourneyArena& spectatingArena = arenas[ player->GetArena() ]; idPlayer** players = spectatingArena.GetPlayers(); if( !players[ 0 ] || !players[ 1 ] || players[ 0 ]->spectating || players[ 1 ]->spectating ) { // setting the spectated client to ourselves will unlock us player->spectator = player->entityNumber; return; } if( player->spectator != players[ 0 ]->entityNumber && player->spectator != players[ 1 ]->entityNumber ) { player->spectator = players[ 0 ]->entityNumber; } else if( player->spectator == players[ 0 ]->entityNumber ) { player->spectator = players[ 1 ]->entityNumber; } else if( player->spectator == players[ 1 ]->entityNumber ) { if( gameLocal.time > player->lastArenaChange ) { if ( GetNumArenas() <= 0 ) { player->JoinInstance( 0 ); } else { player->JoinInstance( GetNextActiveArena( player->GetArena() ) ); } player->lastArenaChange = gameLocal.time + 2000; player->spectator = player->entityNumber; } } // this is where the listen server updates it's gui spectating elements if ( gameLocal.GetLocalPlayer() == player ) { rvTourneyArena& arena = arenas[ player->GetArena() ]; if( arena.GetPlayers()[ 0 ] == NULL || arena.GetPlayers()[ 1 ] == NULL || (player->spectating && player->spectator != arena.GetPlayers()[ 0 ]->entityNumber && player->spectator != arena.GetPlayers()[ 1 ]->entityNumber) ) { gameLocal.mpGame.tourneyGUI.ArenaSelect( player->GetArena(), TGH_BRACKET ); } else if( arena.GetPlayers()[ 0 ] == player || player->spectator == arena.GetPlayers()[ 0 ]->entityNumber ) { gameLocal.mpGame.tourneyGUI.ArenaSelect( player->GetArena(), TGH_PLAYER_ONE ); } else if( arena.GetPlayers()[ 1 ] == player || player->spectator == arena.GetPlayers()[ 1 ]->entityNumber ) { gameLocal.mpGame.tourneyGUI.ArenaSelect( player->GetArena(), TGH_PLAYER_TWO ); } gameLocal.mpGame.tourneyGUI.UpdateScores(); } } void rvTourneyGameState::SpectateCyclePrev( idPlayer* player ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); assert( gameLocal.isServer || player->IsFakeClient() ); rvTourneyArena& spectatingArena = arenas[ player->GetArena() ]; idPlayer** players = spectatingArena.GetPlayers(); if( !players[ 0 ] || !players[ 1 ] || players[ 0 ]->spectating || players[ 1 ]->spectating ) { // setting the spectated client to ourselves will unlock us player->spectator = player->entityNumber; return; } if( player->spectator != players[ 0 ]->entityNumber && player->spectator != players[ 1 ]->entityNumber ) { if( gameLocal.time > player->lastArenaChange ) { if ( GetNumArenas() <= 0 ) { player->JoinInstance( 0 ); } else { player->JoinInstance( GetPrevActiveArena( player->GetArena() ) ); } player->lastArenaChange = gameLocal.time + 2000; rvTourneyArena& newSpectatingArena = arenas[ player->GetArena() ]; idPlayer** newPlayers = newSpectatingArena.GetPlayers(); if( !newPlayers[ 0 ] || !newPlayers[ 1 ] || newPlayers[ 0 ]->spectating || newPlayers[ 1 ]->spectating ) { // setting the spectated client to ourselves will unlock us player->spectator = player->entityNumber; return; } player->spectator = newPlayers[ 1 ]->entityNumber; } } else if( player->spectator == players[ 0 ]->entityNumber ) { player->spectator = player->entityNumber; } else if( player->spectator == players[ 1 ]->entityNumber ) { player->spectator = players[ 0 ]->entityNumber; } // this is where the listen server updates it gui spectating elements if( gameLocal.GetLocalPlayer() == player ) { rvTourneyArena& arena = arenas[ player->GetArena() ]; if( arena.GetPlayers()[ 0 ] == NULL || arena.GetPlayers()[ 1 ] == NULL || (player->spectating && player->spectator != arena.GetPlayers()[ 0 ]->entityNumber && player->spectator != arena.GetPlayers()[ 1 ]->entityNumber) ) { gameLocal.mpGame.tourneyGUI.ArenaSelect( player->GetArena(), TGH_BRACKET ); } else if( arena.GetPlayers()[ 0 ] == player || player->spectator == arena.GetPlayers()[ 0 ]->entityNumber ) { gameLocal.mpGame.tourneyGUI.ArenaSelect( player->GetArena(), TGH_PLAYER_ONE ); } else if( arena.GetPlayers()[ 1 ] == player || player->spectator == arena.GetPlayers()[ 1 ]->entityNumber ) { gameLocal.mpGame.tourneyGUI.ArenaSelect( player->GetArena(), TGH_PLAYER_TWO ); } gameLocal.mpGame.tourneyGUI.UpdateScores(); } } void rvTourneyGameState::UpdateTourneyBrackets( void ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); gameLocal.mpGame.tourneyGUI.SetupTourneyHistory( startingRound, round - 1, tourneyHistory ); } void rvTourneyGameState::UpdateTourneyHistory( int round ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); if ( round >= MAX_ROUNDS ) { assert( false ); gameLocal.Error( "rvTourneyGameState::UpdateTourneyHistory: MAX_ROUNDS exceeded" ); return; } for( int i = 0; i < MAX_ARENAS; i++ ) { // sometimes tourney history might have been updated for the current // round, so don't clobber any data if( (tourneyHistory[ round ][ i ].playerOne[ 0 ] != '\0' || tourneyHistory[ round ][ i ].playerOneNum != -1) || (tourneyHistory[ round ][ i ].playerTwo[ 0 ] != '\0' || tourneyHistory[ round ][ i ].playerTwoNum != -1) ) { continue; } tourneyHistory[ round ][ i ].playerOne[ 0 ] = '\0'; tourneyHistory[ round ][ i ].playerOneNum = -1; tourneyHistory[ round ][ i ].playerOneScore = 0; tourneyHistory[ round ][ i ].playerTwo[ 0 ] = '\0'; tourneyHistory[ round ][ i ].playerTwoNum = -1; tourneyHistory[ round ][ i ].playerTwoScore = 0; if( arenas[ i ].GetState() == AS_DONE ) { idPlayer* playerOne = arenas[ i ].GetPlayers()[ 0 ]; idPlayer* playerTwo = arenas[ i ].GetPlayers()[ 1 ]; if( playerOne ) { tourneyHistory[ round ][ i ].playerOneNum = playerOne->entityNumber; tourneyHistory[ round ][ i ].playerOne[ MAX_TOURNEY_HISTORY_NAME_LEN - 1 ] = '\0'; tourneyHistory[ round ][ i ].playerOneScore = gameLocal.mpGame.GetTeamScore( playerOne ); } if( playerTwo ) { tourneyHistory[ round ][ i ].playerTwoNum = playerTwo->entityNumber; tourneyHistory[ round ][ i ].playerTwo[ MAX_TOURNEY_HISTORY_NAME_LEN - 1 ] = '\0'; tourneyHistory[ round ][ i ].playerTwoScore = gameLocal.mpGame.GetTeamScore( playerTwo ); } } } } /* ================ rvTourneyGameState::FirstAvailableArena Returns the first non-WARMUP arena available for use in the next round ================ */ int rvTourneyGameState::FirstAvailableArena( void ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); for( int i = 0; i < MAX_ARENAS; i++ ) { if( arenas[ i ].GetState() != AS_WARMUP ) { return i; } } // no available arenas assert( 0 ); return 0; } arenaOutcome_t* rvTourneyGameState::GetArenaOutcome( int arena ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); if( arenas[ arena ].GetState() != AS_DONE || (arenas[ arena ].GetPlayers()[ 0 ] && arenas[ arena ].GetPlayers()[ 1 ]) ) { return NULL; } return &(tourneyHistory[ round - 1 ][ arena ]); } bool rvTourneyGameState::HasBye( idPlayer* player ) { assert( IsType( rvTourneyGameState::GetClassType() ) ); if( player == NULL || player->GetArena() < 0 || player->GetArena() >= MAX_ARENAS ) { return false; } // if we're one of the players in the arena we're in, and the other player is NULL, we have a bye if( (arenas[ player->GetArena() ].GetPlayers()[ 0 ] == player || arenas[ player->GetArena() ].GetPlayers()[ 1 ] == player) && (arenas[ player->GetArena() ].GetPlayers()[ 0 ] == NULL || arenas[ player->GetArena() ].GetPlayers()[ 1 ] == NULL) ) { return true; } return false; } // simple RTTI gameStateType_t rvGameState::type = GS_BASE; gameStateType_t rvDMGameState::type = GS_DM; gameStateType_t rvTeamDMGameState::type = GS_TEAMDM; gameStateType_t rvCTFGameState::type = GS_CTF; gameStateType_t rvTourneyGameState::type = GS_TOURNEY; bool rvGameState::IsType( gameStateType_t type ) const { return ( type == rvGameState::type ); } bool rvDMGameState::IsType( gameStateType_t type ) const { return ( type == rvDMGameState::type ); } bool rvTeamDMGameState::IsType( gameStateType_t type ) const { return ( type == rvTeamDMGameState::type ); } bool rvCTFGameState::IsType( gameStateType_t type ) const { return ( type == rvCTFGameState::type ); } bool rvTourneyGameState::IsType( gameStateType_t type ) const { return ( type == rvTourneyGameState::type ); } gameStateType_t rvGameState::GetClassType( void ) { return rvGameState::type; } gameStateType_t rvDMGameState::GetClassType( void ) { return rvDMGameState::type; } gameStateType_t rvTeamDMGameState::GetClassType( void ) { return rvTeamDMGameState::type; } gameStateType_t rvCTFGameState::GetClassType( void ) { return rvCTFGameState::type; } gameStateType_t rvTourneyGameState::GetClassType( void ) { return rvTourneyGameState::type; } /* =============================================================================== riDZGameState Game state info for Dead Zone =============================================================================== */ /* ================ riDZGameState::riDZGameState ================ */ riDZGameState::riDZGameState( bool allocPrevious ) : rvGameState( false ) { Clear(); if( allocPrevious ) { previousGameState = new riDZGameState( false ); } else { previousGameState = NULL; } trackPrevious = allocPrevious; type = GS_DZ; } /* ================ riDZGameState::~riDZGameState ================ */ riDZGameState::~riDZGameState( void ) { Clear(); delete previousGameState; previousGameState = NULL; } /* ================ riDZGameState::Clear ================ */ void riDZGameState::Clear( void ) { rvGameState::Clear(); if ( previousGameState ) { riDZGameState* prevState = (riDZGameState*)previousGameState; prevState->Clear( ); } for( int i = 0; i < TEAM_MAX; i++ ) { dzStatus[ i ].state = DZ_NONE; dzStatus[ i ].clientNum = -1; } dzTriggerEnt = -1; } /* ================ riDZGameState::SendState ================ */ void riDZGameState::SendState( const idMessageSender &sender, int clientNum ) { idBitMsg outMsg; byte msgBuf[MAX_GAME_MESSAGE_SIZE]; assert( (gameLocal.isServer || gameLocal.isRepeater) && trackPrevious && type == GS_DZ ); if( clientNum == -1 && (riDZGameState&)(*this) == (riDZGameState&)(*previousGameState) ) { return; } outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_GAMESTATE ); WriteState( outMsg ); sender.Send( outMsg ); // don't update the state if we are working for a single client if ( clientNum == -1 ) { outMsg.ReadByte(); // pop off the msg ID ReceiveState( outMsg ); } } /* =============== riDZGameState::WriteState =============== */ void riDZGameState::WriteState( idBitMsg &msg ) { // send off base info rvGameState::PackState( msg ); // add DZ info PackState( msg ); } /* ================ riDZGameState::ReceiveState ================ */ void riDZGameState::ReceiveState( const idBitMsg& msg ) { assert( type == GS_DZ ); if ( !rvGameState::BaseUnpackState( msg ) ) { return; } UnpackState( msg ); if ( gameLocal.localClientNum >= 0 ) { GameStateChanged(); } (riDZGameState&)(*previousGameState) = (riDZGameState&)(*this); } /* ================ riDZGameState::PackState ================ */ void riDZGameState::PackState( idBitMsg& outMsg ) { int i; for( i = 0; i < TEAM_MAX; i++ ) { outMsg.WriteByte( dzStatus[ i ].state ); outMsg.WriteBits( dzStatus[ i ].clientNum, -( idMath::BitsForInteger( MAX_CLIENTS ) + 1 ) ); } outMsg.WriteLong(dzTriggerEnt); outMsg.WriteLong(dzShaderParm); } /* ================ riDZGameState::UnpackState ================ */ void riDZGameState::UnpackState( const idBitMsg& inMsg ) { int i; for( i = 0; i < TEAM_MAX; i++ ) { dzStatus[ i ].state = (dzState_t)inMsg.ReadByte(); dzStatus[ i ].clientNum = inMsg.ReadBits( -( idMath::BitsForInteger( MAX_CLIENTS ) + 1 ) ); } dzTriggerEnt = inMsg.ReadLong(); dzShaderParm = inMsg.ReadLong(); } /* ================ riDZGameState::SendInitialState ================ */ void riDZGameState::SendInitialState( const idMessageSender &sender, int clientNum ) { assert( type == GS_DZ ); riDZGameState* previousState = (riDZGameState*)previousGameState; riDZGameState invalidState; previousGameState = &invalidState; SendState( sender, clientNum ); previousGameState = previousState; } /* ================ riDZGameState::ControlZoneStateChanged ================ */ void riDZGameState::ControlZoneStateChanged( int team ) { if( !gameLocal.isClient && !gameLocal.isListenServer ) { return; } idPlayer* player = gameLocal.GetLocalPlayer(); if( player == NULL ) { return; } if ( dzTriggerEnt < 0 ) return; idEntity* ent = gameLocal.FindEntity(dzTriggerEnt); if ( ent ) { ent->SetShaderParm(7, dzShaderParm); } dzTriggerEnt = -1; } /* ================ riDZGameState::GameStateChanged ================ */ void riDZGameState::GameStateChanged( void ) { // detect any base state changes rvGameState::GameStateChanged(); // DZ specific stuff idPlayer* player = gameLocal.GetLocalPlayer(); if( player == NULL ) { //gameLocal.Error( "riDZGameState::GameStateChanged() - NULL local player\n" ); return; } if( currentState == GAMEREVIEW ) { // Need to clear the deadzone state at this point. ((riDZGameState*)previousGameState)->Clear(); for( int i = 0; i < TEAM_MAX; i++ ) { dzStatus[ i ].state = DZ_NONE; dzStatus[ i ].clientNum = -1; } } for( int i = 0; i < TEAM_MAX; i++ ) { if( dzStatus[ i ] == ((riDZGameState*)previousGameState)->dzStatus[ i ] ) { continue; } ControlZoneStateChanged(i); } } /* ================ riDZGameState::Run ================ */ void riDZGameState::Run( void ) { // run common stuff rvGameState::Run(); switch( currentState ) { case GAMEON: { /// Check if we're frozen (in buy mode, etc.) if( gameLocal.GetIsFrozen() ) { /// Check if it's time for freeze to wear off int unFreezeTime = gameLocal.GetUnFreezeTime(); if( gameLocal.time >= unFreezeTime ) { gameLocal.SetIsFrozen( false ); // FIXME: say "fight" } } else { /// Check if time limit has been reached if ( gameLocal.mpGame.TimeLimitHit() ) { int marineTeamScore = gameLocal.mpGame.GetScoreForTeam( TEAM_MARINE ); int stroggTeamScore = gameLocal.mpGame.GetScoreForTeam( TEAM_STROGG ); gameLocal.mpGame.PrintMessageEvent( -1, MSG_TIMELIMIT ); if( marineTeamScore > stroggTeamScore ) { /// Marines win! gameLocal.mpGame.OnDeadZoneTeamVictory( TEAM_MARINE ); } else if( marineTeamScore < stroggTeamScore ) { /// Strogg win! gameLocal.mpGame.OnDeadZoneTeamVictory( TEAM_STROGG ); } else { /// Teams are tied and time limit was hit - go to sudden death! fragLimitTimeout = 0; NewState( SUDDENDEATH ); } } } break; } case SUDDENDEATH: { int marineTeamScore = gameLocal.mpGame.GetScoreForTeam( TEAM_MARINE ); int stroggTeamScore = gameLocal.mpGame.GetScoreForTeam( TEAM_STROGG ); if( marineTeamScore > stroggTeamScore ) { /// Marines win! gameLocal.mpGame.OnDeadZoneTeamVictory( TEAM_MARINE ); } else if( marineTeamScore < stroggTeamScore ) { /// Strogg win! gameLocal.mpGame.OnDeadZoneTeamVictory( TEAM_STROGG ); } break; } } } /* ================ riDZGameState::SetDZState ================ */ void riDZGameState::SetDZState( int dz, dzState_t newState ) { assert( gameLocal.isServer && ( dz >= 0 && dz < TEAM_MAX ) && type == GS_DZ ); dzStatus[ dz ].state = newState; } /* ================ riDZGameState::operator== ================ */ bool riDZGameState::operator==( const riDZGameState& rhs ) const { if( (rvGameState&)(*this) != (rvGameState&)rhs ) { return false; } for( int i = 0; i < TEAM_MAX; i++ ) { if( dzStatus[ i ] != rhs.dzStatus[ i ] ) { return false; } } return true; } /* ================ riDZGameState::operator= ================ */ riDZGameState& riDZGameState::operator=( const riDZGameState& rhs ) { (rvGameState&)(*this) = (rvGameState&)rhs; for( int i = 0; i < TEAM_MAX; i++ ) { dzStatus[ i ] = rhs.dzStatus[ i ]; } return (*this); }
[ "joropito@23c7d628-c96c-11de-a380-73d83ba7c083" ]
[ [ [ 1, 3133 ] ] ]
fcbe7f1412dc4210451d07e89ab086e2d184266b
651639abcfc06818971a0296944703b3dd050e8d
/Pool.cpp
a2c9b3a2c57b97293dd22cdce75d8f0280dff703
[]
no_license
reanag/snailfight
5256dc373e3f3f3349f77c7e684cb0a52ccc5175
c4f157226faa31d526684233f3c5cd4572949698
refs/heads/master
2021-01-19T07:34:17.122734
2010-01-20T17:16:36
2010-01-20T17:16:36
34,893,173
0
0
null
null
null
null
UTF-8
C++
false
false
5,552
cpp
#ifndef POOL #define POOL #include <iostream> #include <vector> #include <SFML/Network.hpp> #include <SFML/System.hpp> #include "Event.hpp" #include "TargetPointChangeEvent.hpp" #include "MoveLeftEvent.hpp" #include "MoveRightEvent.hpp" #include "MoveUpEvent.hpp" #include "RollLeftEvent.hpp" #include "RollRightEvent.hpp" #include "ShotEvent.hpp" #include "Menu.hpp" using namespace std; using namespace sf; static SocketTCP mSocket; static vector<GameEvent*>* Messages; static vector<GameEvent*>* MessagesToSend; class Pool { public: int id; Pool() { Messages = new vector<GameEvent*>(); MessagesToSend = new vector<GameEvent*>(); cout<<"\nPOOL created\n"; } void start() { cout<<"\n\tSTART\n"; SocketTCP* pSocket; GameEvent* ev = new GameEvent("INIT"); GameEvent* iv = new GameEvent("INIT"); MessagesToSend->push_back(ev); Messages->push_back(iv); Thread* ThreadSendMess = new Thread(&ThreadSendMessFunc); Thread* ThreadReceiveMess = new Thread(&ThreadReceiveMessFunc, this); ThreadSendMess -> Launch(); ThreadReceiveMess -> Launch(); cout<<"\n\tstart END\n"; } //Figyeli a socket-et, ha stringet kap cast-olja a megfelelő típusú üzenetté, és a Messages vektorba teszi. void static ThreadReceiveMessFunc(void* UserData) { cout << "\nReceiveThread START\n"; while (true) { string s = ReceiveMess(mSocket); cout<<"ezt kaptam: "<<s; if(s.at(0) == '1'){ TargetPointChangeEvent* ge = new TargetPointChangeEvent(s); Messages->push_back(ge); } if(s.at(0) == '2'){ MoveLeftEvent* mle = new MoveLeftEvent(); Messages->push_back(mle); } if(s.at(0) =='3'){ MoveRightEvent* mre = new MoveRightEvent(); Messages->push_back(mre); } if(s.at(0) =='4'){ MoveUpEvent* mue = new MoveUpEvent(); Messages->push_back(mue); } if(s.at(0) =='5'){ MoveDownEvent* mde = new MoveDownEvent(); Messages->push_back(mde); } if(s.at(0) =='7'){ RollLeftEvent* rle = new RollLeftEvent(); Messages->push_back(rle); } if(s.at(0) =='8'){ RollRightEvent* rre = new RollRightEvent(); Messages->push_back(rre); } if(s.at(0) =='9'){ GranadeThrowedEvent* gte = new GranadeThrowedEvent(); Messages->push_back(gte); } if(s.at(0)=='#'){//"#ShotEvent"){ cout<<"Loves van"; ShotEvent* se = new ShotEvent(); Messages->push_back(se); } else { GameEvent* ge = new GameEvent(s); Messages->push_back(ge); } } } //visszatér a Messages vektor méretével int GetMessSize(){ return Messages->size(); } void static ThreadSendMessFunc(void* UserData) { cout << "\nSendThread Start\n"; while(true){ if(MessagesToSend->size() > 0){ GameEvent* ev; if(MessagesToSend->size()>0){ ev = MessagesToSend->at(0); } else { ev = new GameEvent("NULL"); } string s; s = ev->EventToString(); // cout<<"ezt kuldom: "<<s; if(s.at(0)!='N'){ SendMess(mSocket, s); vector<GameEvent*>::iterator i = MessagesToSend->begin(); MessagesToSend->erase(i); } } //Sleep(1.0f); } } //MessagesToSend vektorba beletesz egy eventet static void AddMess(GameEvent* ev){ MessagesToSend->push_back(ev); // cout<<ev->EventToString()<<" lett hozzaadva\n\n"; } //Messages vektorba beletesz egy eventet static void AddMess2(GameEvent* ev){ Messages->push_back(ev); } //Visszatér a Messages vektor első elemével, majd kitörli azt static GameEvent* GetMess(){ GameEvent* tp; if(Messages->size()>0){ tp = Messages->at(0); } else { tp = new GameEvent("NULL"); } if(tp->EventToString().at(1) == 'N'){ } else { vector<GameEvent*>::iterator i = Messages->begin(); Messages->erase(i); } return tp; } static void SendMess(SocketTCP mSock, string s) { char ToSend[s.size()]; for (int i =0; i<s.size(); i++) { ToSend[i] = s[i]; } if (mSock.Send(ToSend, sizeof(ToSend)) != sf::Socket::Done) { cout<< "\n\nError in SendMess"; } else { // cout<< "Message sent"; } } static string ReceiveMess(SocketTCP mSock) { string s=""; char Message[50]; std::size_t Received; if (mSock.Receive(Message, sizeof(Message), Received) != sf::Socket::Done) return "-"; for (int i = 0; i<40; i++) { s+= Message[i]; } return s; } }; #endif
[ "[email protected]@96fa20d8-dc45-11de-8f20-5962d2c82ea8", "gergely.bacso@96fa20d8-dc45-11de-8f20-5962d2c82ea8" ]
[ [ [ 1, 21 ], [ 23, 24 ], [ 26, 33 ], [ 36, 53 ], [ 55, 186 ] ], [ [ 22, 22 ], [ 25, 25 ], [ 34, 35 ], [ 54, 54 ] ] ]
57f4d243238226abece6ac291d86a602dd1f3ba0
a0155e192c9dc2029b231829e3db9ba90861f956
/MFInstWizard/MFInstWizard.cpp
a5daf500f41ba54ed8f31b90292f2861044ff7cb
[]
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
ISO-8859-1
C++
false
false
25,817
cpp
// MFInstWizard.cpp : Definiert das Klassenverhalten für die Anwendung. // #include "stdafx.h" #include "MFInstWizard.h" #include "ServerDlg.h" #include "FoldersDlg.h" #include "DomainDetailsDlg.h" #include "SmtpHomeDlg.h" #include "WelcomeDlg.h" #include "ProgressDlg.h" #include "LicenseDlg.h" #include "InstallDlg.h" #include "netwareapi.h" #include "../MailFilter/Main/MFVersion.h" #include <ios> #include <iostream> #include <fstream> #include <string> #ifdef _DEBUG #define new DEBUG_NEW #endif // CInstApp BEGIN_MESSAGE_MAP(CInstApp, CWinApp) // ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() // CInstApp-Erstellung CInstApp::CInstApp() { this->mf_SharedInstallation = FALSE; this->mf_AppDir = "SYS:MAILFLT"; this->mf_InstallLegacyVersion = FALSE; this->mf_GroupwiseVersion6 = TRUE; this->mf_LoadMailFilter = TRUE; NetwareApi api; api.GetPrimaryServerName(&this->mf_ServerName); } // Das einzige CInstApp-Objekt CInstApp theApp; void WriteLog(CString szText) { CTime time = CTime::GetCurrentTime(); std::ofstream logFile("mfinstall.log",std::ios_base::app); logFile << time.Format("%c") << ": " << szText << std::endl; logFile.close(); } static unsigned int MF_CreateDirectory(CString szDirectoryName) { CFileStatus status; WriteLog(" CreateDirectory: " + szDirectoryName); if (CFile::GetStatus(szDirectoryName,status)) { if (!(status.m_attribute | 0x10)) { WriteLog(" ==> ERROR rc 1: file already exists, but !directory"); return 1; } // ok directory already exists, no need to create it WriteLog(" ==> rc 0: directory already exists"); return 0; } else { // no status --> nothing there, go create. if (CreateDirectory(szDirectoryName,NULL) == FALSE) { WriteLog(" ==> ERROR rc 2: error when creating directory"); return 2; } WriteLog(" ==> rc 0: directory created"); return 0; } } static unsigned int MF_CopyFile(CProgressCtrl *progressCtrl, CString sourcePath, CString destPath, CString fileName) { unsigned int rc = 0; char szTemp[40]; progressCtrl->SetPos(progressCtrl->GetPos()+1); WriteLog(" Copy file " + fileName + " from " + sourcePath + " to " + destPath); rc = CopyFile(sourcePath + "\\" + fileName, destPath + "\\" + fileName, FALSE); CString buf = " => rc: "; itoa(rc,szTemp,10); WriteLog(buf + szTemp); return rc; } static unsigned int MF_CreateNCFFile(CString szNCFFilename, CString szExecLine) { DeleteFile(szNCFFilename); WriteLog(" CreateNCFFile: " + szNCFFilename + " - '" + szExecLine + "'"); FILE* fp = fopen(szNCFFilename,"w"); if (fp == NULL) { WriteLog(" => ERROR fopen failed"); return 1; } fprintf(fp,"#\n# %s\n# NCF File created by MailFilter Installation Wizard\n",szNCFFilename); fprintf(fp,"%s\n",szExecLine); fprintf(fp,"#\n#\n\n"); fclose(fp); WriteLog(" => done"); return 0; } // CInstApp Initialisierung BOOL CInstApp::InitInstance() { // InitCommonControls() ist für Windows XP erforderlich, wenn ein Anwendungsmanifest // die Verwendung von ComCtl32.dll Version 6 oder höher zum Aktivieren // von visuellen Stilen angibt. Ansonsten treten beim Erstellen von Fenstern Fehler auf. InitCommonControls(); CWinApp::InitInstance(); // Standardinitialisierung // Wenn Sie diese Features nicht verwenden und die Größe // der ausführbaren Datei verringern möchten, entfernen Sie // die nicht erforderlichen Initialisierungsroutinen. // Ändern Sie den Registrierungsschlüssel unter dem Ihre Einstellungen gespeichert sind. // TODO: Ändern Sie diese Zeichenfolge entsprechend, // z.B. zum Namen Ihrer Firma oder Organisation. SetRegistryKey(_T("Hofstaedtler IE GmbH\\MailFilter")); CBitmap bmpWizHeader; bmpWizHeader.LoadBitmap(IDB_WIZHEADER); CBitmap bmpWizSpecial; bmpWizSpecial.LoadBitmap(IDB_WIZBMP); HICON hIcon; hIcon = CWinApp::LoadIcon(IDR_MAINFRAME); bool bErrors = false; bool bNonFatalErrors = false; CString szError = ""; CString szNonFatalError = ""; do { bErrors = false; szError = ""; // "ui" wizard = ask user bleh and blah { bNonFatalErrors = false; szNonFatalError = ""; CPropertySheet wizard("MailFilter Installation Wizard",NULL, 0, bmpWizSpecial, NULL, bmpWizHeader); wizard.SetWizardMode(); // 0x198128| wizard.m_psh.dwFlags |= PSH_WIZARD97|PSH_HEADER|PSH_USEHICON; wizard.m_psh.hInstance = AfxGetInstanceHandle(); wizard.m_psh.hIcon = hIcon; WriteLog("MailFilter Installation Wizard "MAILFILTERVERNUM); WelcomeDlg welcomeDlg; ServerDlg serverDlg; LicenseDlg licenseDlg; FoldersDlg foldersDlg; DomainDetailsDlg domainDlg; SmtpHomeDlg smtpHomeDlg; InstallDlg installDlg; wizard.AddPage(&welcomeDlg); wizard.AddPage(&serverDlg); wizard.AddPage(&licenseDlg); wizard.AddPage(&foldersDlg); wizard.AddPage(&domainDlg); wizard.AddPage(&smtpHomeDlg); wizard.AddPage(&installDlg); if (wizard.DoModal() == ID_WIZFINISH) { // act "wizard" = progress dialog CPropertySheet progress("MailFilter Installation Wizard",NULL, 0, NULL, NULL, bmpWizHeader); progress.SetWizardMode(); progress.m_psh.dwFlags |= PSH_WIZARD97|PSH_HEADER|PSH_USEHICON; progress.m_psh.hInstance = AfxGetInstanceHandle(); progress.m_psh.hIcon = hIcon; ProgressDlg progressDlg; progress.AddPage(&progressDlg); progress.Create(); progress.ShowWindow(SW_SHOW); progress.SetWizardButtons(PSWIZB_DISABLEDFINISH); CProgressCtrl *progressCtrl = &((ProgressDlg*)progress.GetPage(0))->m_ProgressCtrl; progressCtrl->SetRange(0,60); progressCtrl->SetPos(5); CStatic* progressTextCtrl = (CStatic*)((ProgressDlg*)progress.GetPage(0))->GetDlgItem(IDC_PROGRESSTEXT); progress.UpdateWindow(); // do what we want NetwareApi api; api.SelectServerByName(this->mf_ServerName); WriteLog("***************************************************************"); WriteLog("New Installation to server " + this->mf_ServerName + ", AppDir: " + this->mf_AppDir); if (this->mf_IsUpgrade) WriteLog(" *** UPGRADE UPGRADE UPGRADE ***"); WriteLog("Gwia.Cfg: " + this->mf_GwiaCfgPath); WriteLog("License Key: " + this->mf_LicenseKey); if (this->mf_GwiaResetSmtpHome) WriteLog("Gwia.Cfg shall be patched"); else WriteLog("Gwia.Cfg shall not be patched"); unsigned int server_majorVersion; unsigned int server_minorVersion; unsigned int server_revision; if (!api.GetServerVersion(server_majorVersion,server_minorVersion,server_revision)) { WriteLog("Unable to get server version!"); szError = "The NetWare Server Version could not be determined. Please check if you are still connected to the target server."; bErrors = true; } else { CString verbuf; verbuf.Format(" Raw Server Version Data: %d.%d.%d",server_majorVersion,server_minorVersion,server_revision); WriteLog(verbuf); this->mf_InstallLegacyVersion = false; if (server_majorVersion < 5) { WriteLog(" Server reported Version < 5... too old for us."); szError = "The NetWare Server reported Product Version 4.x or earlier. MailFilter requires at least NetWare 5.0."; bErrors = true; } else { if ((server_majorVersion == 5) && (server_minorVersion == 0)) { WriteLog(" Server 5.0"); this->mf_InstallLegacyVersion = true; } if ((server_majorVersion == 5) && (server_minorVersion == 10) && (server_revision < 6)) { WriteLog(" Server 5.1 SP5 or earlier"); this->mf_InstallLegacyVersion = true; } if ((server_majorVersion == 5) && (server_minorVersion == 10) && (server_revision >= 6)) { WriteLog(" Server 5.1 SP6 or newer"); this->mf_InstallLegacyVersion = false; } if ((server_majorVersion == 6) && (server_minorVersion == 0) && (server_revision < 3)) { WriteLog(" Server 6.0 SP2 or earlier"); this->mf_InstallLegacyVersion = true; } if ((server_majorVersion == 6) && (server_minorVersion == 0) && (server_revision >= 3)) { WriteLog(" Server 6.0 SP3 or newer"); this->mf_InstallLegacyVersion = false; } if ((server_majorVersion == 6) && (server_minorVersion == 50) && (server_revision == 0)) { WriteLog(" Server 6.5 with no service pack"); this->mf_InstallLegacyVersion = true; } if ((server_majorVersion == 6) && (server_minorVersion == 50) && (server_revision >= 1)) { WriteLog(" Server 6.5 SP1 or newer"); this->mf_InstallLegacyVersion = false; } if ((server_majorVersion == 6) && (server_minorVersion > 50)) { WriteLog(" Server 6.x (x=newer than 50)"); this->mf_InstallLegacyVersion = false; } if (server_majorVersion > 6) { WriteLog(" Server 7 or newer (OES?)"); this->mf_InstallLegacyVersion = false; } } } if (!bErrors) { if (this->mf_InstallLegacyVersion) { WriteLog("Installing LEGACY Version"); AfxMessageBox("Note: Your NetWare server does not meet all requirements for the full MailFilter Version.\n" "Instead, a limited functionality version of MailFilter (MFLT50.NLM) will be installed.\n" "If you want to use MailFilter's full power, please upgrade to a recent NetWare Support Pack and run this wizard again!", MB_ICONEXCLAMATION, 0); } else WriteLog("Installing LIBC Version"); } CString szAppConfigDest = ""; CString szAppBinaryDest = ""; CString szAppBaseDest = ""; CString szServerAppBaseDest = ""; CString szServerAppConfigDest = ""; CString szServerAppBinaryDest = ""; if (!bErrors) { if (this->mf_SharedInstallation == FALSE) { szAppBaseDest = "\\\\" + this->mf_ServerName; szAppBaseDest += "\\" + this->mf_AppDir; szAppBaseDest.Replace(":","\\"); if (szAppBaseDest.Right(1) == "\\") szAppBaseDest.Delete(szAppBaseDest.GetLength()); szAppConfigDest = szAppBaseDest + "\\ETC"; szAppBinaryDest = szAppBaseDest + "\\BIN"; szServerAppBaseDest = this->mf_AppDir; if (szServerAppBaseDest.Right(1) == "\\") szServerAppBaseDest.Delete(szServerAppBaseDest.GetLength()); szServerAppConfigDest = szServerAppBaseDest + "\\ETC"; szServerAppBinaryDest = szServerAppBaseDest + "\\BIN"; } else { szAppBaseDest = "\\\\" + this->mf_ServerName + "\\SYS\\"; szAppBinaryDest = szAppBaseDest + "SYSTEM"; szAppConfigDest = szAppBaseDest + "ETC\\MAILFLT"; szAppBaseDest += "SYSTEM"; szServerAppBaseDest = "SYS:"; szServerAppBinaryDest = szServerAppBaseDest + "\\SYSTEM"; szServerAppConfigDest = szServerAppBaseDest + "\\ETC\\MAILFLT"; szServerAppBaseDest += "SYSTEM"; } WriteLog("Local Directories: " + szAppBaseDest + ", " + szAppConfigDest + ", " + szAppBinaryDest); WriteLog("Server Directories: " + szServerAppBaseDest + ", " + szServerAppConfigDest + ", " + szServerAppBinaryDest); } if (!bErrors) { CString mfpathCfg = "\\\\" + this->mf_ServerName + "\\SYS\\ETC\\MFPATH.CFG"; WriteLog("mfpathCfg = "+mfpathCfg); FILE* mfpathFile = fopen(mfpathCfg,"wt"); if (mfpathFile != NULL) { fprintf(mfpathFile,"%s",szServerAppConfigDest); fclose(mfpathFile); WriteLog("Wrote: "+szServerAppConfigDest); } else { bNonFatalErrors = true; szNonFatalError = "Could not write MailFilter Location file (SYS:ETC\\MFPATH.CFG). The Installation Wizard may not find the MailFilter installation when upgrading."; WriteLog("ERROR: Cannot write mfpath.cfg"); } } if (!bErrors) { // 1: Create Directories WriteLog("1 - Create Directories."); int rc = 0; rc = MF_CreateDirectory(szAppBaseDest); if (!rc) MF_CreateDirectory(szAppBinaryDest); if (!rc) MF_CreateDirectory(szAppConfigDest); if (!rc) MF_CreateDirectory(szAppConfigDest+"\\DEFAULTS"); switch (rc) { case 0: // kay break; case 1: szError = "The target directory could not be created: a file already exists at this place. Please delete it before continuing."; bErrors = true; break; default: szError = "The target directory could not be created: an unknown error occoured."; bErrors = true; break; } } if (!bErrors) { // 2: Copy Files WriteLog("2 - Copy files."); progressCtrl->SetPos(progressCtrl->GetPos()+1); progressTextCtrl->SetWindowText("Copying files"); { CString sourceBase = ".\\SERVER\\"; CString sourceBin = sourceBase + "BIN\\"; CString sourceEtc = sourceBase + "ETC\\"; // base szError = "Could not copy NCF file."; if (!this->mf_IsUpgrade) if (MF_CopyFile(progressCtrl, sourceBase, szAppBaseDest, "MFSTOP.NCF") == FALSE) bErrors = true; // binaries if (!bErrors) szError = "Could not copy NLM file."; DeleteFile(szAppBinaryDest + "\\MAILFLT.NLM"); DeleteFile(szAppBinaryDest + "\\MFLT50.NLM"); DeleteFile(szAppBinaryDest + "\\MFCONFIG.NLM"); DeleteFile(szAppBinaryDest + "\\MFUPGR.NLM"); DeleteFile(szAppBinaryDest + "\\MFREST.NLM"); DeleteFile(szAppBinaryDest + "\\MFNRM.NLM"); if (MF_CopyFile(progressCtrl, sourceBin, szAppBinaryDest, "MAILFLT.NLM") == FALSE) bErrors = true; if (MF_CopyFile(progressCtrl, sourceBin, szAppBinaryDest, "MFLT50.NLM") == FALSE) bErrors = true; if (MF_CopyFile(progressCtrl, sourceBin, szAppBinaryDest, "MFAVA.NLM") == FALSE) bErrors = true; if (MF_CopyFile(progressCtrl, sourceBin, szAppBinaryDest, "MFCONFIG.NLM") == FALSE) bErrors = true; // config if (!bErrors) szError = "Could not copy configuration file."; if (MF_CopyFile(progressCtrl, sourceEtc, szAppConfigDest+"\\DEFAULTS", "FILTERS.BIN") == FALSE) bErrors = true; if (MF_CopyFile(progressCtrl, sourceEtc, szAppConfigDest+"\\DEFAULTS", "MAILCOPY.TPL") == FALSE) bErrors = true; if (MF_CopyFile(progressCtrl, sourceEtc, szAppConfigDest+"\\DEFAULTS", "REPORT.TPL") == FALSE) bErrors = true; if (MF_CopyFile(progressCtrl, sourceEtc, szAppConfigDest+"\\DEFAULTS", "RINSIDE.TPL") == FALSE) bErrors = true; if (MF_CopyFile(progressCtrl, sourceEtc, szAppConfigDest+"\\DEFAULTS", "ROUTRCPT.TPL") == FALSE) bErrors = true; if (MF_CopyFile(progressCtrl, sourceEtc, szAppConfigDest+"\\DEFAULTS", "ROUTSNDR.TPL") == FALSE) bErrors = true; if (!this->mf_IsUpgrade) { if (MF_CopyFile(progressCtrl, sourceEtc, szAppConfigDest, "FILTERS.BIN") == FALSE) bErrors = true; if (MF_CopyFile(progressCtrl, sourceEtc, szAppConfigDest, "MAILCOPY.TPL") == FALSE) bErrors = true; if (MF_CopyFile(progressCtrl, sourceEtc, szAppConfigDest, "REPORT.TPL") == FALSE) bErrors = true; if (MF_CopyFile(progressCtrl, sourceEtc, szAppConfigDest, "RINSIDE.TPL") == FALSE) bErrors = true; if (MF_CopyFile(progressCtrl, sourceEtc, szAppConfigDest, "ROUTRCPT.TPL") == FALSE) bErrors = true; if (MF_CopyFile(progressCtrl, sourceEtc, szAppConfigDest, "ROUTSNDR.TPL") == FALSE) bErrors = true; } if (!bErrors) szError = ""; } } if (!bErrors) { // 3: Create ncf files WriteLog("3 - Create NCF files."); progressCtrl->SetPos(progressCtrl->GetPos()+1); progressTextCtrl->SetWindowText("Creating NCF files"); { CString mfbinary = "LOAD "; if (!((server_majorVersion == 5) && (server_minorVersion == 0))) mfbinary += "PROTECTED "; mfbinary += szServerAppBinaryDest + "\\MAILFLT.NLM "; if (this->mf_InstallLegacyVersion) mfbinary = szServerAppBinaryDest + "\\MFLT50.NLM "; CString line; if (!this->mf_IsUpgrade) { // mfstart.ncf line = mfbinary + "-t server " + szServerAppConfigDest; MF_CreateNCFFile(szAppBaseDest + "\\MFSTART.NCF", line); // mfinst.ncf line = mfbinary + "-t install " + szServerAppConfigDest; MF_CreateNCFFile(szAppBaseDest + "\\MFINST.NCF", line); } else { // on an upgrade only write a new MFINST.NCF // mfinst.ncf line = mfbinary + "-t upgrade " + szServerAppConfigDest; MF_CreateNCFFile(szAppBaseDest + "\\MFINST.NCF", line); } // mfconfig.ncf // line = "%if !loaded mailflt&mflt50 then cmd " + mfbinary; // line += "-t config " + szServerAppConfigDest; // MF_CreateNCFFile(szAppBaseDest + "\\MFCONFIG.NCF", line); } } if ((this->mf_IsUpgrade) && (!bErrors)) { // 4: Unload MailFilter on upgrade WriteLog("4 - Upgrade: Unload MailFilter"); progressCtrl->SetPos(progressCtrl->GetPos()+1); progressTextCtrl->SetWindowText("Unloading MailFilter NLMs..."); szError = "An error occoured while unloading a MailFilter NLM. Please check the System Console/Logger Screen!"; if (!api.ExecuteNCF("MFSTOP.NCF")) bErrors = true; if (!api.UnloadNLM("MAILFLT.NLM")) bErrors = true; if (!api.UnloadNLM("MFLT50.NLM")) bErrors = true; bErrors = false; if (!bErrors) szError = ""; } if (!bErrors) { // 5: Create Configuration WriteLog("5 - Create Install Configuration."); progressCtrl->SetPos(progressCtrl->GetPos()+1); if (!this->mf_IsUpgrade) progressTextCtrl->SetWindowText("Creating configuration files"); else progressTextCtrl->SetWindowText("Upgrading configuration files"); { WriteLog("Writing install.cfg as " + szAppConfigDest + "\\INSTALL.CFG"); DeleteFile(szAppConfigDest + "\\INSTALL.CFG"); std::ofstream installCfg(szAppConfigDest + "\\INSTALL.CFG"); if (installCfg.is_open()) { installCfg << "# created by MFInstallWizard" << std::endl; if (!this->mf_IsUpgrade) { installCfg << "/config-mode=install" << std::endl; WriteLog(" /config-mode=install"); installCfg << "/domain=" << this->mf_DomainName << std::endl; WriteLog(" /domain="+this->mf_DomainName); installCfg << "/hostname=" << this->mf_HostName << std::endl; WriteLog(" /hostname="+this->mf_HostName); installCfg << "/config-directory=" << szAppConfigDest << std::endl; WriteLog(" /config-directory="+szAppConfigDest); installCfg << "/gwia-version=" << (this->mf_GroupwiseVersion6 ? 600 : 550) << std::endl; WriteLog(this->mf_GroupwiseVersion6 ? " /gwia-version=600" : " /gwia-version=550"); installCfg << "/home-gwia=" << this->mf_GwiaDHome << std::endl; WriteLog(" /home-gwia="+this->mf_GwiaDHome); installCfg << "/home-mailfilter=" << this->mf_GwiaSmtpHome << std::endl; WriteLog(" /home-mailfilter="+this->mf_GwiaSmtpHome); installCfg << "/licensekey=" << this->mf_LicenseKey << std::endl; WriteLog(" /licensekey="+this->mf_LicenseKey); installCfg << "/config-importfilterfile=" << szAppConfigDest + "\\FILTERS.BIN" << std::endl; WriteLog(" /config-importfilterfile="+ szAppConfigDest + "\\FILTERS.BIN"); } else { installCfg << "/config-mode=upgrade" << std::endl; WriteLog(" /config-mode=upgrade"); installCfg << "/config-deleteinstallfile=yes" << std::endl; WriteLog(" /config-deleteinstallfile=yes"); } installCfg.close(); progressCtrl->SetPos(progressCtrl->GetPos()+1); progressTextCtrl->SetWindowText("Contacting Server Agent ..."); WriteLog("Executing NCF: " + szServerAppBaseDest + "\\MFINST.NCF"); if (!api.ExecuteNCF(szServerAppBaseDest + "\\MFINST.NCF")) { bErrors = true; szError = "MFINST.NCF could not be executed on the Server. Please check the Server Console for errors!"; } } else { WriteLog(" => ofstream() failed"); bErrors = true; if (!this->mf_IsUpgrade) szError = "Could not write initial configuration file."; else szError = "Could not write Configuration Update instructions file."; } } } if ((!this->mf_IsUpgrade) && (!bErrors)) { // 6: patch autoexec.ncf WriteLog("6 - patch autoexec.ncf."); progressCtrl->SetPos(progressCtrl->GetPos()+5); progressTextCtrl->SetWindowText("Updating Server Configuration"); { CString szAutoexec = "\\\\" + this->mf_ServerName + "\\SYS\\AUTOEXEC.NCF"; CString szAutoexecBackup = szAutoexec + ".MFOLD"; WriteLog(" Using Autoexec.ncf from " + szAutoexec); WriteLog(" Saving copy to " + szAutoexecBackup); // make backup CopyFile(szAutoexec,szAutoexecBackup, FALSE); std::ofstream autoexecFile(szAutoexec,std::ios_base::app); autoexecFile << std::endl; autoexecFile << "# Added to load MailFilter" << std::endl; CString theLine = szServerAppBaseDest + "\\MFSTART.NCF"; WriteLog(" Adding command: " + theLine); autoexecFile << theLine << std::endl; autoexecFile << std::endl; autoexecFile.close(); } } if ((!this->mf_IsUpgrade) && (!bErrors)) { // 7: patch gwia.cfg WriteLog("7 - patch gwia.ncf."); progressCtrl->SetPos(progressCtrl->GetPos()+5); progressTextCtrl->SetWindowText("Updating GroupWise Configuration"); if (this->mf_GwiaResetSmtpHome) { CString oldGwiaCfg = this->mf_GwiaCfgPath + ".MFOLD"; WriteLog(" -> Setting SmtpHome to " + this->mf_GwiaSmtpHome); WriteLog(" -> Saving copy to " + oldGwiaCfg); CopyFile(this->mf_GwiaCfgPath,oldGwiaCfg, FALSE); WriteLog(" Reading old file..."); static const std::string::size_type npos = -1; size_t i; std::string smtpHomeLine = "/smtphome=" + this->mf_GwiaSmtpHome+ "\r\n"; std::string line; std::string value; FILE* oldcfgfile = fopen(oldGwiaCfg,"rt"); if (oldcfgfile == NULL) { bErrors = true; szError = "The backup copy of gwia.cfg could not be opened. It is usually named gwia.cfg.mfold."; } else { bool bPatchedSmtpHome = false; char szBuf[2048]; std::ofstream newcfgfile(this->mf_GwiaCfgPath); while (!feof(oldcfgfile)) { memset(szBuf,0,2047); fgets(szBuf,2040,oldcfgfile); line = szBuf; if (line[0] == '/') { value = ""; i = line.find("="); if (i == npos) i = line.find("-"); if (i != npos) value = line.substr(++i); if (value[0] == '"') value = value.substr(1); if (value[value.length()-1] == '"') value = value.substr(0,value.length()-1); // /PARAMETER if (stricmp(line.substr(0,9).c_str(),"/smtphome") == 0) { line = smtpHomeLine; bPatchedSmtpHome = true; WriteLog(" > overriding old smtphome setting"); } } newcfgfile << line;// << std::endl; } if (!bPatchedSmtpHome) { WriteLog(" > adding new smtphome setting"); newcfgfile << smtpHomeLine << std::endl; } newcfgfile.close(); fclose(oldcfgfile); } } else WriteLog(" -> NOT modifying gwia.cfg - user said NO!"); } if (!bErrors) { // 8: load mailfilter if yes WriteLog("8 - load mailfilter if yes"); progressCtrl->SetPos(progressCtrl->GetPos()+1); if (this->mf_LoadMailFilter == TRUE) { progressTextCtrl->SetWindowText("Starting MailFilter"); WriteLog(" -> yes"); if (!api.ExecuteNCF(szServerAppBaseDest + "\\MFSTART.NCF")) { WriteLog(" -> ExecuteNCF returned error?"); bNonFatalErrors = true; szNonFatalError = "MailFilter could not be started on the Server. Please check the System Console/Logger Screen for errors."; } } } // Done. if (!bErrors) { // present finish dialog int nLower; int nUpper; progressCtrl->GetRange(nLower,nUpper); progressCtrl->SetPos(nUpper); progressTextCtrl->SetWindowText("Completed."); progress.UpdateWindow(); WriteLog("----- -------------------------------------------------"); if (bNonFatalErrors) { WriteLog("----- -------------------------------------------------"); WriteLog("----- Non-Fatal Error: "); WriteLog("----- " + szNonFatalError); AfxMessageBox(szNonFatalError, MB_ICONEXCLAMATION); } WriteLog("----- Installation Finished successfully."); WriteLog("----- -------------------------------------------------"); progress.SetWizardButtons(PSWIZB_FINISH); progress.RunModalLoop(MLF_SHOWONIDLE); } else { progressTextCtrl->SetWindowText("Aborted."); WriteLog("----- -------------------------------------------------"); WriteLog("----- Installation aborted:"); WriteLog("----- " + szError); WriteLog("----- -------------------------------------------------"); AfxMessageBox("An Error occoured while installing MailFilter on the target server:\n " + szError + "\n\nPlease correct the problem and follow the Installation Wizard steps again.", MB_ICONERROR); progress.DestroyWindow(); } } } } while (bErrors); // Da das Dialogfeld geschlossen wurde, FALSE zurückliefern, so dass wir die // Anwendung verlassen, anstatt das Nachrichtensystem der Anwendung zu starten. return FALSE; }
[ [ [ 1, 750 ] ] ]
2b27ce6806199e0ae239fa01a92544dfb2e5aba4
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/idcodermessagedigest.hpp
d683e8228b1925f6bd7ee685c6f774c6ce369c18
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
3,623
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'IdCoderMessageDigest.pas' rev: 6.00 #ifndef IdCoderMessageDigestHPP #define IdCoderMessageDigestHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <IdCoder.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Idcodermessagedigest { //-- type declarations ------------------------------------------------------- typedef Byte T64BitRecord[8]; typedef Byte T128BitRecord[16]; typedef unsigned T4x4LongWordRecord[4]; typedef unsigned T4x4x4LongWordRecord[4][4]; typedef unsigned T16x4LongWordRecord[16]; typedef Byte T160BitRecord[20]; typedef Byte T384BitRecord[48]; class DELPHICLASS TIdCoderMD2; class PASCALIMPLEMENTATION TIdCoderMD2 : public Idcoder::TIdCoder { typedef Idcoder::TIdCoder inherited; protected: Byte FBuffer[16]; Byte FChecksum[16]; int FCount; Byte FCheckSumScore; Byte FState[16]; Byte FX[48]; virtual void __fastcall Coder(void); virtual void __fastcall CompleteCoding(void); public: __fastcall virtual TIdCoderMD2(Classes::TComponent* AOwner); virtual void __fastcall Reset(void); virtual void __fastcall FillSamples(Classes::TStrings* AStringList); virtual void __fastcall SetBufferSize(unsigned ASize); public: #pragma option push -w-inl /* TIdCoder.Destroy */ inline __fastcall virtual ~TIdCoderMD2(void) { } #pragma option pop }; class DELPHICLASS TIdCoderMD4; class PASCALIMPLEMENTATION TIdCoderMD4 : public Idcoder::TIdCoder { typedef Idcoder::TIdCoder inherited; protected: unsigned FBitsProcessed; unsigned FBuffer[4]; Byte FCount[8]; bool FDone; virtual void __fastcall Coder(void); virtual void __fastcall CompleteCoding(void); virtual unsigned __fastcall func_f(unsigned x, unsigned y, unsigned z); virtual unsigned __fastcall func_g(unsigned x, unsigned y, unsigned z); virtual unsigned __fastcall func_h(unsigned x, unsigned y, unsigned z); public: __fastcall virtual TIdCoderMD4(Classes::TComponent* AOwner); virtual void __fastcall Reset(void); virtual void __fastcall FillSamples(Classes::TStrings* AStringList); virtual void __fastcall SetBufferSize(unsigned ASize); public: #pragma option push -w-inl /* TIdCoder.Destroy */ inline __fastcall virtual ~TIdCoderMD4(void) { } #pragma option pop }; class DELPHICLASS TIdCoderMD5; class PASCALIMPLEMENTATION TIdCoderMD5 : public TIdCoderMD4 { typedef TIdCoderMD4 inherited; protected: virtual void __fastcall Coder(void); virtual unsigned __fastcall func_g(unsigned x, unsigned y, unsigned z); virtual unsigned __fastcall func_i(unsigned x, unsigned y, unsigned z); public: __fastcall virtual TIdCoderMD5(Classes::TComponent* AOwner); virtual void __fastcall FillSamples(Classes::TStrings* AStringList); public: #pragma option push -w-inl /* TIdCoder.Destroy */ inline __fastcall virtual ~TIdCoderMD5(void) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- } /* namespace Idcodermessagedigest */ using namespace Idcodermessagedigest; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // IdCoderMessageDigest
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 124 ] ] ]
8f8089275798bf6d3f93903e3bca72fa5e12b7f4
b22c254d7670522ec2caa61c998f8741b1da9388
/dependencies/OpenSceneGraph/include/osg/Vec2d
b5a8e6d3bdd1e36766142b446a4b8d725ddb537a
[]
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
5,792
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #ifndef OSG_VEC2D #define OSG_VEC2D 1 #include <osg/Vec2f> namespace osg { /** General purpose double pair, uses include representation of * texture coordinates. * No support yet added for double * Vec2d - is it necessary? * Need to define a non-member non-friend operator* etc. * BTW: Vec2d * double is okay */ class Vec2d { public: /** Type of Vec class.*/ typedef double value_type; /** Number of vector components. */ enum { num_components = 2 }; value_type _v[2]; Vec2d() {_v[0]=0.0; _v[1]=0.0;} Vec2d(value_type x,value_type y) { _v[0]=x; _v[1]=y; } inline Vec2d(const Vec2f& vec) { _v[0]=vec._v[0]; _v[1]=vec._v[1]; } inline operator Vec2f() const { return Vec2f(static_cast<float>(_v[0]),static_cast<float>(_v[1]));} inline bool operator == (const Vec2d& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1]; } inline bool operator != (const Vec2d& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1]; } inline bool operator < (const Vec2d& v) const { if (_v[0]<v._v[0]) return true; else if (_v[0]>v._v[0]) return false; else return (_v[1]<v._v[1]); } inline value_type* ptr() { return _v; } inline const value_type* ptr() const { return _v; } inline void set( value_type x, value_type y ) { _v[0]=x; _v[1]=y; } inline value_type& operator [] (int i) { return _v[i]; } inline value_type operator [] (int i) const { return _v[i]; } inline value_type& x() { return _v[0]; } inline value_type& y() { return _v[1]; } inline value_type x() const { return _v[0]; } inline value_type y() const { return _v[1]; } inline bool valid() const { return !isNaN(); } inline bool isNaN() const { return osg::isNaN(_v[0]) || osg::isNaN(_v[1]); } /** Dot product. */ inline value_type operator * (const Vec2d& rhs) const { return _v[0]*rhs._v[0]+_v[1]*rhs._v[1]; } /** Multiply by scalar. */ inline const Vec2d operator * (value_type rhs) const { return Vec2d(_v[0]*rhs, _v[1]*rhs); } /** Unary multiply by scalar. */ inline Vec2d& operator *= (value_type rhs) { _v[0]*=rhs; _v[1]*=rhs; return *this; } /** Divide by scalar. */ inline const Vec2d operator / (value_type rhs) const { return Vec2d(_v[0]/rhs, _v[1]/rhs); } /** Unary divide by scalar. */ inline Vec2d& operator /= (value_type rhs) { _v[0]/=rhs; _v[1]/=rhs; return *this; } /** Binary vector add. */ inline const Vec2d operator + (const Vec2d& rhs) const { return Vec2d(_v[0]+rhs._v[0], _v[1]+rhs._v[1]); } /** Unary vector add. Slightly more efficient because no temporary * intermediate object. */ inline Vec2d& operator += (const Vec2d& rhs) { _v[0] += rhs._v[0]; _v[1] += rhs._v[1]; return *this; } /** Binary vector subtract. */ inline const Vec2d operator - (const Vec2d& rhs) const { return Vec2d(_v[0]-rhs._v[0], _v[1]-rhs._v[1]); } /** Unary vector subtract. */ inline Vec2d& operator -= (const Vec2d& rhs) { _v[0]-=rhs._v[0]; _v[1]-=rhs._v[1]; return *this; } /** Negation operator. Returns the negative of the Vec2d. */ inline const Vec2d operator - () const { return Vec2d (-_v[0], -_v[1]); } /** Length of the vector = sqrt( vec . vec ) */ inline value_type length() const { return sqrt( _v[0]*_v[0] + _v[1]*_v[1] ); } /** Length squared of the vector = vec . vec */ inline value_type length2( void ) const { return _v[0]*_v[0] + _v[1]*_v[1]; } /** Normalize the vector so that it has length unity. * Returns the previous length of the vector. */ inline value_type normalize() { value_type norm = Vec2d::length(); if (norm>0.0) { value_type inv = 1.0/norm; _v[0] *= inv; _v[1] *= inv; } return( norm ); } }; // end of class Vec2d /** multiply by vector components. */ inline Vec2d componentMultiply(const Vec2d& lhs, const Vec2d& rhs) { return Vec2d(lhs[0]*rhs[0], lhs[1]*rhs[1]); } /** divide rhs components by rhs vector components. */ inline Vec2d componentDivide(const Vec2d& lhs, const Vec2d& rhs) { return Vec2d(lhs[0]/rhs[0], lhs[1]/rhs[1]); } } // end of namespace osg #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 190 ] ] ]
65a9130319239943b976a2efc9245f8cdefa808c
19cc679323aee582f207a701a543f7ac5e87e2b1
/util/eagle-fu/awtools.inc
53f5d8cd1beffaecfc2dc40968ccd8750e3e801f
[]
no_license
machinaut/circuits
3d17f8c3438aeeba69bf6ad897245e53a1c3f015
adcd36a22dd9f38650f94722821231ed8f767307
refs/heads/master
2020-04-14T19:15:27.070115
2011-08-30T22:14:32
2011-08-30T22:14:32
1,357,703
1
1
null
null
null
null
UTF-8
C++
false
false
61,402
inc
//"awtools.ulp" - include file containing useful procedures and functions //(C) 2011-06-14 Andreas Weidner #require 5.0303 //Earlier EAGLE versions (from 5.0 upwards) MAY be able to run these functions, //but were not properly tested #usage "en:---<br>\n" "<font color=red><b>Include-File:</b></font> " "This file is used by several programs and cannot be run on its own.", "de:---<br>\n" "<font color=red><b>Include-File:</b></font> " "Diese Datei wird von diversen Programmen verwendet und ist nicht " "selbständig lauffähig." //General definitions enum {dlgSpace=6}; string AWExitCommand=""; //PROCEDURES FOR STRING MANIPULATION ------------------------------------------ string AWTrim(string Text) { //Removes leading and trailing blanks, tabs and line feeds from TEXT string NewText,Character; NewText=Text; //Remove leading blanks and tabs Character=strsub(NewText,0,1); while ((Character==" ") || (Character=="\t") || (Character=="\n")) { NewText=strsub(NewText,1); Character=strsub(NewText,0,1); } //Ditto with trailing ones Character=strsub(NewText,strlen(NewText)-1); while ((Character==" ") || (Character=="\t") || (Character=="\n")) { NewText=strsub(NewText,0,strlen(NewText)-1); Character=strsub(NewText,strlen(NewText)-1); } return NewText; } string AWReplace(string Text,string From,string To) { //Replaces all (case-sensitive) occurrences of the string FROM in the string //TEXT by the string TO and returns the resulting string int Pos; Pos=strstr(Text,From); while (Pos!=-1) { Text=strsub(Text,0,Pos)+To+strsub(Text,Pos+strlen(From)); Pos=strstr(Text,From,Pos+strlen(To)); } return Text; } string AWReplaceText(string Text,string From,string To) { //Replaces all (case-insensitive) occurrences of the string FROM in the //string TEXT by the string TO and returns the resulting string string LowerText; int Pos; //Use the lowercase strings for searching, but return the contents of the //original string From=strlwr(From); LowerText=strlwr(Text); Pos=strstr(LowerText,From); while (Pos!=-1) { Text=strsub(Text,0,Pos)+To+strsub(Text,Pos+strlen(From)); LowerText=strsub(LowerText,0,Pos)+To+strsub(LowerText,Pos+strlen(From)); Pos=strstr(LowerText,From,Pos+strlen(To)); } return Text; } string AWReplaceVal(string Text,string From,int To) { //Replaces all (case-sensitive) occurrences of the string FROM in the string //TEXT by the character with the EAGLE character code TO int Pos; //Force the character code into the range 0..255 To=max(min(To,255),0); Pos=strstr(Text,From); while (Pos!=-1) { Text=strsub(Text,0,Pos)+"?"+strsub(Text,Pos+strlen(From)); Text[Pos]=To; Pos=strstr(Text,From,Pos+1); } return Text; } string AWText2Script(string Text,int Backslashes,int ExclamationMarks) { //Converts the string TEXT so that it can be used in a script (each single //quote replaced by two single quotes). If BACKSLASHES!=0, each single //backslash is replaced by two backslashes. If EXCLAMATIONMARKS!=0, each //exclamation mark is escaped with a backslash) int Pos; //Double all single quotes Pos=strstr(Text,"'"); while (Pos!=-1) { Text=strsub(Text,0,Pos+1)+strsub(Text,Pos); Pos=strstr(Text,"'",Pos+2); } //Double all backslashes, if desired if (Backslashes) { Pos=strstr(Text,"\\"); while (Pos!=-1) { Text=strsub(Text,0,Pos+1)+strsub(Text,Pos); Pos=strstr(Text,"\\",Pos+2); } } //Escape exclamation marks, if desired if (ExclamationMarks) { Pos=strstr(Text,"!"); while (Pos!=-1) { Text=strsub(Text,0,Pos)+"\\"+strsub(Text,Pos); Pos=strstr(Text,"!",Pos+2); } } return Text; } string AWHTMLText(string Text,int Backslashes) { //Converts the TEXT so that it can be displayed in an HTML display context //(e.g., replaces '<' by '&lt;' etc. If BACKSLASHES!=0, backslashes are //converted to '\\' string Result; Result=AWReplace(AWReplace(AWReplace(Text,"<","&lt;"),">","&gt;"),"\n", "<br>\n"); if (Backslashes) Result=AWReplace(Result,"\\","\\\\"); return Result; } string AWEscapeString(string Text,int EscapeBars,int EscapeEquals) { //Escapes special characters of the string TEXT with a backslash: '\' is //changed to '\\', a linefeed to '\n' and a tab to '\t'. Additionally, if //ESCAPEBARS!=0, '|' is changed to '\b', and if ESCAPEEQUALS!=0, '=' is //changed to '\e' Text=AWReplace(AWReplace(AWReplace(Text,"\\","\\\\"),"\n","\\n"),"\t","\\t"); if (EscapeBars) Text=AWReplace(Text,"|","\\b"); if (EscapeEquals) Text=AWReplace(Text,"=","\\e"); return Text; } string AWUnescapeString(string Text) { //Searches the string TEXT for characters escaped with the previous function //and replaces the escape sequences with the original characters. If an //invalid escape sequence is found, a question mark is inserted int Pos; string Char; Pos=strstr(Text,"\\"); while (Pos>-1) { Char=strsub(Text,Pos+1,1); if (Char=="n") Text=strsub(Text,0,Pos)+"\n"+strsub(Text,Pos+2); else if (Char=="b") Text=strsub(Text,0,Pos)+"|"+strsub(Text,Pos+2); else if (Char=="e") Text=strsub(Text,0,Pos)+"="+strsub(Text,Pos+2); else if (Char=="t") Text=strsub(Text,0,Pos)+"\t"+strsub(Text,Pos+2); else if (Char=="\\") Text=strsub(Text,0,Pos+1)+strsub(Text,Pos+2); else Text=strsub(Text,0,Pos)+"?"+strsub(Text,Pos+2); Pos=strstr(Text,"\\",Pos+1); } return Text; } string AWTodayText() { //Returns the current date in international form (YYYY-MM-DD) return t2string(time(),"yyyy-MM-dd"); } string AWNowText(int Seconds) { //Returns the current date and time in international form, either with //(SECONDS!=0) or without (SECONDS=0) seconds (YYYY-MM-DD HH:MM:SS) if (Seconds) return t2string(time(),"yyyy-MM-dd, hh:mm:ss"); return t2string(time(),"yyyy-MM-dd, hh:mm"); } string AWBoolString(int Bool) { //Depending on the Boolean value BOOL, returns either '0' or '1' if (Bool) return "1"; else return "0"; } //PROCEDURES FOR STRING LOCALISATION ------------------------------------------ int AWIsGerman() { //Returns 1, if a German EAGLE version is running (0 otherwise) if (language()!="de") return 1; return 0; } string AWLocalise(string EnglishText,string GermanText) { //Depending on the current EAGLE language, returns ENGLISHTEXT or GERMANTEXT //and replaces HTML syntax by the proper EAGLE characters string Text; //Select the desired language string if (AWIsGerman()) Text=GermanText; else Text=EnglishText; //Replace HTML syntax (not necessary anymore, because EAGLE can now cope with //Unicode, but just in case and to be backward-compatible) Text=AWReplaceVal(Text,"&auml;",228); Text=AWReplaceVal(Text,"&Auml;",196); Text=AWReplaceVal(Text,"&ouml;",246); Text=AWReplaceVal(Text,"&Ouml;",214); Text=AWReplaceVal(Text,"&uuml;",252); Text=AWReplaceVal(Text,"&Uuml;",220); Text=AWReplaceVal(Text,"&szlig;",223); Text=AWReplaceVal(Text,"&micro;",181); Text=AWReplaceVal(Text,"&deg;",176); Text=AWReplaceVal(Text,"&plusmn;",177); return Text; } void AWStatus(string EnglishText,string GermanText) { //Depending on the current EAGLE language, displays either ENGLISHTEXT or //GERMANTEXT in the status bar status(AWLocalise(EnglishText,GermanText)); } //PROCEDURES FOR GENERAL FILE ACCESS ----------------------------------------- int AWDirEntryExists(string Name) { //Returns 1 if the file (or directory) with the NAME exists (0 otherwise) string Files[]; int Nr; //Throw away any trailing slash if (strsub(Name,strlen(Name)-1)=="/") Name=strsub(Name,0,strlen(Name)-1); //Check, if the directory entry exists Nr=fileglob(Files,Name); if (Nr==0) return 0; return 1; } string AWEAGLEPath() { //Returns the base path of the EAGLE installation (this is assumed to be the //parent directory of the ULP file itself) including directory separator string FileName; FileName=filedir(argv[0]); return filedir(strsub(FileName,0,strlen(FileName)-1)); } string AWGetULPSettingsPath(int ShowWarning) { //Returns the complete name of a special folder for ULP settings. Previously, //ULP settings were stored in the ULP's directory. Unfortunately, if EAGLE //resides on a server, this is undesired, so another location for storing is //necessary. Therefore, the settings path is defined as having the name //'settings' and residing parallel to one of the given project paths. If such //a path does NOT exist and SHOWWARNING=1, then the user is asked to create //the folder manually or cancel the ULP. Returns an empty string if still //no such folder is available. If SHOWWARNING=2, the user cannot cancel the //dialog, but MUST create the directory properly int Nr,Pos,Count,Result=0; string Path,Warning; //Repeat the search for a settings folder until one is available or the user //cancels the operation while (Result==0) { Count=0; Warning=""; //Go through all of EAGLE's project paths for (Nr=0;Nr<16;Nr++) { Path=path_epf[Nr]; if (Path=="") continue; //Ignore the project path when it contains the import/export autoscripts Pos=strstr(Path,"autoscripts"); if (Pos>=0) continue; //Ignore the path if it is not a subdirectory of another path Pos=strrstr(Path,"/"); if (Pos<0) continue; //Replace the last project path subdirectory name by 'settings'. This //could be the complete settings path Path=strsub(Path,0,Pos+1)+"settings"; //If this path was NOT already checked previously, add it to the warning //that might be displayed later Pos=strstr(Warning,Path); if (Pos<0) { Warning=Warning+"&nbsp;&nbsp;&nbsp;"+Path+"<br>"; Count++; } //If the folder does not exist, try with the next project path if (!AWDirEntryExists(Path)) continue; //If the folder exists, return its name return Path; } //If no settings folder could be found and warnings are desired, show //a message and give the user the chance to create the settings folder //manually. Afterwards, the folder search process is repeated if (ShowWarning) { if (Count<2) Warning=AWLocalise("the following<br>directory (with write access)", "das folgende Verzeichnis<br>(mit Schreibrechten) händisch "+ "erzeugen")+":<br>"+Warning; else Warning=AWLocalise("one of the<br>following directories (with write "+ "access)","eins der folgenden<br>Verzeichnisse (mit Schreibrechten)"+ " händisch erzeugen")+":<br>"+Warning; if (ShowWarning==1) { Warning=":<html><nobr>"+AWLocalise("This ULP needs to save certain "+ "settings to work properly.<br>Therefore, you should <b>now</b> " "manually create ","Dieses ULP muß bestimmte Einstellungen "+ "speichern, um korrekt zu<br>funktionieren. Dazu sollten Sie <b>"+ "jetzt</b> ")+Warning; Warning+="<br>"+AWLocalise("Select 'Retry' after successfully "+ "creating the directory, or<br>'Cancel' to exit the ULP.","Wählen "+ "Sie \"Wiederholen\", nachdem Sie das Verzeichnis erfolgreich<br>"+ "erzeugt haben, oder \"Abbrechen\", um das ULP zu beenden."); Result=dlgMessageBox(Warning,AWLocalise("Retry","Wiederholen"), AWLocalise("Cancel","Abbrechen")); } else { Warning=":<html><nobr>"+AWLocalise("In order for some ULPs to "+ "properly save their settings,<br>you should <b>now</b> manually "+ "create ","Damit einige ULPs ihre Einstellungen speichern<br>"+ "können, sollten Sie <b>jetzt</b> ")+Warning; Warning+="<br>"+AWLocalise("Select 'OK' after sucessfully creating "+ "the directory.","Wählen Sie \"OK\", nachdem Sie das Verzeichnis"+ "<br>erfolgreich erzeugt haben."); Result=dlgMessageBox(Warning); } } else //The user cancelled the dialog box Result=1; } //No settings folder found return ""; } //PROCEDURES FOR INI FILE (OR ATTRIBUTE) ACCESS ------------------------------- string AWIniFile[]; //All string entries from the current INI file //(or INI attribute) int AWIniFileLineCount=0; //Number of lines in this INI file int AWReadIniFile(string FileName) { //Reads all lines from the INI file FILENAME and puts them into the //corresponding global array. Returns 1 if the INI file could be read and //contains at least one line. The resulting strings still contain the escape //characters \\ (for backslash), \n (for linefeed), \t (for tab), \b (for //bar) and \e (for equal) int Lines,Nr; //Exit if the INI file does not exist AWIniFile[0]=""; AWIniFileLineCount=0; FileName=AWTrim(FileName); if ((!FileName) || (!AWDirEntryExists(FileName))) return 0; //Read the file. Exit, if it contains no lines Lines=fileread(AWIniFile,FileName); if (Lines<1) return 0; //By some reason, the EAGLE function 'lookup' doesn't work properly if the //INI file contains empty lines. Therefore, replace empty lines by lines //containing a space character for (Nr=0;Nr<Lines;Nr++) if (AWIniFile[Nr]=="") AWIniFile[Nr]=" "; //The INI file contains some lines return 1; } int AWReadIniAttribute(string AttributeName,int Schematic,int Board) { //Reads the INI settings from the global attribute ATTRIBUTENAME. The first //information in the corresponding attribute value should be an international //date plus time of the last change. The attribute is extracted from both //schematics and board, the newer one of these is taken as source for all //INI settings that are put into the corresponding global array. Returns 1 if //at least one setting was found. The resulting strings still contain the //escape characters \\ (for backslash), \n (for linefeed), \t (for tab), \b //(for bar) and \e (for equal) string SettingsSCH="",SettingsBRD="",Settings=""; int Lines,Nr; //Remove the current INI array contents AWIniFile[0]=""; AWIniFileLineCount=0; AttributeName=strupr(AWTrim(AttributeName)); //Read the schematics attribute, if available if ((Schematic) && (project.schematic)) project.schematic(S) S.attributes(A) if (A.name==AttributeName) SettingsSCH=AWTrim(A.value); //Read the board attribute, if available if ((Board) && (project.board)) project.board(B) B.attributes(A) if (A.name==AttributeName) SettingsBRD=AWTrim(A.value); //Select the newer of both if ((SettingsSCH) && (SettingsBRD)) { if (SettingsSCH>SettingsBRD) Settings=SettingsSCH; else Settings=SettingsBRD; } else if (SettingsSCH) Settings=SettingsSCH; else Settings=SettingsBRD; //Extract all lines from the attribute value. Exit, if it contains no lines if (!Settings) return 0; Lines=strsplit(AWIniFile,Settings,'|'); if (Lines<1) return 0; //By some reason, the EAGLE function 'lookup' doesn't work properly if the //INI file contains empty lines. Therefore, replace empty lines with lines //containing a space character for (Nr=0;Nr<Lines;Nr++) if (!AWIniFile[Nr]) AWIniFile[Nr]=" "; //The INI attribute contains some lines return 1; } int AWReadIniSettings(string AttributeName,string FileName) { //Reads the INI settings from the global attribute ATTRIBUTENAME, if this is //available. If not, reads the settings from the INI file FILENAME. The //INI lines are put into the corresponding global array. Returns 1 if the INI //settings could be read and contain at least one line. The resulting strings //still contain the escape characters \\ (for backslash), \n (for linefeed), //\t (for tab), \b (for bar) and \e (for equal) int OK=0; //Read the INI attribute. Exit on success if (AttributeName) OK=AWReadIniAttribute(AttributeName,1,1); if (OK) return 1; //Otherwise, read the INI file if (FileName) OK=AWReadIniFile(FileName); if (OK) return 1; return 0; } string AWReadIniString(string Key,string Default) { //Reads the KEY string from the current INI file array and returns it with //escape sequences properly converted to original characters. If no entry is //found, returns DEFAULT string Text,Char; int Pos; Text=lookup(AWIniFile,Key,1,'='); if (Text) return AWUnescapeString(Text); return Default; } string AWWriteIniString(string Key,string Text) { //Returns the string necessary to write the TEXT into the KEY entry of an INI //file or attribute. Special characters are automatically escaped with a //backslash Key=AWTrim(Key); if (Key) return AWEscapeString(Key,1,1)+"="+AWEscapeString(Text,1,1)+"|"; return AWEscapeString(Text,1,1)+"|"; } string AWWriteIniSection(string Section) { //Returns the string necessary to write the SECTION string of an INI file or //attribute. Special characters are automatically escaped with a backslash, //the section is framed by brackets Section=AWTrim(Section); if (Section) Section="["+Section+"]"; return "|"+AWWriteIniString("",Section); } int AWReadIniInt(string Key,int Minimum,int Maximum,int Default) { //Reads the KEY integer entry from the current INI file array. If the value //exceeds the range from MINIMUM to MAXIMUM, or if no entry is found, DEFAULT //is returned string IniString; int Result; IniString=lookup(AWIniFile,Key,1,'='); if (IniString=="") return Default; Result=strtol(IniString); if ((Result<Minimum) || (Result>Maximum)) Result=Default; return Result; } string AWWriteIniInt(string Key,int Value) { //Returns the string necessary to write the integer VALUE into the KEY entry //of an INI file or attribute string Text; sprintf(Text,"%d",Value); return AWWriteIniString(Key,Text); } real AWReadIniReal(string Key,real Minimum,real Maximum,real Default) { //Reads the KEY real number entry from the current INI file array. If the //value exceeds the range from MINIMUM to MAXIMUM, or if no entry is found, //DEFAULT is returned string IniString; real Result; IniString=lookup(AWIniFile,Key,1,'='); if (IniString=="") return Default; Result=strtod(IniString); if ((Result<Minimum) || (Result>Maximum)) Result=Default; return Result; } string AWWriteIniReal(string Key,real Value) { //Returns the string necessary to write the real number VALUE into the KEY //entry of an INI file or attribute string Text; sprintf(Text,"%g",Value); return AWWriteIniString(Key,Text); } int AWReadIniBool(string Key,int Default) { //Reads the KEY boolean entry from the current INI file array. If no //entry is found, returns DEFAULT return AWReadIniInt(Key,0,1,Default); } void AWWriteIniFile(string FileName,string Info,int Version,string Settings) { //Saves the INI settings SETTINGS to the file FILENAME. If VERSION!=0, this //file version number is included as a separate line. If INFO='auto', some //hint warning the user not to edit this file manually is included. If //INFO!="", this information text is included instead. Additionally, the //current time stamp is included as a separate line FileName=AWTrim(FileName); if (!FileName) return; //Include file version, if desired if (Version) Settings=AWWriteIniInt("FileVersion",Version)+Settings; //Always add a time stamp Settings=AWWriteIniString("FileTime",AWNowText(1))+Settings; //Include file information, if desired Info=AWTrim(Info); if (Info) { if (strupr(Info)=="AUTO") Settings="Used by '"+filename(argv[0])+"' - do not edit manually!|"+ Settings; else Settings=AWEscapeString(Info,1,1)+"|"+Settings; Settings="[FileInformation]|FileInfo="+Settings; } //Replace newly inserted bars by line feeds Settings=AWReplace(Settings,"|","\n"); //Write the file output(FileName) printf("%s",Settings); } string AWWriteIniAttribute(string AttributeName,string Info,int Version, string Settings,int Schematic,int Board) { //Returns the exit command string necessary to save the INI settings SETTINGS //in the global attribute ATTRIBUTENAME. If VERSION!=0, this file version //number is included as a separate line. If INFO='auto', some hint warning //the user not to edit this file manually is included. If INFO!="", this //information text is included instead. Additionally, the current time stamp //is included as a separate line. If SCHEMATIC!=0, the global attribute of //the schematic is set. If BOARD!=0, the global attribute of the board is //set. If neither SCHEMATIC nor BOARD is given, the attribute of the current //editor window is set string Text=""; //If no attribute name is given, exit AttributeName=strupr(AWTrim(AttributeName)); if (!AttributeName) return ""; //Include file version, if desired if (Version) Settings=AWWriteIniInt("FileVersion",Version)+Settings; //Always add a time stamp Settings=AWWriteIniString("FileTime",AWNowText(1))+Settings; //Include file information, if desired Info=AWTrim(Info); if (Info) { if (strupr(Info)=="AUTO") Settings="Used by '"+filename(argv[0])+"' - do not edit manually! |"+ Settings; else Settings=AWEscapeString(Info,1,1)+" |"+Settings; } //If schematic or board attributes are to be set explicitly, do this if ((Schematic) || (Board)) { if ((Schematic) && (project.schematic)) { Text+="EDIT .sch;\n"+ "ATTRIBUTE * "+AttributeName+" '"+AWText2Script(Settings,0,0)+"';\n"; } if ((Board) && (project.board)) { Text+="EDIT .brd;\n"+ "ATTRIBUTE * "+AttributeName+" '"+AWText2Script(Settings,0,0)+"';\n"; } } else //Otherwise just use the current editor window Text+="ATTRIBUTE * "+AttributeName+" '"+AWText2Script(Settings,0,0)+"';\n"; return Text; } //PROCEDURES FOR OPERATING SYSTEM DETECTION ----------------------------------- int AWIsWindows() { //Returns 1, if EAGLE is running under Windows (0 for Linux or Macintosh) if ((strsub(argv[0],0,1)=="/") && (strsub(argv[0],0,2)!="//")) return 0; return 1; } int AWIsLinux() { //Returns 1, if EAGLE is running under Linux (0 for Windows or Macintosh). //Since Linux and Macintosh cannot properly be distingished from inside ULPs, //in case a non-Windows system is found, the current system type is read out //of the 'ostype.ini' file in the settings path. If this file is not //available, the user is asked whether a Linux or Macintosh machine is used string SettingsPath=""; int SystemType=0; if (!((strsub(argv[0],0,1)=="/") && (strsub(argv[0],0,2)!="//"))) return 0; SettingsPath=AWGetULPSettingsPath(1); if (!SettingsPath) exit(0); if (AWReadIniFile(SettingsPath+"/ostype.ini")) SystemType=AWReadIniInt("SystemType",0,2,0); if (!SystemType) { SystemType=dlgMessageBox(":<html><nobr>"+AWLocalise("You are running "+ "EAGLE on either a <b>Macintosh</b> or a <b>Linux</b> machine.<br><br>"+ "Since these two cannot be properly distinguished automatically,<br>"+ "please select your current system type manually.","Sie verwenden EAGLE"+ " auf einem <b>Macintosh</b> oder unter <b>Linux</b>.<br><br>Da diese "+ "nicht automatisch unterschieden werden können, geben Sie<br>den "+ "aktuellen Systemtyp bitte manuell an."),"-&Linux","&Macintosh"); SystemType++; AWWriteIniFile(SettingsPath+"/ostype.ini","Used to distinguish between "+ "Macintosh and Linux systems - do not edit manually!",0, AWWriteIniSection("System")+AWWriteIniInt("SystemType",SystemType)); } if (SystemType==1) return 1; return 0; } int AWIsMac() { //Returns 1, if EAGLE is running on a Macintosh (0 for Windows or Linux). //Since Linux and Macintosh cannot properly be distingished from inside ULPs, //in case a non-Windows system is found, the current system type is read out //of the "ostype.ini" file in the settings path. If this file is not //available, the user is asked whether a Linux or Macintosh machine is used if (AWIsWindows()) return 0; if (AWIsLinux()) return 0; return 1; } int AWParameterFound(string Name,int Abbreviate) { //Returns 1 if the ULP was started with the (case-insensitive) command line //parameter NAME (0 otherwise). If ABBREVIATE<>0, the parameter is also found //when it was typed abbreviated int Nr; string Text; //Exit if no parameter or no name was given Name=strupr(AWTrim(Name)); if ((argc<2) || (!Name)) return 0; //Check all given parameters separately for (Nr=1;Nr<argc;Nr++) { Text=strupr(argv[Nr]); if (((Abbreviate) && (strsub(Name,0,strlen(Text))==Text)) || (Name==Text)) return 1; } //Desired parameter not found return 0; } string AWAttributeText(string Text) { int Pos; //Replace double backslashes by single ones Pos=strstr(Text,"\\\\"); while (Pos!=-1) { Text=strsub(Text,0,Pos+1)+strsub(Text,Pos+2); Pos=strstr(Text,"\\\\",Pos+1); } //Replace escaped exclamation mark my normal one Pos=strstr(Text,"\\!"); while (Pos!=-1) { Text=strsub(Text,0,Pos)+strsub(Text,Pos+1); Pos=strstr(Text,"\\!",Pos+1); } return Text; } int AWBadCharsList[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21, 22,23,24,25,26,27,28,29,30,31,127,128,129,130,131,132,133,134,135,136,137, 138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155, 156,157,158,159,160,162,164,165,166,167,168,169,173,174,175,179,180,182, 183,184,185,190,192,193,194,195,200,202,203,204,205,206,207,208,210,211, 212,213,215,217,218,219,222,227,240,245,253,254,255}; //If any of these character values is found in an edit field string, it //is probable that EAGLE does NOT correctly interpret it int AWBadChars[]; //This array holds 256 entries, each containing 0 for an acceptable character //code and 1 for a bad character void AWCreateBadIndex() { //Create the BADCHARS table from the BADCHARSLIST int Nr; //Set all characters to "acceptable" for (Nr=0;Nr<256;Nr++) AWBadChars[Nr]=0; for (Nr=0;Nr<256;Nr++) AWBadChars[AWBadCharsList[Nr]]=1; } string AWRealToStr(real x) { //Returns the real number X formatted as string (fixed point, no exponent) string Text; int DotPos,Nr; sprintf(Text,"%f",x); DotPos=strstr(Text,"."); if (DotPos>=0) for (Nr=strlen(Text)-1;Nr>=DotPos;Nr--) { if ((Text[Nr]!='0') && (Text[Nr]!='.')) break; else Text=strsub(Text,0,strlen(Text)-1); } return Text; } string AWIntToStr(int x) { //Returns the integer X formatted as string string Text; sprintf(Text,"%d",x); return Text; } // Procedures for file access and file name manipulation ---------------------- string AWProjectName(void) { //Returns one of the filenames of the current project. If no project is //available, an empty string is returned if (project.board) project.board(B) return B.name; if (project.schematic) project.schematic(S) return S.name; return ""; } string AWProjectFolder(void) { //Returns the name of the current project's folder (including trailing //slash). If no project is available, an empty string is returned string Result; Result=AWProjectName(); if (Result) Result=filedir(Result); return Result; } string AWSafeFileName(string Text,string SubFolder,string Message) { //Converts spaces IN THE FILENAME PART of the string TEXT (and NOT in the //path, because the path of the current project cannot be renamed) to //underscores. Additionally, if SUBFOLDER is given and the subfolder exists //on the drive, this is inserted between the pathname and the filename. If //the SUBFOLDER does NOT exist and a MESSAGE is defined, this message is //shown to enable the user to create the folder manually. Converting the //spaces is necessary, because even if some TeX versions can cope with spaces //in filenames, most DVI previewers cannot. Since one cannot force people NOT //to use the bloody spaces in their filenames, these must be corrected before //processing string Directory,FileName; int Pos; //Extract pathname and filename from the string and convert spaces Directory=filedir(Text); FileName=AWReplace(filename(Text)," ","_"); //Take the filename without extension and replace all dots by underscores //(PDFLaTeX cannot cope with dots in filenames) FileName=AWReplace(filesetext(FileName,""),".","_")+fileext(FileName); //Add the subfolder name, if available if (SubFolder!="") { if ((!AWDirEntryExists(Directory+SubFolder)) && (Message)) { if (strstr(Message,"%s")>=0) sprintf(Message,Message,Directory+SubFolder); dlgMessageBox(Message); } if (AWDirEntryExists(Directory+SubFolder)) Directory+=SubFolder+"/"; } //Return the new complete filename return Directory+FileName; } string AWGetIniReadFileName() { //Returns the complete file name of the ULP's initialisation file in order to //read from it. If a file with the ULP's name and extension "ini" is found //in the settings path, this file is used. If not, a corresponding file is //searched in the ULP's folder. If it is not found there, either, an empty //string is returned string FileName; //Look in the settings folder for the INI file FileName=AWGetULPSettingsPath(0); if (FileName!="") { FileName+="/"+filesetext(filename(argv[0]),".ini"); if (!AWDirEntryExists(FileName)) FileName=""; } //If no file could be found, search in the ULP's folder if (FileName=="") { FileName=filesetext(argv[0],".ini"); if (!AWDirEntryExists(FileName)) FileName=""; } //Return either a correct file name or an empty string return FileName; } string AWGetIniWriteFileName() { //Returns the complete file name of the ULP's initialisation file in order to //write to it. Because the ULP's directory might well be write-protected, //the INI file may only reside in the special settings folder (which MUST //be write-enabled). If the settings folder was found, it is returned //including the ULP's name and the extension "ini". If not, the user is asked //to create the settings folder in order for the ULP to work properly. If //no settings folder is created by the user, an empty string is returned string FileName; FileName=AWGetULPSettingsPath(1); if (FileName!="") FileName+="/"+filesetext(filename(argv[0]),".ini"); return FileName; } int AWExecuteProgram(string FileName,string Parameters,int Wait) { string CommandLine=""; //Exit, if the file doesn't exist if ((!FileName) || (!AWDirEntryExists(FileName))) return -1; if (AWIsWindows()) { if (!Wait) //Under Windows, EAGLE can NOT decently start a program and immediately //return to the ULP: The help file mentions the use of 'cmd.exe', but //this 1. opens an undesired DOS shell and 2. doesn't work properly, //anyway. Therefore, run the compiled Delphi executable //'startprogram.exe', which itself starts the desired program and //immediately returns. In this case, the desired program is put into //a command line argument, which makes it necessary to convert slashes //to backslashes in order to run everything properly CommandLine="\""+filedir(argv[0])+"startprogram.exe\" \""+ AWReplace(FileName,"/","\\")+"\""; else //If EAGLE should wait for the program to finish, it can just be called //directly CommandLine="\""+FileName+"\""; //If parameters are available, put them into the command line if (Parameters) CommandLine+=" \""+Parameters+"\""; } else if (AWIsLinux()) { //Under Linux, just put filename and parameters into the command line and //add a '&', if immediate return is desired CommandLine="'"+FileName+"'"; if (Parameters) CommandLine+=" '"+Parameters+"'"; if (!Wait) CommandLine+=" &"; } else { //On a Macintosh, programs are started with the 'open' command CommandLine="open -a '"+FileName+"'"; if (Parameters) CommandLine+=" '"+Parameters+"'"; if (!Wait) CommandLine+=" &"; } return system(CommandLine); } int AWCreateFolder(string Name) { //Creates the folder NAME including all necessary parent folders and returns //1 on success (0 otherwise) int Result; if (strsub(Name,strlen(Name)-1)=="/") Name=strsub(Name,0,strlen(Name)-1); if (AWIsWindows()) Result=system("\""+AWReplace(filedir(argv[0])+"filetools.exe\" "+ "createdir \""+Name+"\"","/","\\")); else Result=system("mkdir -p \""+Name+"\""); return (!Result) & AWDirEntryExists(Name); } int AWFolderExists(string Name) { //Returns 1 if the folder NAME exists (0 otherwise) if (!AWDirEntryExists(Name)) return 0; //If the directory entry NAME exists, it still might not be a directory, but //a file (EAGLE makes no distinction between those). Therefore, in case the //entry exists, try to create a folder of the same name. If this works, the //folder already exists. If this fails, the file system was not changed, but //the directory entry is a file and NOT a folder return AWCreateFolder(Name); } int AWFileExists(string Name) { //Returns 1 if the file (and NOT the folder) NAME exists (0 otherwise) if (!AWDirEntryExists(Name)) return 0; //If the directory entry NAME exists, it still might not be a file, but a //folder (EAGLE makes no distinction between those). Therefore, in case the //entry exists, try to create a folder of the same name. If this fails, the //file already exists. If this works, the file system was not changed, but //the directory entry is a folder and NOT a file return !AWCreateFolder(Name); } int AWDeleteFile(string Name) { //Deletes the file NAME and returns 1 on success (0 otherwise) int Result; if (strsub(Name,strlen(Name)-1)=="/") Name=strsub(Name,0,strlen(Name)-1); if (!AWFileExists(Name)) return 1; if (AWIsWindows()) Result=system("\""+AWReplace(filedir(argv[0])+"filetools.exe\" "+ "deletefile \""+Name+"\"","/","\\")); else Result=system("rm -f \""+Name+"\""); return (!Result) & (!AWFileExists(Name)); } int AWDeleteFolder(string Name) { //Deletes the folder NAME including ALL its files and subdirectories and //returns 1 on success (0 otherwise) int Result; if (strsub(Name,strlen(Name)-1)=="/") Name=strsub(Name,0,strlen(Name)-1); if (!AWFolderExists(Name)) return 1; if (AWIsWindows()) Result=system("\""+AWReplace(filedir(argv[0])+"filetools.exe\" "+ "deletedir \""+Name+"\"","/","\\")); else Result=system("rm -d -f -r \""+Name+"\""); return (!Result) & (!AWFolderExists(Name)); } int AWCopyTextFile(string SourceName,string DestinationName) { //Copies the file SOURCENAME to a new file with the name DESTINATIONNAME and //returns 1 on success (0 otherwise) int Result,Size,Lines; string Contents; if (!AWFileExists(SourceName)) return 0; Lines=fileread(Contents,SourceName); if (Lines<1) return 0; if (!AWCreateFolder(filedir(DestinationName))) return 0; output(DestinationName) printf("%s",Contents); return 1; } int AWCreateExportFolder() { //Creates the subfolder 'doc/export' in the project folder and creates its //DESCRIPTION file. Returns 1 on success (0 otherwise) string FileName; FileName=AWProjectFolder()+"doc/export/"; if (!AWCreateFolder(FileName)) return 0; output(FileName+"DESCRIPTION") printf("%s","<table width=\"100%\" cellpadding=\"5\" cellspacing=\"0\" "+ "bgcolor=\"#E0E0E0\">\n"+ "<tr><td><h3>Exported files</h3>\n"+ "...and other user-defined support files</td></tr></table><br><br>\n"+ "This folder contains bitmaps and PDF files exported by the ULPs "+ "<b>bitmap</b>\n"+ "or <b>pdfprint</b>.<p><hr>\n"+ "<b>Hints:</b>\n"+ "<ol><li>You can also place additional files here, but should avoid "+ "naming them\n"+ "with the postfixes <b>-board</b>, <b>-schematic</b> or <b>-sheet*"+ "</b>, since\n"+ "these could be automatically overwritten.</li></ol>"); return 1; } //----- LAYER PROCEDURES ----- int AWIsBRDLayerUsed(UL_BOARD B,int Layer) { //Returns 1, if something is drawn in the LAYER (but pads or vias) of the //board B (0 otherwise) B.circles(C) if (C.layer==Layer) return 1; B.elements(E) { E.texts(T) if (T.layer==Layer) return 1; E.package.circles(C) if (C.layer==Layer) return 1; E.package.polygons(P) if (P.layer==Layer) return 1; E.package.rectangles(R) if (R.layer==Layer) return 1; E.package.texts(T) if (T.layer==Layer) return 1; E.package.wires(W) if (W.layer==Layer) return 1; } B.polygons(P) if (P.layer==Layer) return 1; B.rectangles(R) if (R.layer==Layer) return 1; B.signals(S) S.wires(W) if (W.layer==Layer) return 1; B.texts(T) if (T.layer==Layer) return 1; B.wires(W) if (W.layer==Layer) return 1; return 0; } //Graphical procedures real AWTextWidth(string Text,int Start,int Stop,real TextHeight) { //Calculates the graphical text width of a substring of TEXT, beginning with //START and ending with STOP, using a vector font with the TEXTHEIGHT //Global length of all ASCII characters (from 0 to 255), each given in mm //for 10 characters of 8mm size (necessary for text width calculation) real CharWidths[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,74,25,61.5,74,74,86.5,74,42,49.5,49.5,74,74,49.5,74,37,74,74,74,74, 74,74,74,74,74,74,74,37.5,49.5,74,74,74,74,74,74,74,74,74,74,74,74,74,49.5, 74,74,74,74,74,74,74,74,74,74,74,74,74,74,74,74,74,49.5,74,49.5,74,74,37, 74,74,74,74,74,49.5,74,74,49.5,49.5,61.5,49.5,74,74,74,74,74,61.5,74,49.5, 74,74,74,74,74,74,61.5,25,61.5,74,74,110.5,98.5,110.5,12.5,49.5,49.5,24.5, 49.5,49.5,24.5,74,49.5,49.5,24.5,24.5,74,49.5,49.5,49.5,74,74,74,49.5,74, 74,49.5,74,74,74,49.5,49.5,98.5,74,24.5,74,86,49.5,49.5,25.5,61.5,37,49.5, 74,74,74,74,74,61.5,61.5,74,49.5,74,74,74,61.5,37,61.5,86,74,74,86,86,74, 74,74,49.5,74,49.5,74,74,123,74,24.5,74,49.5,49.5,49.5,49.5,74,49.5,49.5, 74,86,86,61.5,86,74,98.5,98.5,61.5,74,74,74,74,74,74,74,74,74,24.5,74,74, 110.5,61.5,74,74,74,74,61.5,49.5,61.5,49.5,49.5,74,74,74,74,74,74,61.5,74, 74,74,74,74,98.5,86,74}; int Nr; real Width; //Correct input parameters, if necessary if (Start>Stop) { Nr=Start; Start=Stop; Stop=Nr; } if (Start<0) Start=0; if (Start>=strlen(Text)) return 0; if (Stop>=strlen(Text)) Stop=strlen(Text)-1; //Sum up the measured width of all individual string characters. Since //these were measured in mm for 10 characters at 8mm heigth, divide by 80 //and multiply by the desired text height Width=0; for (Nr=Start;Nr<=Stop;Nr++) Width+=CharWidths[Text[Nr]]; return Width/80*TextHeight; } int AWGetFirstStringLength(string Text,real Height,real MaxWidth) { //Checks, whether the string TEXT with the text HEIGHT fits into the //available MAXWIDTH and returns the length of the first text line. If this //is the length of the original text, the whole string fits into the first //line. If this is smaller than the text length, it represents the length //of the first line, breaking the text at a space or behind a hyphen. If //the result is 0, the text does NOT fit in two lines. If -1 is returned, //no text was given int Pos; //If no text is given, exit with -1 if (Text=="") return 0; //If all text fits the first line, exit with text length if (AWTextWidth(Text,0,strlen(Text)-1,Height)<=MaxWidth) return strlen(Text); //2 lines are necessary. Search the break point Pos=strlen(Text)-2; while (Pos>0) { //If the text rest doesn't fit the second line, exit with 0 //if (TextWidth(Text,Pos+1,strlen(Text)-1,Height)>MaxWidth) // return 0; //For hyphens, the break point is AT the hyphen if ((Text[Pos]=='-') && (AWTextWidth(Text,0,Pos,Height)<=MaxWidth)) break; //For spaces, the break point is BEFORE the space if ((Text[Pos]==' ') && (AWTextWidth(Text,0,Pos-1,Height)<=MaxWidth)) { Pos--; break; } //Neither hyphen nor space => Shorten first line Pos--; } //No break found? Then exit with 0 if (Pos<1) return -strlen(Text); //Otherwise, return the length of the first line if (AWTextWidth(AWTrim(strsub(Text,Pos+1)),0,1000,Height)>MaxWidth) return -Pos-1; else return Pos+1; } enum {cefTooShort,cefTooLong,cefIllegalChar,cefTooWide,cefOK}; int AWCheckEditField(string Text,string FieldEnglish,string FieldGerman, int MinLength,int MaxLength,real Height,real MaxWidth,int TwoLines) { //Checks the string TEXT for problems: Warnings or error messages are //displayed if 1) the text length is less than MINLENGTH, 2) MAXLENGTH>0 and //the text length is larger than MAXLENGTH, 3) the text contains unsupported //characters or 4) the real width of the text, when written with the given //text HEIGHT and distributed over TWOLINES (if desired), exceeds the //MAXWIDTH. Depending on the problem, the user is asked whether the text //should be revised. FIELDENGLISH and FIELDGERMAN are the descriptive names //of the edit field containing the TEXT. Returns 0 if the text needs revision //and 1 if the text can be used as it is int Nr; string Message,Start,NrText; Text=AWTrim(Text); //Create the beginning of the message including the field name if ((FieldEnglish) && (FieldGerman)) Start=AWLocalise("<html>The field <b>"+FieldEnglish+"</b> ", "<html>Das Feld <b>"+FieldGerman+"</b> "); else Start=AWLocalise("<html>The edit field ","<html>Das Eingabefeld "); //Exit with error if the text is not long enough if (strlen(Text)<MinLength) { Message=":"+Start+AWLocalise("does not contain enough text<br>"+ "(at least ","enthält zuwenig Text<br>(mindestens "); sprintf(NrText,"%u",MinLength); Message+=NrText+AWLocalise(" character"," Zeichen"); if (MinLength>1) Message+=AWLocalise("s",""); Message+=AWLocalise(" necessary"," erforderlich")+")."; dlgMessageBox(Message); return cefTooShort; } //If the text is too long, show a warning. If the user decides to revise the //text, exit with error if ((MaxLength>0) && (strlen(Text)>MaxLength)) { Message="!"+Start+AWLocalise("contains too much text<br>(maximum ", "enthält zuviel Text<br>(maximal "); sprintf(NrText,"%u",MaxLength); Message+=NrText+AWLocalise(" character"," Zeichen"); if (MaxLength>1) Message+=AWLocalise("s",""); Message+=AWLocalise(" allowed).<br>If you proceed now, excess text will be "+ "deleted.<br><br>Do you want to revise the text?"," erlaubt).<br>Wenn "+ "Sie jetzt fortfahren, wird überzähliger Text gelöscht.<br><br>"+ "Möchten Sie den Text revidieren?"); if (!dlgMessageBox(Message,AWLocalise("-Revise","-Revidieren"), AWLocalise("+Proceed","+Fortfahren"))) return cefTooLong; } //Here, everything's OK if the string is empty if (strlen(Text)==0) return cefOK; //Check all characters whether they are unsupported or not for (Nr=0;Nr<strlen(Text);Nr++) if ((Text[Nr]>255) || (AWBadChars[Text[Nr]])) { //Unsupported? Then build the warning message: Message="!"+Start+AWLocalise("contains unsupported characters<br>that "+ "cannot be properly displayed","enthält nicht-unterstützte Zeichen,"+ "<br>die nicht korrekt angezeigt werden können")+":<br>&nbsp;&nbsp;"+ "&nbsp;&nbsp;"+AWLocalise("'","\""); //Insert the first 32 characters from text in HTML syntax (pay attention //with '<' and '>' signs) with unsupported characters displayed bold Nr=0; while ((Nr<32) && (Nr<strlen(Text))) { if (Text[Nr]=='<') Message+="&lt;"; else if (Text[Nr]=='>') Message+="&gt;"; else if ((Text[Nr]>255) || (AWBadChars[Text[Nr]])) Message+="<b>"+strsub(Text,Nr,1)+"</b>"; else Message+=strsub(Text,Nr,1); Nr++; } Message+=AWLocalise("'","\""); if (strlen(Text)>32) Message+="..."; //Display the warning. If the user decides to revise the text, exit //with error Message+="<br>"+AWLocalise("If you proceed now, EAGLE will replace these "+ "characters<br>by question marks or other symbols.<br><br>Do you "+ "want to revise the text?","Wenn Sie jetzt fortfahren, ersetzt EAGLE "+ "diese Buchstaben<br>durch Fragezeichen oder andere Symbole.<br><br>"+ "Möchten Sie den Text revidieren?"); if (dlgMessageBox(Message,AWLocalise("-Revise","-Revidieren"), AWLocalise("+Proceed","+Fortfahren"))==0) return cefIllegalChar; break; } Nr=0; if (MaxWidth>0) { if (TwoLines) Nr=AWGetFirstStringLength(Text,Height,MaxWidth); else if (AWTextWidth(Text,0,strlen(Text),Height)>MaxWidth) Nr=-1; } if (Nr<0) { Message="!"+Start+AWLocalise("contains text that does<br>not completely "+ "fit into the available space.<br>If you proceed now, the text will "+ "flow out of its frame.<br><br>Do you want to revise the text?", "enthält Text, der nicht<br>vollständig in den verfügbaren Platz paßt."+ "<br>Wenn Sie jetzt fortfahren, fließt der Text<br>aus seinem Rahmen "+ "heraus.<br><br>Möchten Sie den Text revidieren?"); if (!dlgMessageBox(Message,AWLocalise("-Revise","-Revidieren"), AWLocalise("+Proceed","+Fortfahren"))) return cefTooWide; } //The text is OK return cefOK; } //Procedures for manipulation of global attributes string AWReadAttribute(string Name,int SchematicFirst) { //Reads the value of the global attribute NAME from both schematics and //board. string schValue="",brdValue=""; //Return an empty string in libraries if (library) return ""; //Attribute names are always uppercase Name=strupr(AWTrim(Name)); //Read the attribute from the schematics if (project.schematic) project.schematic(S) S.attributes(A) if (A.name==Name) { schValue=AWAttributeText(A.value); break; } //Read the attribute from the board if (project.board) project.board(B) B.attributes(A) if (A.name==Name) { brdValue=AWAttributeText(A.value); break; } // if (SchematicFirst) { if (schValue) return schValue; else return brdValue; } else if (brdValue) return brdValue; else return schValue; } string AWWriteAttribute(string Name,string Value,int DeleteOnEmpty) { //Returns the script string necessary for setting the global attribute NAME //to the string VALUE. If DELETEONEMPTY<>0, the attribute is deleted if its //value is an empty string if (AWTrim(Name)=="") return ""; else if ((Value!="") || (!DeleteOnEmpty)) return "ATTRIBUTE * "+strupr(AWTrim(Name))+" '"+AWText2Script(Value,1,1)+"';\n"; else return "ATTRIBUTE * "+strupr(AWTrim(Name))+" DELETE;\n"; } // void AWLabel(string EnglishText,string GermanText) { dlgLabel("<html><nobr>"+AWLocalise(EnglishText,GermanText)+"</nobr></html>"); } void AWMessage(string EnglishText,string GermanText) { dlgMessageBox("<html><nobr>"+AWLocalise(EnglishText,GermanText)+ "</nobr></html>"); } void AWWarning(string EnglishText,string GermanText) { dlgMessageBox("!<html><nobr>"+AWLocalise(EnglishText,GermanText)+ "</nobr></html>"); } void AWInfo(string EnglishText,string GermanText) { dlgMessageBox(";<html><nobr>"+AWLocalise(EnglishText,GermanText)+ "</nobr></html>"); } void AWError(string EnglishText,string GermanText) { dlgMessageBox(":<html><nobr>"+AWLocalise(EnglishText,GermanText)+ "</nobr></html>"); } int AWYesNo(string EnglishText,string GermanText) { if (dlgMessageBox(";<html><nobr>"+AWLocalise(EnglishText,GermanText)+ "</nobr></html>",AWLocalise("&Yes","&Ja"),AWLocalise("&No","&Nein"))==0) return 1; else return 0; } int AWContinueCancel(string EnglishText,string GermanText) { if (dlgMessageBox(";<html><nobr>"+AWLocalise(EnglishText,GermanText)+ "</nobr></html>",AWLocalise("&Continue","&Fortfahren"), AWLocalise("&Cancel","&Abbrechen"))==0) return 1; else return 0; } int AWCancelContinue(string EnglishText,string GermanText) { if (dlgMessageBox(";<html><nobr>"+AWLocalise(EnglishText,GermanText)+ "</nobr></html>",AWLocalise("-&Cancel","-&Abbrechen"), AWLocalise("&Continue","&Fortfahren"))==0) return 0; else return 1; } void AWExitOnLibrary() { //Exit, if the program was run from within a library if (!library) return; AWError("This program can only be run from within<br>the <b>schematics</b> "+ "or <b>board editor</b>!","Dieses Programm kann nur im <b>Schaltplan-"+ "</b> oder<br><b>Platinen-Editor</b> ausgeführt werden!"); exit(0); } void AWExitOnNoSchematic() { //Exit, if the program was not run from within a schematics if (schematic) return; AWError("This program can only be run from<br>within the <b>schematics "+ " editor</b>!","Dieses Programm kann nur im<br><b>Schaltplan-Editor</b> "+ "ausgeführt werden!"); exit(0); } string AWMic(int Value) { //Converts VALUE (given in editor units) to microns and returns the //corresponding string string Result; if (frac(u2mic(Value))==0) sprintf(Result,"%d",int(u2mic(Value))); else sprintf(Result,"%.1f",u2mic(Value)); return Result; } string AWExtractValueText(string Text) { //Extracts the value text from TEXT, being the first (floating point) number //in the string, possibly followed by a multiplier prefix. Supported values //include, e.g., '4.7n', '33k2', '1e-6', '-1,7e+3M' int Pos,Length; Text=AWTrim(Text); Pos=strxstr(Text,"(^[-+]?[0-9]*[.,]?[0-9]+([eE][-+]?[0-9]+)?"+ "[fFpPnNuUµmkKMgGtT]?)|(^[-+]?[0-9]+[fFpPnNuUµmkKMgGtTvVrR][0-9]*)",0, Length); if (Pos<0) return ""; return strsub(Text,Pos,Length); } real AWExtractValue(string Text) { //Extracts the value from TEXT, being the first (floating point) number in //the string, possibly followed by a multiplier postfix. Supported values //include, e.g., '4.7n', '33k2', '1e-6', '-1,7e+3M', '1meg', '4V7'. If no //decent value could be extracted, REAL_MAX is returned int PostfixNumber=21; char PostfixCharacters[]={'f','F','p','P','n','N','u','U','µ','m','k','K', 'M','g','G','t','T','v','V','r','R'}; real PostfixMultipliers[]={1e-15,1e-15,1e-12,1e-12,1e-9,1e-9,1e-6,1e-6,1e-6, 1e-3,1e3,1e3,1e6,1e9,1e9,1e12,1e12,1,1,1,1}; string Value; int Nr,Position; real Multiplier=1; //Extract the value sub string. Return with REAL_MAX if none was found Value=AWExtractValueText(Text); if (Value=="") return REAL_MAX; //Adjust for weird SPICE syntax and check for 'meg': If found, change the //lowercase 'm' to uppercase, so that it's properly seen as 1e6 Position=strstr(Text,Value); if ((strsub(Value,strlen(Value)-1)=="m") && (Position>=0) && (strupr(strsub(Text,Position+strlen(Value)-1,3))=="MEG")) Value[strlen(Value)-1]='M'; //Replace commas by dots Value=AWReplace(Value,",","."); //Search for multiplier postfixes. If found, replace them by a '.' and //memorise their multiplier for (Nr=0;Nr<PostfixNumber;Nr++) { Position=strchr(Value,PostfixCharacters[Nr]); if (Position>=0) { if (Position==strlen(Value)-1) Value=strsub(Value,0,strlen(Value)-1); else Value[Position]='.'; Multiplier=PostfixMultipliers[Nr]; break; } } //In order to avoid binary conversion errors like "0.1u<>100n", round the //found value to 12 digits and return this sprintf(Value,"%.12e",strtod(Value)*Multiplier); return strtod(Value); } string AWExtractToleranceText(string Text) { //Extracts the tolerance text from TEXT, being the first (floating point) //number followed by a percent character int Pos,Length; Text=AWTrim(Text); Pos=strxstr(Text,"[0-9]*[.,]?[0-9]+[ ]*%",0,Length); if (Pos<0) return ""; return strsub(Text,Pos,Length); } real AWExtractTolerance(string Text) { //Extracts the tolerance value from TEXT, being the first (floating point) //number followed by a percent character. The value is returned in percent. //If no decent value could be extracted, REAL_MAX is returned return AWExtractValue(AWExtractToleranceText(Text)); } string AWExtractTKText(string Text) { //Extracts the temperature coefficient text from TEXT, starting with 'TK' //and followed by the coefficient value in ppm. Supported values include, //e.g., 'TK25', 'TK+-60', 'TK+100-60' int Pos,Length; Text=AWTrim(Text); Pos=strxstr(Text,"[tT][kK][+]?[0-9]*[-]?[0-9]+",0,Length); if (Pos<0) return ""; return strsub(Text,Pos,Length); } string AWFormatReal(real Value,int Postfixes) { //POSTFIX: 0=no postfixes, 1=postfixes INSIDE numbers (like '4M7'), //2=postfixes OUTSIDE numbers (like '4.7M'), 3=SPICE-like postfixes ('4.7Meg') int PostfixNr=10; string PostfixCharacters[]={"T","G","M","k",".","m","u","n","p","f"}; real PostfixMultipliers[]={1e12,1e9,1e6,1e3,1,1e-3,1e-6,1e-9,1e-12,1e-15}; int Pos,Pose,Nr; string Postfix="."; string Result; string Character; //Extract the real value from the text. If none could be found, just return //the original text if (Value>=REAL_MAX) return ""; //If postfixes are desired, reduce the number accordingly if (Postfixes) for (Nr=0;Nr<PostfixNr;Nr++) if (Value>=PostfixMultipliers[Nr]) { Value/=PostfixMultipliers[Nr]; Postfix=PostfixCharacters[Nr]; if ((Postfixes==3) && (Postfix=="M")) Postfix="Meg"; break; } //Format the number 'normally' if (!Postfixes) { if ((Value==0.0) || ((abs(Value)<10000) && (abs(Value)>=0.001))) sprintf(Result,"%1.5f",Value); else sprintf(Result,"%1.3e",Value); } else if (abs(Value)>=100.0) sprintf(Result,"%1.2f",Value); else if (abs(Value)>=10.0) sprintf(Result,"%1.3f",Value); else sprintf(Result,"%1.4f",Value); //Delete trailing zeros after the decimal dot Pos=strchr(Result,'.'); if (Pos>=0) { Pose=strchr(Result,'e'); if (Pose<0) Pose=strlen(Result); for (Nr=Pose-1;Nr>=Pos;Nr--) { if ((Result[Nr]!='0') && (Result[Nr]!='.')) break; Result=strsub(Result,0,Pose-1)+strsub(Result,Pose); Pose--; } } //Replace the decimal dot by the postfix, if desired Pos=strchr(Result,'.'); if ((Pos>=0) && (Postfixes==1)) Result=strsub(Result,0,Pos)+Postfix+strsub(Result,Pos+1); else if ((Postfixes>0) && (Postfix!=".")) Result=Result+Postfix; return Result; } string AWCreateValueText(string Text,int Postfixes) { //POSTFIX: 0=no postfixes, 1=postfixes INSIDE numbers (like '4M7'), //2=postfixes OUTSIDE numbers (like '4.7M'), 3=SPICE-like postfixes ('4.7Meg') real Value; //Extract the real value from the text. If none could be found, just return //the original text Value=AWExtractValue(Text); if (Value>=REAL_MAX) return Text; return AWFormatReal(Value,Postfixes); } string varNotPopulated="[unpopulated]"; string AWCatchUnpopulatedText(string Text) { Text=AWTrim(Text); if ((strupr(Text)=="NC") || (strupr(Text)=="NP") || (strupr(Text)=="NOMOUNT") || (strupr(Text)=="-") || (strupr(Text)=="--") || (strupr(Text)=="---") || (strupr(Text)=="[NOT POPULATED]") || (strupr(Text)=="NOT POPULATED") || (strupr(Text)=="[UNPOPULATED]") || (strupr(Text)=="UNPOPULATED") || (strupr(Text)==strupr(varNotPopulated))) return varNotPopulated; return Text; } int AWMinMaxInt(int Value,int Minimum,int Maximum) { int Dummy; if (Minimum>Maximum) { Dummy=Minimum; Minimum=Maximum; Maximum=Dummy; } return min(max(Value,Minimum),Maximum); } int AWMinMaxReal(real Value,real Minimum,real Maximum) { real Dummy; if (Minimum>Maximum) { Dummy=Minimum; Minimum=Maximum; Maximum=Dummy; } return min(max(Value,Minimum),Maximum); } enum {awbtUnknown,awbtCadSoft,awbtVersion4,awbtVersion5,awbtMostly4, awbtMostly5,awbtMostlyCadSoft}; int AWBoardType() { int HasName4,HasName5,Count4=0,Count5=0,CountCadSoft=0,NameFound; if (!project.board) return awbtUnknown; project.board(B) B.elements(E) { HasName4=0; HasName5=0; NameFound=0; E.texts(T) if (T.value==E.name) { NameFound=1; if ((T.layer==LAYER_TPLACE) || (T.layer==LAYER_BPLACE)) HasName5=1; else if ((T.layer==LAYER_TDOCU) || (T.layer==LAYER_BDOCU)) HasName4=1; } E.package.texts(T) if (T.value==E.name) { NameFound=1; if ((T.layer==LAYER_TPLACE) || (T.layer==LAYER_BPLACE)) HasName5=1; else if ((T.layer==LAYER_TDOCU) || (T.layer==LAYER_BDOCU)) HasName4=1; } if (NameFound) { if (HasName5) Count5++; if (HasName4) Count4++; if ((!HasName4) && (!HasName5)) CountCadSoft++; } } if ((Count5) && (!Count4) && (!CountCadSoft)) return awbtVersion5; if ((Count4) && (!Count5) && (!CountCadSoft)) return awbtVersion4; if ((CountCadSoft) && (!Count4) && (!Count5)) return awbtCadSoft; if ((Count5>=Count4) && (Count5>=CountCadSoft)) return awbtMostly5; if ((Count4>=CountCadSoft) && (Count4>=Count5)) return awbtMostly4; return awbtMostlyCadSoft; } string AWGetPartValue(UL_PART P) { //Returns the DISPLAYED value of the part P. This MIGHT be the REAL value of //the part, but under the following circumstances, it's not: If the part's //value may NOT be changed, and it equals its standard (automatically //generated) value, return the value string from the element's 'TYPE' //attribute (if available) if ((P.device.value=="Off") && (P.value==P.device.name) && (P.attribute["TYPE"])) return P.attribute["TYPE"]; else return P.value; } string AWRestoreEditorWindow() { //Returns the string necessary to restore the previous editor window, //independent of the current one string Result; if (board) Result="EDIT .brd;\n"; if (schematic) { Result="EDIT .sch;\n"; if (sheet) sheet(S) Result+="EDIT .s"+AWIntToStr(S.number)+";\n"; } return Result; } void AWInsertOKCancel() { dlgHBoxLayout { dlgStretch(0); dlgPushButton(AWLocalise("+OK","+OK")) dlgAccept(1); dlgPushButton(AWLocalise("-Cancel", "-Abbrechen")) dlgReject(0); } } AWCreateBadIndex();
[ [ [ 1, 1797 ] ] ]
bc88b247707154e9b1059512b445cafe54baa280
6c8c4728e608a4badd88de181910a294be56953a
/RexLogicModule/RexLogicModule.h
bc88c723795d89d52cc3920e2d9eff868a463e07
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,192
h
// For conditions of distribution and use, see copyright notice in license.txt #ifndef incl_RexLogicModule_h #define incl_RexLogicModule_h #include "ModuleInterface.h" #include "ModuleLoggingFunctions.h" #include "RexLogicModuleApi.h" #include "ForwardDefines.h" #include "NetworkEvents.h" #include "Quaternion.h" #include <boost/smart_ptr.hpp> #include <boost/function.hpp> #include <QString> #include <map> #include <set> class RexUUID; namespace OgreRenderer { class Renderer; typedef boost::shared_ptr<OgreRenderer::Renderer> RendererPtr; } namespace ProtocolUtilities { class WorldStream; class InventorySkeleton; class ProtocolModuleInterface; } namespace RexLogic { class NetworkEventHandler; class InputEventHandler; class SceneEventHandler; class NetworkStateEventHandler; class FrameworkEventHandler; class Avatar; class AvatarEditor; class Primitive; class AvatarControllable; class CameraControllable; class OpenSimLoginHandler; class TaigaLoginHandler; class MainPanelHandler; class WorldInputLogic; typedef boost::shared_ptr<ProtocolUtilities::WorldStream> WorldStreamConnectionPtr; typedef boost::shared_ptr<Avatar> AvatarPtr; typedef boost::shared_ptr<AvatarEditor> AvatarEditorPtr; typedef boost::shared_ptr<Primitive> PrimitivePtr; typedef boost::shared_ptr<AvatarControllable> AvatarControllablePtr; typedef boost::shared_ptr<CameraControllable> CameraControllablePtr; typedef boost::shared_ptr<ProtocolUtilities::InventorySkeleton> InventoryPtr; //! Camera states handled by rex logic enum CameraState { //! Camera follows the avatar (third or first person) CS_Follow, //! Camera moves around freely CS_Free }; //! interface for modules class REXLOGIC_MODULE_API RexLogicModule : public Foundation::ModuleInterfaceImpl { public: RexLogicModule(); virtual ~RexLogicModule(); virtual void Load(); virtual void Initialize(); virtual void PostInitialize(); virtual void Uninitialize(); virtual void SubscribeToNetworkEvents(boost::weak_ptr<ProtocolUtilities::ProtocolModuleInterface> currentProtocolModule); virtual void Update(f64 frametime); virtual bool HandleEvent(event_category_id_t category_id, event_id_t event_id, Foundation::EventDataInterface* data); MODULE_LOGGING_FUNCTIONS; //! returns name of this module. Needed for logging. static const std::string &NameStatic() { return Foundation::Module::NameFromType(type_static_); } static const Foundation::Module::Type type_static_ = Foundation::Module::MT_WorldLogic; WorldStreamConnectionPtr GetServerConnection() const { return world_stream_; } //! switch current input controller, if using avatar controller, switch to camera controller and vice versa void SwitchCameraState(); //! @return The avatar handler object that manages reX avatar logic. AvatarPtr GetAvatarHandler() const; //! @return The avatar editor. AvatarEditorPtr GetAvatarEditor() const; //! @return The primitive handler object that manages reX primitive logic. PrimitivePtr GetPrimitiveHandler() const; /// @return Invetory pointer. InventoryPtr GetInventory() const; //! Returns the camera controllable CameraControllablePtr GetCameraControllable() const { return camera_controllable_; } //! Returns the avatar controllable AvatarControllablePtr GetAvatarControllable() const { return avatar_controllable_; } //! Return camera entity. Note: may be expired if scene got deleted and new scene not created yet Scene::EntityWeakPtr GetCameraEntity() const { return camera_entity_; } //! The scene system can store multiple scenes. Only one scene is active at a time, that is the one //! that is currently being rendered. You may pass a null pointer to erase the currently active scene. void SetCurrentActiveScene(Scene::ScenePtr scene); //! @return The currently viewed scene, or 0 if not connected. (Don't use as an indicator of connection state!) Scene::ScenePtr GetCurrentActiveScene() const; //! Creates a new scene and sets that as active. Also creates the core entities to that scene that //! are always to be present in an reX world, like terrain. Scene::ScenePtr CreateNewActiveScene(const std::string &name); //! Deletes the scene with the given name. If that was the current active scene, the active scene will be //! set to null. void DeleteScene(const std::string &name); //! @return The entity corresponding to given scene entityid, or null if not found. Scene::EntityPtr GetEntity(entity_id_t entityid); //! @return The entity corresponding to given scene entityid, or null if not found. //! This entity is guaranteed to have an existing EC_OpenSimPrim component. __inline Scene::EntityPtr GetPrimEntity(entity_id_t entityid) { return GetEntityWithComponent(entityid,"EC_OpenSimPrim"); } Scene::EntityPtr GetPrimEntity(const RexUUID &fullid); //! @return The entity corresponding to given scene entityid, or null if not found. //! This entity is guaranteed to have an existing EC_OpenSimAvatar component, //! and EC_OpenSimPresence component. __inline Scene::EntityPtr GetAvatarEntity(entity_id_t entityid) { return GetEntityWithComponent(entityid,"EC_OpenSimAvatar"); } Scene::EntityPtr GetAvatarEntity(const RexUUID &fullid); //! Register uuid - localid pair void RegisterFullId(const RexUUID &fullid, entity_id_t entityid); //! Unregister uuid void UnregisterFullId(const RexUUID &fullid); //! Handle a resource event. Needs to be passed to several receivers (Prim, Terrain etc.) bool HandleResourceEvent(event_id_t event_id, Foundation::EventDataInterface* data); //! Handle an inventory event. bool HandleInventoryEvent(event_id_t event_id, Foundation::EventDataInterface* data); //! Handle an asset event. bool HandleAssetEvent(event_id_t event_id, Foundation::EventDataInterface* data); //! Handle real-time update of scene objects /*! Performs dead-reckoning and damped motion for all scene entities which have an OgrePlaceable and a NetworkPosition component. If the OgrePlaceable position/rotation is set anywhere else, it will be overridden by the next call to this, so it should be avoided. Performs animation update to all objects that have an OgreAnimationController component. */ void UpdateObjects(f64 frametime); //! handles assignment of object as a child of other object, if applicable void HandleObjectParent(entity_id_t entityid); //! handles assignment of child objects, who were previously missing this object as a parent void HandleMissingParent(entity_id_t entityid); //! login through console Console::CommandResult ConsoleLogin(const StringVector &params); //! logout through console Console::CommandResult ConsoleLogout(const StringVector &params); //! login from py - temp while loginui misses dllexport void StartLoginOpensim(QString qfirstAndLast, QString qpassword, QString qserverAddressWithPort); //! toggle fly mode through console Console::CommandResult ConsoleToggleFlyMode(const StringVector &params); //! Console command for test EC_Highlight. Adds EC_Highlight for every avatar. Console::CommandResult ConsoleHighlightTest(const StringVector &params); //! logout from server and delete current scene void LogoutAndDeleteWorld(); //! Update avatar overlays. Must be done after other object update void UpdateAvatarOverlays(); //! Update sound listener position /*! Uses current camera for now */ void UpdateSoundListener(); //! XXX have linking probs to AvatarController so trying this wrapper void SetAvatarYaw(Real newyaw); void SetAvatarRotation(Quaternion newrot); void SetCameraYawPitch(Real newyaw, Real newpitch); entity_id_t GetUserAvatarId(); Vector3df GetCameraUp(); Vector3df GetCameraRight(); Vector3df GetCameraPosition(); Quaternion GetCameraOrientation(); Real GetCameraViewportWidth(); Real GetCameraViewportHeight(); Real GetCameraFOV(); void SendRexPrimData(entity_id_t entityid); //! Sets visibility for all name display overlays, used e.g. in screenshot taking void SetAllTextOverlaysVisible(bool visible); private: RexLogicModule(const RexLogicModule &); RexLogicModule &operator=(const RexLogicModule &); //! Does preparations before logout/delete of scene //! For example: Takes ui screenshots of world/avatar with rendering service. //! Add functionality if you need something done before logout. void AboutToDeleteWorld(); /// Return renderer pointer. Convenience function for making code cleaner. OgreRenderer::RendererPtr GetRendererPtr(); //! Event handler for network events. NetworkEventHandler *network_handler_; //! Event handler for network events. InputEventHandler *input_handler_; //! Event handler for network state events. NetworkStateEventHandler *network_state_handler_; //! Event handler for scene events. SceneEventHandler *scene_handler_; //! event handler for framework events FrameworkEventHandler *framework_handler_; //! Server connection WorldStreamConnectionPtr world_stream_; //! Movement damping constant Real movement_damping_constant_; //! How long to keep doing dead reckoning f64 dead_reckoning_time_; typedef boost::function<bool(event_id_t,Foundation::EventDataInterface*)> LogicEventHandlerFunction; typedef std::vector<LogicEventHandlerFunction> EventHandlerVector; typedef std::map<event_category_id_t, EventHandlerVector> LogicEventHandlerMap; //! Event handler map. LogicEventHandlerMap event_handlers_; //! Avatar handler pointer. AvatarPtr avatar_; //! Avatar editor pointer. AvatarEditorPtr avatar_editor_; //! Primitive handler pointer. PrimitivePtr primitive_; //! Active scene pointer. Scene::ScenePtr activeScene_; //! Current camera entity Scene::EntityWeakPtr camera_entity_; #ifdef _DEBUG /// Checks the currently active camera that its transformation is correct, and logs into debug output /// if not. Thanks go to Ogre for having issues with this.. void DebugSanityCheckOgreCameraTransform(); #endif //! workaround for not being able to send events during initialization bool send_input_state_; //! Get a component with certain entitycomponent in it Scene::EntityPtr GetEntityWithComponent(entity_id_t entityid, const std::string &requiredcomponent); //! Mapping for full uuids - localids typedef std::map<RexUUID, entity_id_t> IDMap; IDMap UUIDs_; //! pending parent object assignments, keyed by parent id //! the parent id will be added as a key if it is not missing, and the children id's are added to the set. //! once the parent prim appears, the children will be assigned the parent and the key will be removed from here. typedef std::map<entity_id_t, std::set<entity_id_t> > ObjectParentMap; ObjectParentMap pending_parents_; //! The connection state which is shown in the login window. ProtocolUtilities::Connection::State connectionState_; //! An avatar controllable AvatarControllablePtr avatar_controllable_; //! Camera controllable CameraControllablePtr camera_controllable_; //! Avatar entities found this frame. Needed so that we can update name overlays last, after all other updates std::vector<Scene::EntityWeakPtr> found_avatars_; //! current camera state CameraState camera_state_; //! OpenSim login handler OpenSimLoginHandler *os_login_handler_; //! Taiga login handler TaigaLoginHandler *taiga_login_handler_; //! MainPanel handler MainPanelHandler *main_panel_handler_; }; } #endif
[ "sempuki@5b2332b8-efa3-11de-8684-7d64432d61a3", "tuco@5b2332b8-efa3-11de-8684-7d64432d61a3", "jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3", "cadaver@5b2332b8-efa3-11de-8684-7d64432d61a3", "jaakkoallander@5b2332b8-efa3-11de-8684-7d64432d61a3", "cmayhem@5b2332b8-efa3-11de-8684-7d64432d61a3", "jonnenau@5b2332b8-efa3-11de-8684-7d64432d61a3", "sempuki1@5b2332b8-efa3-11de-8684-7d64432d61a3", "jjj@5b2332b8-efa3-11de-8684-7d64432d61a3", "loorni@5b2332b8-efa3-11de-8684-7d64432d61a3", "antont@5b2332b8-efa3-11de-8684-7d64432d61a3", "erno@5b2332b8-efa3-11de-8684-7d64432d61a3", "Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3", "aura@5b2332b8-efa3-11de-8684-7d64432d61a3", "[email protected]@5b2332b8-efa3-11de-8684-7d64432d61a3", "joosuav@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 2 ], [ 5, 6 ], [ 21, 21 ], [ 36, 36 ], [ 329, 330 ] ], [ [ 3, 4 ], [ 35, 35 ], [ 37, 38 ], [ 53, 53 ], [ 55, 55 ], [ 68, 69 ], [ 71, 76 ], [ 85, 90 ], [ 93, 93 ], [ 102, 102 ], [ 135, 137 ], [ 140, 141 ], [ 146, 147 ], [ 150, 150 ], [ 152, 152 ], [ 192, 193 ], [ 237, 237 ], [ 240, 240 ], [ 251, 251 ], [ 253, 253 ], [ 265, 265 ], [ 268, 268 ], [ 274, 274 ], [ 290, 291 ], [ 293, 294 ], [ 296, 296 ], [ 327, 328 ] ], [ [ 7, 7 ], [ 9, 20 ], [ 28, 34 ] ], [ [ 8, 8 ], [ 43, 43 ], [ 54, 54 ], [ 70, 70 ], [ 81, 81 ], [ 83, 83 ], [ 100, 100 ], [ 132, 134 ], [ 138, 138 ], [ 144, 144 ], [ 148, 148 ], [ 151, 151 ], [ 153, 154 ], [ 156, 165 ], [ 167, 175 ], [ 178, 178 ], [ 181, 181 ], [ 186, 187 ], [ 198, 202 ], [ 204, 206 ], [ 208, 208 ], [ 210, 212 ], [ 214, 215 ], [ 217, 217 ], [ 219, 219 ], [ 254, 260 ], [ 262, 262 ], [ 271, 271 ], [ 292, 292 ], [ 295, 295 ], [ 298, 303 ] ], [ [ 22, 27 ], [ 39, 40 ], [ 42, 42 ], [ 44, 44 ], [ 51, 51 ], [ 80, 80 ], [ 82, 82 ], [ 84, 84 ], [ 91, 91 ], [ 96, 99 ], [ 101, 101 ], [ 103, 108 ], [ 110, 110 ], [ 113, 114 ], [ 123, 123 ], [ 126, 126 ], [ 149, 149 ], [ 155, 155 ], [ 166, 166 ], [ 176, 176 ], [ 182, 182 ], [ 191, 191 ], [ 203, 203 ], [ 207, 207 ], [ 233, 236 ], [ 238, 239 ], [ 241, 246 ], [ 250, 250 ], [ 263, 264 ], [ 269, 270 ], [ 272, 272 ], [ 275, 276 ], [ 297, 297 ] ], [ [ 41, 41 ], [ 45, 46 ], [ 56, 57 ], [ 60, 67 ], [ 77, 79 ], [ 94, 95 ], [ 109, 109 ], [ 111, 112 ], [ 120, 120 ], [ 127, 127 ], [ 139, 139 ], [ 142, 143 ], [ 145, 145 ], [ 177, 177 ], [ 179, 180 ], [ 247, 249 ], [ 261, 261 ], [ 266, 266 ], [ 277, 277 ], [ 288, 289 ], [ 307, 312 ], [ 316, 317 ] ], [ [ 47, 49 ], [ 52, 52 ], [ 58, 58 ], [ 92, 92 ], [ 252, 252 ], [ 318, 326 ] ], [ [ 50, 50 ] ], [ [ 59, 59 ], [ 118, 119 ], [ 121, 122 ], [ 124, 125 ], [ 128, 131 ], [ 224, 224 ], [ 281, 287 ] ], [ [ 115, 117 ], [ 195, 197 ], [ 213, 213 ], [ 267, 267 ], [ 273, 273 ], [ 279, 280 ], [ 313, 315 ] ], [ [ 183, 183 ], [ 185, 185 ], [ 194, 194 ], [ 209, 209 ], [ 218, 218 ], [ 220, 220 ] ], [ [ 184, 184 ] ], [ [ 188, 190 ], [ 221, 223 ], [ 225, 227 ], [ 278, 278 ] ], [ [ 216, 216 ] ], [ [ 228, 232 ] ], [ [ 304, 306 ] ] ]
7aeb24db39a6563ac12574a5563b797a905e749c
40b507c2dde13d14bb75ee1b3c16b4f3f82912d1
/core/systems/HandleSys.cpp
41cc361f2bff0c57042269f1b60bd066794c961b
[]
no_license
Nephyrin/-furry-octo-nemesis
5da2ef75883ebc4040e359a6679da64ad8848020
dd441c39bd74eda2b9857540dcac1d98706de1de
refs/heads/master
2016-09-06T01:12:49.611637
2008-09-14T08:42:28
2008-09-14T08:42:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
25,459
cpp
/** * vim: set ts=4 : * ============================================================================= * SourceMod * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved. * ============================================================================= * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. * * 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/>. * * As a special exception, AlliedModders LLC gives you permission to link the * code of this program (as well as its derivative works) to "Half-Life 2," the * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software * by the Valve Corporation. You must obey the GNU General Public License in * all respects for all other code used. Additionally, AlliedModders LLC grants * this exception to all derivative works. AlliedModders LLC defines further * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), * or <http://www.sourcemod.net/license.php>. * * Version: $Id$ */ #include "HandleSys.h" #include "ShareSys.h" #include "PluginSys.h" #include "ExtensionSys.h" #include "Logger.h" #include <assert.h> #include <string.h> #include "sm_stringutil.h" HandleSystem g_HandleSys; QHandle *ignore_handle; inline HandleType_t TypeParent(HandleType_t type) { return (type & ~HANDLESYS_SUBTYPE_MASK); } inline HandleError IdentityHandle(IdentityToken_t *token, unsigned int *index) { return g_HandleSys.GetHandle(token->ident, g_ShareSys.GetIdentRoot(), &ignore_handle, index); } HandleSystem::HandleSystem() { m_Handles = new QHandle[HANDLESYS_MAX_HANDLES + 1]; memset(m_Handles, 0, sizeof(QHandle) * (HANDLESYS_MAX_HANDLES + 1)); m_Types = new QHandleType[HANDLESYS_TYPEARRAY_SIZE]; memset(m_Types, 0, sizeof(QHandleType) * HANDLESYS_TYPEARRAY_SIZE); m_TypeLookup = sm_trie_create(); m_strtab = new BaseStringTable(512); m_TypeTail = 0; } HandleSystem::~HandleSystem() { delete [] m_Handles; delete [] m_Types; sm_trie_destroy(m_TypeLookup); delete m_strtab; } HandleType_t HandleSystem::CreateType(const char *name, IHandleTypeDispatch *dispatch, HandleType_t parent, const TypeAccess *typeAccess, const HandleAccess *hndlAccess, IdentityToken_t *ident, HandleError *err) { if (!dispatch) { if (err) { *err = HandleError_Parameter; } return 0; } if (typeAccess && typeAccess->hsVersion > SMINTERFACE_HANDLESYSTEM_VERSION) { if (err) { *err = HandleError_Version; } return 0; } if (hndlAccess && hndlAccess->hsVersion > SMINTERFACE_HANDLESYSTEM_VERSION) { if (err) { *err = HandleError_Version; } return 0; } bool isChild = false; if (parent != 0) { isChild = true; if (parent & HANDLESYS_SUBTYPE_MASK) { if (err) { *err = HandleError_NoInherit; } return 0; } if (parent >= HANDLESYS_TYPEARRAY_SIZE || m_Types[parent].dispatch == NULL) { if (err) { *err = HandleError_Parameter; } return 0; } if (m_Types[parent].typeSec.access[HTypeAccess_Inherit] == false && (m_Types[parent].typeSec.ident != ident)) { if (err) { *err = HandleError_Access; } return 0; } } if (name && name[0] != '\0') { if (sm_trie_retrieve(m_TypeLookup, name, NULL)) { if (err) { *err = HandleError_Parameter; } return 0; } } unsigned int index; if (isChild) { QHandleType *pParent = &m_Types[parent]; if (pParent->children >= HANDLESYS_MAX_SUBTYPES) { if (err) { *err = HandleError_Limit; } return 0; } index = 0; for (unsigned int i=1; i<=HANDLESYS_MAX_SUBTYPES; i++) { if (m_Types[parent + i].dispatch == NULL) { index = parent + i; break; } } if (!index) { if (err) { *err = HandleError_Limit; } return 0; } pParent->children++; } else { if (m_FreeTypes == 0) { /* Reserve another index */ if (m_TypeTail >= HANDLESYS_TYPEARRAY_SIZE) { if (err) { *err = HandleError_Limit; } return 0; } else { m_TypeTail += (HANDLESYS_MAX_SUBTYPES + 1); index = m_TypeTail; } } else { /* The "free array" is compacted into the normal array for easiness */ index = m_Types[m_FreeTypes--].freeID; } } QHandleType *pType = &m_Types[index]; pType->dispatch = dispatch; if (name && name[0] != '\0') { pType->nameIdx = m_strtab->AddString(name); sm_trie_insert(m_TypeLookup, name, (void *)pType); } else { pType->nameIdx = -1; } pType->opened = 0; if (typeAccess) { pType->typeSec = *typeAccess; } else { InitAccessDefaults(&pType->typeSec, NULL); pType->typeSec.ident = ident; } if (hndlAccess) { pType->hndlSec = *hndlAccess; } else { InitAccessDefaults(NULL, &pType->hndlSec); } if (!isChild) { pType->children = 0; } return index; } bool HandleSystem::FindHandleType(const char *name, HandleType_t *type) { QHandleType *_type; if (!sm_trie_retrieve(m_TypeLookup, name, (void **)&_type)) { return false; } unsigned int offset = _type - m_Types; if (type) { *type = offset; } return true; } HandleError HandleSystem::TryAllocHandle(unsigned int *handle) { if (m_FreeHandles == 0) { if (m_HandleTail >= HANDLESYS_MAX_HANDLES) { return HandleError_Limit;; } *handle = ++m_HandleTail; } else { *handle = m_Handles[m_FreeHandles--].freeID; } return HandleError_None; } HandleError HandleSystem::MakePrimHandle(HandleType_t type, QHandle **in_pHandle, unsigned int *in_index, Handle_t *in_handle, IdentityToken_t *owner, bool identity) { HandleError err; unsigned int owner_index = 0; if (owner && (IdentityHandle(owner, &owner_index) != HandleError_None)) { return HandleError_Identity; } unsigned int handle; if ((err = TryAllocHandle(&handle)) != HandleError_None) { if (!TryAndFreeSomeHandles() || (err = TryAllocHandle(&handle)) != HandleError_None) { return err; } } QHandle *pHandle = &m_Handles[handle]; assert(pHandle->set == false); if (++m_HSerial >= HANDLESYS_MAX_SERIALS) { m_HSerial = 1; } /* Set essential information */ pHandle->set = identity ? HandleSet_Identity : HandleSet_Used; pHandle->refcount = 1; pHandle->type = type; pHandle->serial = m_HSerial; pHandle->owner = owner; pHandle->ch_next = 0; pHandle->access_special = false; pHandle->is_destroying = false; /* Create the hash value */ Handle_t hash = pHandle->serial; hash <<= 16; hash |= handle; /* Add a reference count to the type */ m_Types[type].opened++; /* Output */ *in_pHandle = pHandle; *in_index = handle; *in_handle = hash; /* Decode the identity token * For now, we don't allow nested ownership */ if (owner && !identity) { QHandle *pIdentity = &m_Handles[owner_index]; if (pIdentity->ch_prev == 0) { pIdentity->ch_prev = handle; pIdentity->ch_next = handle; pHandle->ch_prev = 0; } else { /* Link previous node to us (forward) */ m_Handles[pIdentity->ch_next].ch_next = handle; /* Link us to previous node (backwards) */ pHandle->ch_prev = pIdentity->ch_next; /* Set new tail */ pIdentity->ch_next = handle; } pIdentity->refcount++; } else { pHandle->ch_prev = 0; } return HandleError_None; } void HandleSystem::SetTypeSecurityOwner(HandleType_t type, IdentityToken_t *pToken) { if (!type || type >= HANDLESYS_TYPEARRAY_SIZE || m_Types[type].dispatch == NULL) { return; } m_Types[type].typeSec.ident = pToken; } Handle_t HandleSystem::CreateHandleInt(HandleType_t type, void *object, const HandleSecurity *pSec, HandleError *err, const HandleAccess *pAccess, bool identity) { IdentityToken_t *ident; IdentityToken_t *owner; if (pSec) { ident = pSec->pIdentity; owner = pSec->pOwner; } else { ident = NULL; owner = NULL; } if (!type || type >= HANDLESYS_TYPEARRAY_SIZE || m_Types[type].dispatch == NULL) { if (err) { *err = HandleError_Parameter; } return 0; } /* Check to see if we're allowed to create this handle type */ QHandleType *pType = &m_Types[type]; if (!pType->typeSec.access[HTypeAccess_Create] && (!pType->typeSec.ident || pType->typeSec.ident != ident)) { if (err) { *err = HandleError_Access; } return 0; } unsigned int index; Handle_t handle; QHandle *pHandle; HandleError _err; if ((_err=MakePrimHandle(type, &pHandle, &index, &handle, owner, identity)) != HandleError_None) { if (err) { *err = _err; } return 0; } if (pAccess) { pHandle->access_special = true; pHandle->sec = *pAccess; } pHandle->object = object; pHandle->clone = 0; return handle; } Handle_t HandleSystem::CreateHandleEx(HandleType_t type, void *object, const HandleSecurity *pSec, const HandleAccess *pAccess, HandleError *err) { return CreateHandleInt(type, object, pSec, err, pAccess, false); } Handle_t HandleSystem::CreateHandle(HandleType_t type, void *object, IdentityToken_t *owner, IdentityToken_t *ident, HandleError *err) { HandleSecurity sec; sec.pIdentity = ident; sec.pOwner = owner; return CreateHandleEx(type, object, &sec, NULL, err); } bool HandleSystem::TypeCheck(HandleType_t intype, HandleType_t outtype) { /* Check the type inheritance */ if (intype & HANDLESYS_SUBTYPE_MASK) { if (intype != outtype && (TypeParent(intype) != TypeParent(outtype))) { return false; } } else { if (intype != outtype) { return false; } } return true; } HandleError HandleSystem::GetHandle(Handle_t handle, IdentityToken_t *ident, QHandle **in_pHandle, unsigned int *in_index, bool ignoreFree) { unsigned int serial = (handle >> 16); unsigned int index = (handle & HANDLESYS_HANDLE_MASK); if (index == 0 || index == 0xFFFF) { return HandleError_Index; } QHandle *pHandle = &m_Handles[index]; if (!pHandle->set || (pHandle->set == HandleSet_Freed && !ignoreFree)) { return HandleError_Freed; } else if (pHandle->set == HandleSet_Identity && ident != g_ShareSys.GetIdentRoot()) { /* Only IdentityHandle() can read this! */ return HandleError_Identity; } if (pHandle->serial != serial) { return HandleError_Changed; } *in_pHandle = pHandle; *in_index = index; return HandleError_None; } bool HandleSystem::CheckAccess(QHandle *pHandle, HandleAccessRight right, const HandleSecurity *pSecurity) { QHandleType *pType = &m_Types[pHandle->type]; unsigned int access; if (pHandle->access_special) { access = pHandle->sec.access[right]; } else { access = pType->hndlSec.access[right]; } /* Check if the type's identity matches */ if (access & HANDLE_RESTRICT_IDENTITY) { IdentityToken_t *owner = pType->typeSec.ident; if (!owner || (!pSecurity || pSecurity->pIdentity != owner)) { return false; } } /* Check if the owner is allowed */ if (access & HANDLE_RESTRICT_OWNER) { IdentityToken_t *owner = pHandle->owner; if (owner && (!pSecurity || pSecurity->pOwner != owner)) { return false; } } return true; } HandleError HandleSystem::CloneHandle(QHandle *pHandle, unsigned int index, Handle_t *newhandle, IdentityToken_t *newOwner) { /* Get a new Handle ID */ unsigned int new_index; QHandle *pNewHandle; Handle_t new_handle; HandleError err; if ((err=MakePrimHandle(pHandle->type, &pNewHandle, &new_index, &new_handle, newOwner)) != HandleError_None) { return err; } /* Assign permissions from parent */ if (pHandle->access_special) { pNewHandle->access_special = true; pNewHandle->sec = pHandle->sec; } pNewHandle->clone = index; pHandle->refcount++; *newhandle = new_handle; return HandleError_None; } HandleError HandleSystem::CloneHandle(Handle_t handle, Handle_t *newhandle, IdentityToken_t *newOwner, const HandleSecurity *pSecurity) { HandleError err; QHandle *pHandle; unsigned int index; IdentityToken_t *ident = pSecurity ? pSecurity->pIdentity : NULL; if ((err=GetHandle(handle, ident, &pHandle, &index)) != HandleError_None) { return err; } /* Identities cannot be cloned */ if (pHandle->set == HandleSet_Identity) { return HandleError_Identity; } /* Check if the handle can be cloned */ if (!CheckAccess(pHandle, HandleAccess_Clone, pSecurity)) { return HandleError_Access; } /* Make sure we're not cloning a clone */ if (pHandle->clone) { QHandle *pParent = &m_Handles[pHandle->clone]; return CloneHandle(pParent, pHandle->clone, newhandle, newOwner); } return CloneHandle(pHandle, index, newhandle, newOwner); } HandleError HandleSystem::FreeHandle(QHandle *pHandle, unsigned int index) { QHandleType *pType = &m_Types[pHandle->type]; if (pHandle->clone) { /* If we're a clone, decrease the parent reference count */ QHandle *pMaster; unsigned int master; /* Note that if we ever have per-handle security, we would need to re-check * the access on this Handle. */ master = pHandle->clone; pMaster = &m_Handles[master]; /* Release the clone now */ ReleasePrimHandle(index); /* Decrement the master's reference count */ if (--pMaster->refcount == 0) { /* Type should be the same but do this anyway... */ pType = &m_Types[pMaster->type]; pMaster->is_destroying = true; pType->dispatch->OnHandleDestroy(pMaster->type, pMaster->object); ReleasePrimHandle(master); } } else if (pHandle->set == HandleSet_Identity) { /* If we're an identity, skip all this stuff! * NOTE: SHARESYS DOES NOT CARE ABOUT THE DESTRUCTOR */ ReleasePrimHandle(index); } else { /* Decrement, free if necessary */ if (--pHandle->refcount == 0) { pHandle->is_destroying = true; pType->dispatch->OnHandleDestroy(pHandle->type, pHandle->object); ReleasePrimHandle(index); } else { /* We must be cloned, so mark ourselves as freed */ pHandle->set = HandleSet_Freed; /* Now, unlink us, so we're not being tracked by the owner */ if (pHandle->owner) { UnlinkHandleFromOwner(pHandle, index); } } } return HandleError_None; } HandleError HandleSystem::FreeHandle(Handle_t handle, const HandleSecurity *pSecurity) { unsigned int index; QHandle *pHandle; HandleError err; IdentityToken_t *ident = pSecurity ? pSecurity->pIdentity : NULL; if ((err=GetHandle(handle, ident, &pHandle, &index)) != HandleError_None) { return err; } if (!CheckAccess(pHandle, HandleAccess_Delete, pSecurity)) { return HandleError_Access; } if (pHandle->is_destroying) { /* Someone tried to free this recursively. * We'll just ignore this safely. */ return HandleError_None; } return FreeHandle(pHandle, index); } HandleError HandleSystem::ReadHandle(Handle_t handle, HandleType_t type, const HandleSecurity *pSecurity, void **object) { unsigned int index; QHandle *pHandle; HandleError err; IdentityToken_t *ident = pSecurity ? pSecurity->pIdentity : NULL; if ((err=GetHandle(handle, ident, &pHandle, &index)) != HandleError_None) { return err; } if (!CheckAccess(pHandle, HandleAccess_Read, pSecurity)) { return HandleError_Access; } /* Check the type inheritance */ if (pHandle->type & HANDLESYS_SUBTYPE_MASK) { if (pHandle->type != type && (TypeParent(pHandle->type) != TypeParent(type))) { return HandleError_Type; } } else if (type) { if (pHandle->type != type) { return HandleError_Type; } } if (object) { /* if we're a clone, the rules change - object is ONLY in our reference */ if (pHandle->clone) { pHandle = &m_Handles[pHandle->clone]; } *object = pHandle->object; } return HandleError_None; } void HandleSystem::UnlinkHandleFromOwner(QHandle *pHandle, unsigned int index) { /* Unlink us if necessary */ unsigned int ident_index; if (IdentityHandle(pHandle->owner, &ident_index) != HandleError_None) { /* Uh-oh! */ assert(pHandle->owner == 0); return; } /* Note that since 0 is an invalid handle, if any of these links are 0, * the data can still be set. */ QHandle *pIdentity = &m_Handles[ident_index]; /* Unlink case: We're the head AND tail node */ if (index == pIdentity->ch_prev && index == pIdentity->ch_next) { pIdentity->ch_prev = 0; pIdentity->ch_next = 0; } /* Unlink case: We're the head node */ else if (index == pIdentity->ch_prev) { /* Link us to the next in the chain */ pIdentity->ch_prev = pHandle->ch_next; /* Patch up the previous link */ m_Handles[pHandle->ch_next].ch_prev = 0; } /* Unlink case: We're the tail node */ else if (index == pIdentity->ch_next) { /* Link us to the previous in the chain */ pIdentity->ch_next = pHandle->ch_prev; /* Patch up the next link */ m_Handles[pHandle->ch_prev].ch_next = 0; } /* Unlink case: We're in the middle! */ else { /* Patch the forward reference */ m_Handles[pHandle->ch_next].ch_prev = pHandle->ch_prev; /* Patch the backward reference */ m_Handles[pHandle->ch_prev].ch_next = pHandle->ch_next; } /* Lastly, decrease the reference count */ pIdentity->refcount--; } void HandleSystem::ReleasePrimHandle(unsigned int index) { QHandle *pHandle = &m_Handles[index]; HandleSet set = pHandle->set; if (pHandle->owner && (set != HandleSet_Identity)) { UnlinkHandleFromOwner(pHandle, index); } /* Were we an identity ourself? */ QHandle *pLocal; if (set == HandleSet_Identity) { /* Extra work to do. We need to find everything connected to this identity and release it. */ unsigned int ch_index; #if defined _DEBUG unsigned int old_index = 0; #endif while ((ch_index = pHandle->ch_next) != 0) { pLocal = &m_Handles[ch_index]; #if defined _DEBUG assert(old_index != ch_index); assert(pLocal->set == HandleSet_Used); old_index = ch_index; #endif FreeHandle(pLocal, ch_index); } } pHandle->set = HandleSet_None; m_Types[pHandle->type].opened--; m_Handles[++m_FreeHandles].freeID = index; } bool HandleSystem::RemoveType(HandleType_t type, IdentityToken_t *ident) { if (type == 0 || type >= HANDLESYS_TYPEARRAY_SIZE) { return false; } QHandleType *pType = &m_Types[type]; if (pType->typeSec.ident && pType->typeSec.ident != ident) { return false; } if (pType->dispatch == NULL) { return false; } /* Remove children if we have to */ if (!(type & HANDLESYS_SUBTYPE_MASK)) { QHandleType *childType; for (unsigned int i=1; i<=HANDLESYS_MAX_SUBTYPES; i++) { childType = &m_Types[type + i]; if (childType->dispatch) { RemoveType(type + i, childType->typeSec.ident); } } /* Link us into the free chain */ m_Types[++m_FreeTypes].freeID = type; } /* Invalidate the type now */ IHandleTypeDispatch *dispatch = pType->dispatch; pType->dispatch = NULL; /* Make sure nothing is using this type. */ if (pType->opened) { QHandle *pHandle; for (unsigned int i=1; i<=m_HandleTail; i++) { pHandle = &m_Handles[i]; if (!pHandle->set || pHandle->type != type) { continue; } if (pHandle->clone) { /* Get parent */ QHandle *pOther = &m_Handles[pHandle->clone]; if (--pOther->refcount == 0) { /* Free! */ dispatch->OnHandleDestroy(type, pOther->object); ReleasePrimHandle(pHandle->clone); } /* Unlink ourselves since we don't have a reference count */ ReleasePrimHandle(i); } else { /* If it's not a clone, we still have to check the reference count. * Either way, we'll be destroyed eventually because the handle types do not change. */ if (--pHandle->refcount == 0) { /* Free! */ dispatch->OnHandleDestroy(type, pHandle->object); ReleasePrimHandle(i); } } if (pType->opened == 0) { break; } } } return true; } bool HandleSystem::InitAccessDefaults(TypeAccess *pTypeAccess, HandleAccess *pHandleAccess) { if (pTypeAccess) { if (pTypeAccess->hsVersion > SMINTERFACE_HANDLESYSTEM_VERSION) { return false; } pTypeAccess->access[HTypeAccess_Create] = false; pTypeAccess->access[HTypeAccess_Inherit] = false; pTypeAccess->ident = NULL; } if (pHandleAccess) { if (pHandleAccess->hsVersion > SMINTERFACE_HANDLESYSTEM_VERSION) { return false; } pHandleAccess->access[HandleAccess_Clone] = 0; pHandleAccess->access[HandleAccess_Delete] = HANDLE_RESTRICT_OWNER; pHandleAccess->access[HandleAccess_Read] = HANDLE_RESTRICT_IDENTITY; } return true; } bool HandleSystem::TryAndFreeSomeHandles() { IPluginIterator *pl_iter = g_PluginSys.GetPluginIterator(); IPlugin *highest_owner = NULL; unsigned int highest_handle_count = 0; /* Search all plugins */ while (pl_iter->MorePlugins()) { IPlugin *plugin = pl_iter->GetPlugin(); IdentityToken_t *identity = plugin->GetIdentity(); unsigned int handle_count = 0; if (identity == NULL) { continue; } /* Search all handles */ for (unsigned int i = 1; i <= m_HandleTail; i++) { if (m_Handles[i].set != HandleSet_Used) { continue; } if (m_Handles[i].owner == identity) { handle_count++; } } if (handle_count > highest_handle_count) { highest_owner = plugin; highest_handle_count = handle_count; } pl_iter->NextPlugin(); } if (highest_owner == NULL || highest_handle_count == 0) { return false; } g_Logger.LogFatal("[SM] MEMORY LEAK DETECTED IN PLUGIN (file \"%s\")", highest_owner->GetFilename()); g_Logger.LogFatal("[SM] Reloading plugin to free %d handles.", highest_handle_count); g_Logger.LogFatal("[SM] Contact the author(s) of this plugin to correct this error.", highest_handle_count); highest_owner->GetContext()->n_err = SP_ERROR_MEMACCESS; return g_PluginSys.UnloadPlugin(highest_owner); } void HandleSystem::Dump(HANDLE_REPORTER rep) { char refcount[20], parent[20]; unsigned int total_size = 0; rep("%-10.10s\t%-20.20s\t%-20.20s\t%-10.10s\t%-10.10s\t%-10.10s", "Handle", "Owner", "Type", "Memory", "Refcount", "Parent"); rep("--------------------------------------------------------------------------"); for (unsigned int i = 1; i <= m_HandleTail; i++) { if (m_Handles[i].set != HandleSet_Used) { continue; } /* Get the index */ unsigned int index = (m_Handles[i].serial << 16) | i; /* Determine the owner */ const char *owner = "UNKNOWN"; if (m_Handles[i].owner) { IdentityToken_t *pOwner = m_Handles[i].owner; if (pOwner == g_pCoreIdent) { owner = "CORE"; } else if (pOwner == g_PluginSys.GetIdentity()) { owner = "PLUGINSYS"; } else { CExtension *ext = g_Extensions.GetExtensionFromIdent(pOwner); if (ext) { owner = ext->GetFilename(); } else { CPlugin *pPlugin = g_PluginSys.GetPluginFromIdentity(pOwner); if (pPlugin) { owner = pPlugin->GetFilename(); } } } } else { owner = "NONE"; } const char *type = "ANON"; QHandleType *pType = &m_Types[m_Handles[i].type]; unsigned int size = 0; if (pType->nameIdx != -1) { type = m_strtab->GetString(pType->nameIdx); } if (m_Handles[i].clone == 0) { UTIL_Format(refcount, sizeof(refcount), "%d", m_Handles[i].refcount); UTIL_Format(parent, sizeof(parent), "NULL"); } else { UTIL_Format(refcount, sizeof(refcount), "%d", m_Handles[m_Handles[i].clone].refcount); UTIL_Format(parent, sizeof(parent), "%d", m_Handles[i].clone); } if (pType->dispatch->GetDispatchVersion() < HANDLESYS_MEMUSAGE_MIN_VERSION || !pType->dispatch->GetHandleApproxSize(m_Handles[i].type, m_Handles[i].object, &size)) { rep("0x%08x\t%-20.20s\t%-20.20s\t%-10.10s\t%-10.10s\t%-10.10s", index, owner, type, "-1", refcount, parent); } else { char buffer[32]; UTIL_Format(buffer, sizeof(buffer), "%d", size); rep("0x%08x\t%-20.20s\t%-20.20s\t%-10.10s\t%-10.10s\t%-10.10s", index, owner, type, buffer, refcount, parent); total_size += size; } } rep("-- Approximately %d bytes of memory are in use by Handles.\n", total_size); }
[ [ [ 1, 1 ], [ 4, 5 ], [ 7, 7 ], [ 11, 11 ], [ 16, 16 ], [ 19, 19 ], [ 28, 1078 ] ], [ [ 2, 3 ], [ 6, 6 ], [ 8, 10 ], [ 12, 15 ], [ 17, 18 ], [ 20, 27 ] ] ]
5e9e37c9976f08f8dc0c41af0e100c90982d64f3
10dae5a20816dba197ecf76d6200fd1a9763ef97
/src/lce_disperse.cpp
a9597f85f65cb1d5508576af1a2b315ca7603a28
[]
no_license
peterdfields/quantiNEMO_Taylor2010
fd43aba9b1fcf504132494ff63d08a9b45b3f683
611b46bf89836c4327fe64abd7b4008815152c9f
refs/heads/master
2020-02-26T17:33:24.396350
2011-02-08T23:08:34
2011-02-08T23:08:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
60,875
cpp
/** @file LCEdisperse.cpp * * Copyright (C) 2006 Frederic Guillaume <[email protected]> * Copyright (C) 2008 Samuel Neuenschwander <[email protected]> * * quantiNEMO: * quantiNEMO is an individual-based, genetically explicit stochastic * simulation program. It was developed to investigate the effects of * selection, mutation, recombination, and drift on quantitative traits * with varying architectures in structured populations connected by * migration and located in a heterogeneous habitat. * * quantiNEMO is built on the evolutionary and population genetics * programming framework NEMO (Guillaume and Rougemont, 2006, Bioinformatics). * * * Licensing: * This file is part of quantiNEMO. * * quantiNEMO 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. * * quantiNEMO 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 quantiNEMO. If not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <cmath> #include "lce_disperse.h" #include "metapop.h" #include "individual.h" #include "stathandler.cpp" #include "simulation.h" /******************************************************************************/ // ******** LCE_Disperse ******** /******************************************************************************/ LCE_Disperse::LCE_Disperse(int rank) : LCE("disperse","",rank), _disperser(NULL), _colonizer(NULL) { // migration/dispersal parameters this->add_parameter("dispersal_model",INT2,false,true,0,3,"0"); this->add_parameter("dispersal_border_model",INT2,false,true,0,2,"0"); this->add_parameter("dispersal_lattice_range",INT2,false,true,0,1,"0"); this->add_parameter("dispersal_lattice_dims",MAT, false, false,0,0,""); this->add_parameter("dispersal_propagule_prob",DBL,false,true,0,1,"1",true); this->add_parameter("dispersal_rate",DBL_MAT,false,false,0,0,"0", true); this->add_parameter("dispersal_rate_fem",DBL_MAT,false,false,0,0,"0",true); this->add_parameter("dispersal_rate_mal",DBL_MAT,false,false,0,0,"0",true); this->add_parameter("dispersal_k_threshold",DBL,false,true,0,1,"0"); this->add_parameter("dispersal_k_min",DBL,false,false,0,0,"0"); this->add_parameter("dispersal_k_max",DBL,false,false,0,0,"1"); this->add_parameter("dispersal_k_max_growth",DBL,false,false,0,0,"-1"); this->add_parameter("dispersal_k_growth_rate",DBL,false,false,0,0,"1e4"); this->add_parameter("dispersal_k_symmetry",DBL,false,false,0,0,"1"); // colonization parameters this->add_parameter("colonization_model",INT2,false,true,0,3,"0"); this->add_parameter("colonization_border_model",INT2,false,true,0,2,"0"); this->add_parameter("colonization_lattice_range",INT2,false,true,0,1,"0"); this->add_parameter("colonization_lattice_dims",MAT, false, false,0,0,""); this->add_parameter("colonization_propagule_prob",DBL,false,true,0,1,"1", true); this->add_parameter("colonization_rate",DBL_MAT,false,false,0,0,"0", true); this->add_parameter("colonization_rate_fem",DBL_MAT,false,false,0,0,"0", true); this->add_parameter("colonization_rate_mal",DBL_MAT,false,false,0,0,"0", true); this->add_parameter("colonization_k_threshold",DBL,false,true,0,1,"0"); this->add_parameter("colonization_k_min",DBL,false,false,0,0,"0"); this->add_parameter("colonization_k_max",DBL,false,false,0,0,"1"); this->add_parameter("colonization_k_max_growth",DBL,false,false,0,0,"-1"); this->add_parameter("colonization_k_growth_rate",DBL,false,false,0,0,"1e4"); this->add_parameter("colonization_k_symmetry",DBL,false,false,0,0,"1"); } // ----------------------------------------------------------------------------- LCE_Disperse::~LCE_Disperse() { if(_disperser) delete _disperser; if(_colonizer) delete _colonizer; } // ----------------------------------------------------------------------------- // LCE_Disperse::execute // ----------------------------------------------------------------------------- void LCE_Disperse::execute() { #ifdef _DEBUG message(" LCE_Disperse ... "); #endif preDispersal(); if( _colonizer ) { _colonizer->execute(); } _disperser->execute(); postDispersal(); #ifdef _DEBUG unsigned int c = 0; for(unsigned int i = 0; i < _nb_patch; i++) { c += _popPtr->getPatch(i)->nbEmigrant; } message("done! (nbEmigrants: %i; Individuals(F/M): [%i/%i; %i/%i])\n", c, _popPtr->size(FEM, OFFSPRG), _popPtr->size(MAL, OFFSPRG), _popPtr->size(FEM, ADULTS), _popPtr->size(MAL, ADULTS)); #endif } // ----------------------------------------------------------------------------- // LCE_Disperse::preDispersal // ----------------------------------------------------------------------------- /** prepares the dispersal, resets counters,... */ void LCE_Disperse::preDispersal() { Patch* curPatch; for(unsigned int i = 0; i < _nb_patch; i++) { curPatch = _popPtr->getPatch(i); // remove all adult individuals _popPtr->getPatch(i)->flush(ADLTx); // reset counters curPatch->nbKolonisers = curPatch->get_isExtinct() ? 0 : my_NAN; curPatch->nbImmigrant = 0; curPatch->nbEmigrant = 0; } } // ----------------------------------------------------------------------------- // LCE_Disperse::postDispersal // ----------------------------------------------------------------------------- /** set the demographic information about colonization and migration of the * current patch * nbEmigrant: is not incremented here but in the function _sendEmigrants * nbImmigrant: is not incremented here but in the function _sendEmigrants */ void LCE_Disperse::postDispersal() { Patch* current_patch; // for each patch for(unsigned int i = 0; i < _nb_patch; i++) { current_patch = _popPtr->getPatch(i); // change offspring to adults for each patch current_patch->move(OFFSx, ADLTx); // was the patch extinct? if(current_patch->get_isExtinct()) { // set the age since colonization current_patch->colnAge = 0; // if the patch is now inhabited we have colonizers assert(current_patch->nbImmigrant == current_patch->size(ADLTx)); if(current_patch->nbImmigrant) { current_patch->set_isExtinct(false); // colonizers are also immigrants current_patch->nbKolonisers = current_patch->nbImmigrant; } continue; // go to the next patch } else { // increment age since colonization for extant patches ++(current_patch->colnAge); } // is the patch now extinct? if(!current_patch->size(ADLTx)) { current_patch->set_isExtinct(true); continue; // go to the next patch } // compute the number of residents current_patch->nbPhilopat = current_patch->size(ADLTx) - current_patch->nbImmigrant; } } // ----------------------------------------------------------------------------- // LCE_Disperse::init // ----------------------------------------------------------------------------- bool LCE_Disperse::init (Metapop* popPtr) { LCE::init(popPtr); // clear the Dispersers if(_disperser) delete _disperser; if(_colonizer) delete _colonizer; _disperser = _colonizer = NULL; // if only one patch is used there is simply no migration _nb_patch = popPtr->getPatchNbr(); if( _nb_patch == 1 ) { _disperser = new Disperser(_paramSet, DISP_NONE); return true; } // create the Dispersers if( _paramSet->isSet("colonization_model") || _paramSet->isSet("colonization_border_model") || _paramSet->isSet("colonization_lattice_range") || _paramSet->isSet("colonization_lattice_dims") || _paramSet->isSet("colonization_propagule_prob") || _paramSet->isSet("colonization_rate") || _paramSet->isSet("colonization_rate_fem") || _paramSet->isSet("colonization_rate_mal") || _paramSet->isSet("colonization_k_threshold") || _paramSet->isSet("colonization_k_min") || _paramSet->isSet("colonization_k_max") || _paramSet->isSet("colonization_k_max_growth") || _paramSet->isSet("colonization_k_growth_rate") || _paramSet->isSet("colonization_k_symmetry") ) { _disperser = new Disperser(_paramSet, DISP_MIGR); _colonizer = new Disperser(_paramSet, DISP_COLN); _colonizer->init(popPtr); } else { _disperser = new Disperser(_paramSet, DISP_BOTH); } _disperser->init(popPtr); return true; } //----------------------------------------------------------------------------- // LCE_Disperse::executeBeforeEachGeneration //----------------------------------------------------------------------------- void LCE_Disperse::executeBeforeEachGeneration(const int& gen) { // temporal parameters map<string, Param*>* pParam = _paramSet->getTemporalParams(gen); // if it is a temporal paramter if(pParam) { // check if a change has to be made if(_paramSet->updateTemporalParams(gen)) init(_popPtr); } } /******************************************************************************/ // ******** Disperser ******** /******************************************************************************/ Disperser::Disperser(ParamSet *paramSet, DISP_TYPE type) : _disp_model(0), _border_model(0), _lattice_range(0), _disp_propagule_prob(0), _disp_factor(0) { // set the parameter set pointer _paramSet = paramSet; // set the dispersal type (none, migr, coln, both) _disp_type = type; for(int i=0; i<2; ++i) { _dispMatrix[i] = NULL; _migr_rate[i] = 0; _lattice_dims[i] = 0; } } // ----------------------------------------------------------------------------- Disperser::~Disperser() { if(_dispMatrix[0]) delete _dispMatrix[0]; if(_dispMatrix[1]) delete _dispMatrix[1]; if(_disp_factor) delete[] _disp_factor; } // ----------------------------------------------------------------------------- // Disperser::disperse_zeroDispersal // ----------------------------------------------------------------------------- /** This function is set, when there is no dispersal or if there is only a * single population. */ void Disperser::disperse_zeroDispersal() {} // ----------------------------------------------------------------------------- // Disperser::setDispMatrix // ----------------------------------------------------------------------------- void Disperser::setDispMatrix (TMatrix* mat) { checkDispMatrix(mat); if(_dispMatrix[0]) delete _dispMatrix[0]; if(_dispMatrix[1]) delete _dispMatrix[1]; _dispMatrix[0] = new TMatrix(*mat); _dispMatrix[1] = new TMatrix(*mat); } // ----------------------------------------------------------------------------- // Disperser::setDispMatrix // ----------------------------------------------------------------------------- void Disperser::setDispMatrix (sex_t sex, TMatrix* mat) { checkDispMatrix(mat); if(_dispMatrix[sex]) delete _dispMatrix[sex]; _dispMatrix[sex] = new TMatrix(*mat); } // ----------------------------------------------------------------------------- // Disperser::checkDispMatrix // ----------------------------------------------------------------------------- void Disperser::checkDispMatrix (TMatrix* mat) { double cntr; unsigned int i, j; mat->get_dims(_lattice_dims); if(_lattice_dims[0] != _lattice_dims[1] || _lattice_dims[0] != _nb_patch) { fatal("The dimension of the dispersal matrix (%ix%i) does not " "match the number of patches (%i)!\n", _lattice_dims[0], _lattice_dims[1], _nb_patch); } for(i = 0; i < _lattice_dims[0]; ++i) { cntr = 0; for(j = 0; j < _lattice_dims[1]; ++j) { cntr += mat->get(i,j); } // (cntr != 1): floating numbers can never be the same if(abs(1-cntr) > 1e-4) { warning("The elements of row %i of the dispersal matrix do " "not sum to 1!\n", i+1); } } } // ----------------------------------------------------------------------------- // Disperser::execute // ----------------------------------------------------------------------------- void Disperser::execute() { (this->*doDispersal)(); } // ----------------------------------------------------------------------------- // Disperser::dispersal_matrix // ----------------------------------------------------------------------------- /** if the dispersal rates are defined by a matrix */ void Disperser::dispersal_matrix() { Patch *current_patch; int nbInd[2]; double disp[2]; unsigned int home, target; double factor; // for each patch for(home = 0; home < _nb_patch; ++home) { current_patch = _popPtr->getPatch(home); nbInd[FEM] = current_patch->size(FEM, OFFSx); nbInd[MAL] = current_patch->size(MAL, OFFSx); factor = (this->*get_disp_factor_funcPtr)(current_patch); // dispersal to each other patch for(target=0; target<_nb_patch; ++target) { // if it is the same patch, continue if( home == target ) continue; disp[FEM] = _dispMatrix[FEM]->get(home,target); disp[MAL] = _dispMatrix[MAL]->get(home,target); // send the emigrants _sendEmigrants(current_patch, home, target, nbInd, disp, factor); } // end for each target }//end for each home patch } // ----------------------------------------------------------------------------- // Disperser::_sendEmigrants // ----------------------------------------------------------------------------- /** function to send emigrants from the home to the target patch for both sexes. * If the migration rate is negative, the emigrating individuals are removed * (absorbed) */ void Disperser::_sendEmigrants(Patch* curPatch, const int& home, const int& target, int* nbInd, double* dispRate, const double& factor) { _sendEmigrants(curPatch, home, target, nbInd[FEM], dispRate[FEM], factor, FEM); _sendEmigrants(curPatch, home, target, nbInd[MAL], dispRate[MAL], factor, MAL); } // ----------------------------------------------------------------------------- // Disperser::_sendEmigrants // ----------------------------------------------------------------------------- /** function to send emigrants form the home to the target patch for a specific * sex. If the migration rate is negative, the emigrating individuals are * removed (absorbed) */ void Disperser::_sendEmigrants(Patch* curPatch, const int& home, const int& target, const int& size, const double& dispRate, const double& factor, const sex_t& SEX) { double d = dispRate * factor; int nb_emigrants; // check if dispersal occurs if(!d) return; // get the number of individuals remaining in the patch int curSize = curPatch->size(SEX,OFFSx); if(!curSize) return; // check for failed colonization/migration (colonists to nonextinct patch // or migrants to extinct patch) if( d > 0 && (_disp_type && ((_disp_type ^ DISP_MIGR) ^ DISP_COLN)) ) { if( (bool)(_disp_type & DISP_COLN) ^ (bool)(_popPtr->getPatch(target)->get_isExtinct()) ) { // failed emigrants will be removed d = -d; } } // perform migration if(d>0) { // normal migration // number of emigrants defined if(d>=1) nb_emigrants = my_round(d); // emigration rate defined else nb_emigrants = (int)SimRunner::r.Binomial(d, size); // return no emigrants if(!nb_emigrants) return; // if there are not enough individuals if(nb_emigrants > curSize) nb_emigrants = curSize; // set the number of emigrants curPatch->nbEmigrant += nb_emigrants; // set the number of immigrants of the target patch _popPtr->getPatch(target)->nbImmigrant += nb_emigrants; for(; nb_emigrants; --curSize, --nb_emigrants) { _popPtr->move(SEX, OFFSx, home, ADLTx, target, SimRunner::r.Uniform(curSize)); } } else { // emigrants are removed (absorbing boundaries) // number of emigrants defined if(d<=-1) nb_emigrants = my_round((-1)*d); // emigration rate defined else nb_emigrants = (int)SimRunner::r.Binomial((-1)*d, size); // return no emigrants if(!nb_emigrants) return; // if there are not enough individuals if(nb_emigrants > curSize) nb_emigrants = curSize; curPatch->nbEmigrant += nb_emigrants; for(; nb_emigrants; --curSize, --nb_emigrants) { curPatch->recycle(SEX, OFFSx, SimRunner::r.Uniform(curSize)); } } } // ----------------------------------------------------------------------------- // Disperser::disperse_island // ----------------------------------------------------------------------------- /** island migration model with a female and a male migration rate * migration rate to any patch is m/(_nb_patch-1) */ void Disperser::disperse_island() { Patch *current_patch; int nbInd[2]; unsigned int home, target; double factor; // for each patch for(home = 0; home < _nb_patch; ++home) { current_patch = _popPtr->getPatch(home); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); // dispersal to each other patch for(target=0; target<_nb_patch; ++target) { // if it is the same patch, continue if( home == target ) continue; // send emigrants _sendEmigrants(current_patch, home, target, nbInd, _migr_rate, factor); } // end for each target }//end for each home patch } // ----------------------------------------------------------------------------- // Disperser::disperse_island_propagule // ----------------------------------------------------------------------------- /** island migration model with a female and a male migration rate * migration rate to any patch is m/(_nb_patch-1) */ void Disperser::disperse_island_propagule() { Patch *current_patch; int nbInd[2]; unsigned int home, target, propagule; double factor; // for each patch for(home = 0; home < _nb_patch; ++home) { current_patch = _popPtr->getPatch(home); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); // dispersal to the propagule patch do{ // draw the propagule patch randomly propagule = SimRunner::r.Uniform(_nb_patch); } while( home == propagule ); _sendEmigrants(current_patch, home, propagule, nbInd, _migr_rate_propagule, factor); // migration to each other patch for( target=0; target<_nb_patch; ++target ) { // if it is the same patch, continue if( home == target ) continue; // send emigrants _sendEmigrants(current_patch, home, target, nbInd, _migr_rate, factor); } // end for each target }//end for each home patch } // ----------------------------------------------------------------------------- // Disperser::disperse_1D_stepping_stone // ----------------------------------------------------------------------------- /** island migration model with a female and a male migration rate * migration rate to any patch is m/2, except for the edge patches */ void Disperser::disperse_1D_stepping_stone() { Patch *current_patch; int nbInd[2]; double factor; // for each patch in the middle: 1-_nb_patch-2 for(unsigned int home = 1; home < _nb_patch-1; ++home) { current_patch = _popPtr->getPatch(home); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL]= current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, home, home-1, nbInd, _migr_rate, factor); // migrate left _sendEmigrants(current_patch, home, home+1, nbInd, _migr_rate, factor); // migrate right current_patch->move(OFFSx,ADLTx); // not migrated individuals remain in the original patch }//end for each home patch // edge patches (first patch) current_patch = _popPtr->getPatch(0); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL]= current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, 0, _nb_patch-1, nbInd, _migr_rateOut, factor); // migrate left _sendEmigrants(current_patch, 0, 1, nbInd, _migr_rateIn, factor); // migrate right current_patch->move(OFFSx,ADLTx); // not migrated individuals remain in the original patch // edge patches (last patch) current_patch = _popPtr->getPatch(_nb_patch-1); // last patch nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL]= current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, _nb_patch-1, _nb_patch-2, nbInd, _migr_rateIn, factor); // migrate left _sendEmigrants(current_patch, _nb_patch-1, 0, nbInd, _migr_rateOut, factor); // migrate right current_patch->move(OFFSx,ADLTx); // not migrated individuals remain in the original patch } // ----------------------------------------------------------------------------- // Disperser::_disperse_2D_SS_middle_4Neighbour // ----------------------------------------------------------------------------- /** 2D stepping stone migration of the middle patches (4 neighbours)*/ void Disperser::_disperse_2D_SS_middle_4Neighbour() { Patch *current_patch; int nbInd[2]; unsigned int r, c, home; unsigned int x = _lattice_dims[0]; unsigned int y = _lattice_dims[1]; double factor; // for each patch in the middle for(c = 1; c < y-1; ++c) { // for each column for(r = 1; r < x-1; ++r) { // for each row home = c*x+r; current_patch = _popPtr->getPatch(home); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); // migrate _sendEmigrants(current_patch, home, home-1, nbInd, _migr_rate, factor); // left _sendEmigrants(current_patch, home, home+1, nbInd, _migr_rate, factor); // right _sendEmigrants(current_patch, home, home-x, nbInd, _migr_rate, factor); // up _sendEmigrants(current_patch, home, home+x, nbInd, _migr_rate, factor); // down } }//end for each home patch } // ----------------------------------------------------------------------------- // Disperser::_disperse_2D_SS_middle_8Neighbour // ----------------------------------------------------------------------------- /** 2D stepping stone migration of the middle patches (8 neighbours)*/ void Disperser::_disperse_2D_SS_middle_8Neighbour() { Patch *current_patch; int nbInd[2]; unsigned int r, c, home; unsigned int x = _lattice_dims[0]; unsigned int y = _lattice_dims[1]; double factor; // for each patch in the middle for(c = 1; c < y-1; ++c) { // for each column for(r = 1; r < x-1; ++r) { // for each row home = c*x+r; current_patch = _popPtr->getPatch(home); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); // migrate _sendEmigrants(current_patch, home, home+1, nbInd, _migr_rate, factor); // right _sendEmigrants(current_patch, home, home+1+x, nbInd, _migr_rate, factor); // right down _sendEmigrants(current_patch, home, home+x, nbInd, _migr_rate, factor); // down _sendEmigrants(current_patch, home, home-1+x, nbInd, _migr_rate, factor); // left down _sendEmigrants(current_patch, home, home-1, nbInd, _migr_rate, factor); // left _sendEmigrants(current_patch, home, home-1-x, nbInd, _migr_rate, factor); // left up _sendEmigrants(current_patch, home, home-x, nbInd, _migr_rate, factor); // up _sendEmigrants(current_patch, home, home+1-x, nbInd, _migr_rate, factor); // right up } }//end for each home patch } // ----------------------------------------------------------------------------- // Disperser::_disperse_2D_SS_edge_4Neighbour // ----------------------------------------------------------------------------- void Disperser::_disperse_2D_SS_edge_4Neighbour() { Patch* current_patch; int nbInd[2]; unsigned int x = _lattice_dims[0]; unsigned int home; double factor; // upper edge for(home = 1; home <= x-2; ++home) { current_patch = _popPtr->getPatch(home); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, home, home+1, nbInd, _migr_rateIn, factor); // right _sendEmigrants(current_patch, home, home+x, nbInd, _migr_rateIn, factor); // down _sendEmigrants(current_patch, home, home-1, nbInd, _migr_rateIn, factor); // left _sendEmigrants(current_patch, home, _nb_patch+home-x, nbInd, _migr_rateOut, factor); // up } // right edge for(home = (2*x)-1; home <= _nb_patch-x-1; home+=x) { current_patch = _popPtr->getPatch(home); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, home, home-x+1, nbInd, _migr_rateOut, factor); // right _sendEmigrants(current_patch, home, home+x, nbInd, _migr_rateIn, factor); // down _sendEmigrants(current_patch, home, home-1, nbInd, _migr_rateIn, factor); // left _sendEmigrants(current_patch, home, home-x, nbInd, _migr_rateIn, factor); // up } // lower edge for(home = _nb_patch-x+1; home <= _nb_patch-2; ++home) { current_patch = _popPtr->getPatch(home); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, home, home+1, nbInd, _migr_rateIn, factor); // right _sendEmigrants(current_patch, home, home-_nb_patch+x, nbInd, _migr_rateOut, factor); // down _sendEmigrants(current_patch, home, home-1, nbInd, _migr_rateIn, factor); // left _sendEmigrants(current_patch, home, home-x, nbInd, _migr_rateIn, factor); // up } // left edge for(home = x; home <= _nb_patch-(2*x); home+=x) { current_patch = _popPtr->getPatch(home); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, home, home+1, nbInd, _migr_rateIn, factor); // right _sendEmigrants(current_patch, home, home+x, nbInd, _migr_rateIn, factor); // down _sendEmigrants(current_patch, home, home+x-1, nbInd, _migr_rateOut, factor); // left _sendEmigrants(current_patch, home, home-x, nbInd, _migr_rateIn, factor); // up } } // ----------------------------------------------------------------------------- // Disperser::_disperse_2D_SS_edge_8Neighbour // ----------------------------------------------------------------------------- void Disperser::_disperse_2D_SS_edge_8Neighbour() { Patch* current_patch; int nbInd[2]; unsigned int x = _lattice_dims[0]; unsigned int home; double factor; // upper edge for(home = 1; home <= x-2; ++home) { current_patch = _popPtr->getPatch(home); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, home, home+1, nbInd, _migr_rateIn, factor); // right _sendEmigrants(current_patch, home, home+x+1, nbInd, _migr_rateIn, factor); // right down _sendEmigrants(current_patch, home, home+x, nbInd, _migr_rateIn, factor); // down _sendEmigrants(current_patch, home, home+x-1, nbInd, _migr_rateIn, factor); // left down _sendEmigrants(current_patch, home, home-1, nbInd, _migr_rateIn, factor); // left _sendEmigrants(current_patch, home, _nb_patch+home-x-1, nbInd, _migr_rateOut, factor); // left up _sendEmigrants(current_patch, home, _nb_patch+home-x, nbInd, _migr_rateOut, factor); // up _sendEmigrants(current_patch, home, _nb_patch+home-x+1, nbInd, _migr_rateOut, factor); // right up } // right edge for(home = (2*x)-1; home <= _nb_patch-x-1; home+=x) { current_patch = _popPtr->getPatch(home); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, home, home-x+1, nbInd, _migr_rateOut, factor); // right _sendEmigrants(current_patch, home, home+1, nbInd, _migr_rateOut, factor); // right down _sendEmigrants(current_patch, home, home+x, nbInd, _migr_rateIn, factor); // down _sendEmigrants(current_patch, home, home+x-1, nbInd, _migr_rateIn, factor); // left down _sendEmigrants(current_patch, home, home-1, nbInd, _migr_rateIn, factor); // left _sendEmigrants(current_patch, home, home-x-1, nbInd, _migr_rateIn, factor); // left up _sendEmigrants(current_patch, home, home-x, nbInd, _migr_rateIn, factor); // up _sendEmigrants(current_patch, home, home-(2*x)+1, nbInd, _migr_rateOut, factor); // right up } // lower edge for(home = _nb_patch-x+1; home <= _nb_patch-2; ++home) { current_patch = _popPtr->getPatch(home); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, home, home+1, nbInd, _migr_rateIn, factor); // right _sendEmigrants(current_patch, home, home-_nb_patch+x+1, nbInd, _migr_rateOut, factor); // right down _sendEmigrants(current_patch, home, home-_nb_patch+x, nbInd, _migr_rateOut, factor); // down _sendEmigrants(current_patch, home, home-_nb_patch+x-1, nbInd, _migr_rateOut, factor); // left down _sendEmigrants(current_patch, home, home-1, nbInd, _migr_rateIn, factor); // left _sendEmigrants(current_patch, home, home-x-1, nbInd, _migr_rateIn, factor); // left up _sendEmigrants(current_patch, home, home-x, nbInd, _migr_rateIn, factor); // up _sendEmigrants(current_patch, home, home-x+1, nbInd, _migr_rateIn, factor); // right up } // left edge for(home = x; home <= _nb_patch-(2*x); home+=x) { current_patch = _popPtr->getPatch(home); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, home, home+1, nbInd, _migr_rateIn, factor); // right _sendEmigrants(current_patch, home, home+x+1, nbInd, _migr_rateIn, factor); // right down _sendEmigrants(current_patch, home, home+x, nbInd, _migr_rateIn, factor); // down _sendEmigrants(current_patch, home, home+(2*x)-1, nbInd, _migr_rateOut, factor); // left down _sendEmigrants(current_patch, home, home+x-1, nbInd, _migr_rateOut, factor); // left _sendEmigrants(current_patch, home, home-1, nbInd, _migr_rateOut, factor); // left up _sendEmigrants(current_patch, home, home-x, nbInd, _migr_rateIn, factor); // up _sendEmigrants(current_patch, home, home-x+1, nbInd, _migr_rateIn, factor); // right up } } // ----------------------------------------------------------------------------- // Disperser::_disperse_2D_SS_corner_4Neighbour // ----------------------------------------------------------------------------- void Disperser::_disperse_2D_SS_corner_4Neighbour() { Patch* current_patch; int nbInd[2]; unsigned int x = _lattice_dims[0]; double factor; // first corner current_patch = _popPtr->getPatch(0); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, 0, 1, nbInd, _migr_rateCorner, factor); // right _sendEmigrants(current_patch, 0, x, nbInd, _migr_rateCorner, factor); // down _sendEmigrants(current_patch, 0, x-1, nbInd, _migr_rateOut, factor); // left _sendEmigrants(current_patch, 0, _nb_patch-x, nbInd, _migr_rateOut, factor); // up // second corner current_patch = _popPtr->getPatch(x-1); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, x-1, 0, nbInd, _migr_rateOut, factor); // right _sendEmigrants(current_patch, x-1, 2*x-1, nbInd, _migr_rateCorner, factor); // down _sendEmigrants(current_patch, x-1, x-2, nbInd, _migr_rateCorner, factor); // left _sendEmigrants(current_patch, x-1, _nb_patch-1, nbInd, _migr_rateOut, factor); // up // third corner current_patch = _popPtr->getPatch(_nb_patch-x); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, _nb_patch-x, _nb_patch-x+1, nbInd, _migr_rateCorner, factor); // right _sendEmigrants(current_patch, _nb_patch-x, 0, nbInd, _migr_rateOut, factor); // down _sendEmigrants(current_patch, _nb_patch-x, _nb_patch-1, nbInd, _migr_rateOut, factor); // left _sendEmigrants(current_patch, _nb_patch-x, _nb_patch-(2*x), nbInd, _migr_rateCorner, factor); // up // forth corner current_patch = _popPtr->getPatch(_nb_patch-1); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, _nb_patch-1, _nb_patch-x, nbInd, _migr_rateOut, factor); // right _sendEmigrants(current_patch, _nb_patch-1, x-1, nbInd, _migr_rateOut, factor); // down _sendEmigrants(current_patch, _nb_patch-1, _nb_patch-2, nbInd, _migr_rateCorner, factor); // left _sendEmigrants(current_patch, _nb_patch-1, _nb_patch-x-1, nbInd, _migr_rateCorner, factor); // up } // ----------------------------------------------------------------------------- // Disperser::_disperse_2D_SS_corner_8Neighbour // ----------------------------------------------------------------------------- void Disperser::_disperse_2D_SS_corner_8Neighbour() { Patch* current_patch; int nbInd[2]; unsigned int x = _lattice_dims[0]; double factor; // first corner current_patch = _popPtr->getPatch(0); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, 0, 1, nbInd, _migr_rateCorner, factor); // right _sendEmigrants(current_patch, 0, x+1, nbInd, _migr_rateCorner, factor); // right down _sendEmigrants(current_patch, 0, x, nbInd, _migr_rateCorner, factor); // down _sendEmigrants(current_patch, 0, 2*x-1, nbInd, _migr_rateOut, factor); // left down _sendEmigrants(current_patch, 0, x-1, nbInd, _migr_rateOut, factor); // left _sendEmigrants(current_patch, 0, _nb_patch-1, nbInd, _migr_rateOut, factor); // left up _sendEmigrants(current_patch, 0, _nb_patch-x, nbInd, _migr_rateOut, factor); // up _sendEmigrants(current_patch, 0, _nb_patch-x+1, nbInd, _migr_rateOut, factor); // right up // second corner current_patch = _popPtr->getPatch(x-1); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, x-1, 0, nbInd, _migr_rateOut, factor); // right _sendEmigrants(current_patch, x-1, x, nbInd, _migr_rateOut, factor); // right down _sendEmigrants(current_patch, x-1, 2*x-1, nbInd, _migr_rateCorner, factor); // down _sendEmigrants(current_patch, x-1, 2*x-2, nbInd, _migr_rateCorner, factor); // left down _sendEmigrants(current_patch, x-1, x-2, nbInd, _migr_rateCorner, factor); // left _sendEmigrants(current_patch, x-1, _nb_patch-2, nbInd, _migr_rateOut, factor); // left up _sendEmigrants(current_patch, x-1, _nb_patch-1, nbInd, _migr_rateOut, factor); // up _sendEmigrants(current_patch, x-1, _nb_patch-x, nbInd, _migr_rateOut, factor); // right up // third corner current_patch = _popPtr->getPatch(_nb_patch-x); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, _nb_patch-x, _nb_patch-x+1, nbInd, _migr_rateCorner, factor); // right _sendEmigrants(current_patch, _nb_patch-x, 1, nbInd, _migr_rateOut, factor); // right down _sendEmigrants(current_patch, _nb_patch-x, 0, nbInd, _migr_rateOut, factor); // down _sendEmigrants(current_patch, _nb_patch-x, x-1, nbInd, _migr_rateOut, factor); // left down _sendEmigrants(current_patch, _nb_patch-x, _nb_patch-1, nbInd, _migr_rateOut, factor); // left _sendEmigrants(current_patch, _nb_patch-x, _nb_patch-x-1, nbInd, _migr_rateOut, factor); // left up _sendEmigrants(current_patch, _nb_patch-x, _nb_patch-(2*x), nbInd, _migr_rateCorner, factor); // up _sendEmigrants(current_patch, _nb_patch-x, _nb_patch-(2*x)+1, nbInd, _migr_rateCorner, factor); // rigth up // fourth corner current_patch = _popPtr->getPatch(_nb_patch-1); nbInd[FEM] = current_patch->size(FEM,OFFSPRG); nbInd[MAL] = current_patch->size(MAL,OFFSPRG); factor = (this->*get_disp_factor_funcPtr)(current_patch); _sendEmigrants(current_patch, _nb_patch-1, _nb_patch-x, nbInd, _migr_rateOut, factor); // right _sendEmigrants(current_patch, _nb_patch-1, 0, nbInd, _migr_rateOut, factor); // right down _sendEmigrants(current_patch, _nb_patch-1, x-1, nbInd, _migr_rateOut, factor); // down _sendEmigrants(current_patch, _nb_patch-1, x-2, nbInd, _migr_rateOut, factor); // left down _sendEmigrants(current_patch, _nb_patch-1, _nb_patch-2, nbInd, _migr_rateCorner, factor); // left _sendEmigrants(current_patch, _nb_patch-1, _nb_patch-x-2, nbInd, _migr_rateCorner, factor); // left up _sendEmigrants(current_patch, _nb_patch-1, _nb_patch-x-1, nbInd, _migr_rateCorner, factor); // up _sendEmigrants(current_patch, _nb_patch-1, _nb_patch-(2*x), nbInd, _migr_rateOut, factor); // right up } // ----------------------------------------------------------------------------- // Disperser::disperse_2D_stepping_stone_4Neighbour // ----------------------------------------------------------------------------- void Disperser::disperse_2D_stepping_stone_4Neighbour() { // perform migration _disperse_2D_SS_middle_4Neighbour(); _disperse_2D_SS_edge_4Neighbour(); _disperse_2D_SS_corner_4Neighbour(); // all not migrated individuals remain in the original patch for(unsigned int home = 0; home < _nb_patch; ++home) { _popPtr->getPatch(home)->move(OFFSx,ADLTx); } } // ----------------------------------------------------------------------------- // Disperser::disperse_2D_stepping_stone_8Neighbour // ----------------------------------------------------------------------------- void Disperser::disperse_2D_stepping_stone_8Neighbour() { // perform migration _disperse_2D_SS_middle_8Neighbour(); _disperse_2D_SS_edge_8Neighbour(); _disperse_2D_SS_corner_8Neighbour(); // all not migrated individuals remain in the original patch for(unsigned int home = 0; home < _nb_patch; ++home) { _popPtr->getPatch(home)->move(OFFSx,ADLTx); } } // ----------------------------------------------------------------------------- // Disperser::init // ----------------------------------------------------------------------------- bool Disperser::init (Metapop* popPtr) { _popPtr = popPtr; _nb_patch = popPtr->getPatchNbr(); // if no dispersal type if( _disp_type == DISP_NONE ) { doDispersal = &Disperser::disperse_zeroDispersal; return true; } //reset matrixes if( _dispMatrix[FEM] ) {delete _dispMatrix[FEM]; _dispMatrix[FEM]=NULL;} if( _dispMatrix[MAL] ) {delete _dispMatrix[MAL]; _dispMatrix[MAL]=NULL;} // get parameters if( _disp_type & DISP_MIGR ) { _disp_model = (int)_paramSet->getValue("dispersal_model"); _disp_propagule_prob = _paramSet->getValue("dispersal_propagule_prob"); _border_model = (int)_paramSet->getValue("dispersal_border_model"); _lattice_range = (int)_paramSet->getValue("dispersal_lattice_range"); } else { _disp_model = (int)_paramSet->getValue("colonization_model"); _disp_propagule_prob = _paramSet->getValue("colonization_propagule_prob"); _border_model = (int)_paramSet->getValue("colonization_border_model"); _lattice_range = (int)_paramSet->getValue("colonization_lattice_range"); } // migration is set by matrixes if( ((_disp_type & DISP_MIGR) && ( (_paramSet->isSet("dispersal_rate") || _paramSet->isSet("dispersal_rate_fem") || _paramSet->isSet("dispersal_rate_mal")) && (_paramSet->isMatrix("dispersal_rate") || _paramSet->isMatrix("dispersal_rate_fem") || _paramSet->isMatrix("dispersal_rate_mal")) ) ) || ((_disp_type & DISP_COLN) && ( (_paramSet->isSet("colonization_rate") || _paramSet->isSet("colonization_rate_fem") || _paramSet->isSet("colonization_rate_mal")) && (_paramSet->isMatrix("colonization_rate") || _paramSet->isMatrix("colonization_rate_fem") || _paramSet->isMatrix("colonization_rate_mal")) ) ) ) { setDispersalMatrix(); } else { // migration is set by a single dispersal rate (or default) // if it is a 2D stepping stone model if( _disp_model == 3 ) _get_lattice_dims(); setDispersalRate(); } _setDispersalFactor(); return true; } // ----------------------------------------------------------------------------- // Disperser::setDispersalFactor // ----------------------------------------------------------------------------- /** set the genralized logistic function parameters * check if the function is really needed, i.e. if there is really a change */ void Disperser::_setDispersalFactor() { if(_disp_factor) { delete[] _disp_factor; _disp_factor=NULL; } // get the values _disp_factor = new double[5]; if( _disp_type & DISP_MIGR ) { _disp_factor[0] = _paramSet->getValue("dispersal_k_min"); _disp_factor[1] = _paramSet->getValue("dispersal_k_max"); _disp_factor[2] = _paramSet->getValue("dispersal_k_max_growth"); _disp_factor[3] = _paramSet->getValue("dispersal_k_growth_rate"); _disp_factor[4] = _paramSet->getValue("dispersal_k_symmetry"); if(!_disp_factor) { fatal("Parameter 'dispersal_k_symmetry' cannot be zero!\n"); } } else { _disp_factor[0] = _paramSet->getValue("colonization_k_min"); _disp_factor[1] = _paramSet->getValue("colonization_k_max"); _disp_factor[2] = _paramSet->getValue("colonization_k_max_growth"); _disp_factor[3] = _paramSet->getValue("colonization_k_growth_rate"); _disp_factor[4] = _paramSet->getValue("colonization_k_symmetry"); if(!_disp_factor) { fatal("Parameter 'colonization_k_symmetry' cannot be zero!\n"); } } // if the growth rate is too large/small, the logsitic function has a // size problem (exp) change to threshold function if( abs(_disp_factor[3]) >= STRING::str2int<double>( _paramSet->get_param( (_disp_type & DISP_MIGR ) ? "dispersal_k_growth_rate" : "colonization_k_growth_rate" )->get_default_arg()) ) { if(_disp_factor[3]<0) { // swap min and max if slope is negative double temp = _disp_factor[0]; _disp_factor[0] = _disp_factor[1]; _disp_factor[1] = temp; } if(_disp_factor[2]<0) { // where is the threshold? if(abs(_disp_factor[1]-1)<1e-6) { get_disp_factor_funcPtr = &Disperser::get_disp_factor_one; return; } else { get_disp_factor_funcPtr = &Disperser::get_disp_factor_max; return; } } get_disp_factor_funcPtr = &Disperser::get_disp_factor_k_threshold; return; } // test if there is a change between 0 and 10 (populations may exceed // K...) double ten = generalLogisticCurve(10,_disp_factor[0],_disp_factor[1], _disp_factor[2],_disp_factor[3],_disp_factor[4]); double zero = generalLogisticCurve(0, _disp_factor[0],_disp_factor[1], _disp_factor[2],_disp_factor[3],_disp_factor[4]); if(abs(ten-zero)<1e-6) { // factor not influenced by pop density if(abs(ten-1)<1e-6) { // factor = 1 get_disp_factor_funcPtr = &Disperser::get_disp_factor_one; return; } if(abs(ten-_disp_factor[0])<1e-6) { // factor = min get_disp_factor_funcPtr = &Disperser::get_disp_factor_min; return; } if(abs(ten-_disp_factor[1])<1e-6) { // factor = max get_disp_factor_funcPtr = &Disperser::get_disp_factor_max; return; } } // use the full general logistic function get_disp_factor_funcPtr = &Disperser::get_disp_factor_k_logistic; } // ----------------------------------------------------------------------------- // Disperser::_get_lattice_dims // ----------------------------------------------------------------------------- /** get the dimensions of the 2D stepping stone matrix */ void Disperser::_get_lattice_dims() { if( _disp_type & DISP_MIGR ? _paramSet->isSet("dispersal_lattice_dims") : _paramSet->isSet("colonization_lattice_dims") ) { TMatrix* m = (_disp_type & DISP_MIGR ? _paramSet->getMatrix("dispersal_lattice_dims") : _paramSet->getMatrix("colonization_lattice_dims")); // check if the dimensions of the matrix are correct if(m->get_dims(NULL) != 2) { fatal(_disp_type & DISP_MIGR ? "The parameter dispersal_lattice_dims should have a " "matrix with two values!\n" : "The parameter colonization_lattice_dims should have a " "matrix with two values!\n"); } // get the dimension of the lattice _lattice_dims[0] = (unsigned int)m->get(0,0); _lattice_dims[1] = (unsigned int)m->get(0,1); if(_lattice_dims[0]*_lattice_dims[1] != _nb_patch) { if( _disp_type & DISP_MIGR ) { fatal("Parameter dispersal_lattice_dims: The dimension of the " "lattice (%ix%i) does not mach the number of patches " "(%i)!\n", _lattice_dims[0], _lattice_dims[1], _nb_patch); } else { fatal("Parameter colonization_lattice_dims: The dimension of " "the lattice (%ix%i) does not mach the number of " "patches (%i)!\n", _lattice_dims[0], _lattice_dims[1], _nb_patch); } } } else { // if the dimensions are not set, we assume that x=y _lattice_dims[0] = _lattice_dims[1] = (unsigned int) sqrt((double)_nb_patch); if(_lattice_dims[0]*_lattice_dims[1] != _nb_patch) { if( _disp_type & DISP_MIGR ) { fatal("Parameter dispersal_lattice_dims: The dimension of the " "lattice (%ix%i) does not mach the number of patches " "(%i)!\n", _lattice_dims[0], _lattice_dims[1], _nb_patch); } else { fatal("Parameter colonization_lattice_dims: The dimension of " "the lattice (%ix%i) does not mach the number of " "patches (%i)!\n", _lattice_dims[0], _lattice_dims[1], _nb_patch); } } } // check if it is realy a 2D and not a 1D lattice if(_lattice_dims[0] == 1 || _lattice_dims[1]==1) { _disp_model = 2; // use a 1D stepping stone model } } // ----------------------------------------------------------------------------- // Disperser::setDispersalMatrix // ----------------------------------------------------------------------------- /** dispersal is set by a dispersal matrix * sex specific matrixes have precendence * if only one sex specific matrix is set, an error is drawn */ void Disperser::setDispersalMatrix() { // set the dispersal matrix if(_paramSet->isSet(_disp_type & DISP_MIGR ? "dispersal_rate_fem" : "colonization_rate_fem")) { if(_paramSet->isSet(_disp_type & DISP_MIGR ? "dispersal_rate_fem" : "colonization_rate_fem") && _paramSet->isSet(_disp_type & DISP_MIGR ? "dispersal_rate_mal" : "colonization_rate_mal")) { setDispMatrix(FEM, _paramSet->getMatrix(_disp_type & DISP_MIGR ? "dispersal_rate_fem" : "colonization_rate_fem")); setDispMatrix(MAL, _paramSet->getMatrix(_disp_type & DISP_MIGR ? "dispersal_rate_mal" : "colonization_rate_mal")); } else { fatal(_disp_type & DISP_MIGR ? "Only one sex specific migration matrix is specified: " "both are required!\n" : "Only one sex specific colonization matrix is specified: " "both are required!\n"); } } else { // general dispersal matrix setDispMatrix(_paramSet->getMatrix(_disp_type & DISP_MIGR ? "dispersal_rate" : "colonization_rate")); } // function pointer to the dispersal function doDispersal = &Disperser::dispersal_matrix; } // ----------------------------------------------------------------------------- // Disperser::setDispersalRate // ----------------------------------------------------------------------------- /** dispersal is set by a dispersal rate * sex specific rates have precendence * if only one sex specific rate is set, an error is drawn */ void Disperser::setDispersalRate() { if(_paramSet->isSet(_disp_type & DISP_MIGR ? "dispersal_rate_fem" : "colonization_rate_fem")) { if(_paramSet->isSet(_disp_type & DISP_MIGR ? "dispersal_rate_fem" : "colonization_rate_fem") && _paramSet->isSet(_disp_type & DISP_MIGR ? "dispersal_rate_mal" : "colonization_rate_mal")) { _migr_rate[FEM] = _paramSet->getValue(_disp_type & DISP_MIGR ? "dispersal_rate_fem" : "colonization_rate_fem"); _migr_rate[MAL] = _paramSet->getValue(_disp_type & DISP_MIGR ? "dispersal_rate_mal" : "colonization_rate_mal"); } else { fatal(_disp_type & DISP_MIGR ? "Only one sex specific migration rate is specified: " "both are required!\n" : "Only one sex specific colonization rate is specified: " "both are required!\n"); } } else { // general dispersal rate _migr_rate[FEM] = _migr_rate[MAL] = _paramSet->getValue(_disp_type & DISP_MIGR ? "dispersal_rate": "colonization_rate"); } // if there is no migration if(!_migr_rate[MAL] && !_migr_rate[FEM]) { doDispersal = &Disperser::disperse_zeroDispersal; return; } switch (_disp_model) { case 0: // island migration model _migr_rate[FEM] /= _nb_patch-1; _migr_rate[MAL] /= _nb_patch-1; doDispersal = &Disperser::disperse_island; break; case 1: // island migration model with propagule pool // if there are only two populations use the island simple model if(_nb_patch == 2) { _disp_model = 0; warning("With only 2 populations it is not possible to " "run a propagule dispersal model: the island " "model is used!\n"); return setDispersalRate(); } _migr_rate_propagule[FEM] = _migr_rate[FEM] * _disp_propagule_prob; _migr_rate_propagule[MAL] = _migr_rate[MAL] * _disp_propagule_prob; _migr_rate[FEM] *= (1.0-_disp_propagule_prob)/(_nb_patch-2); _migr_rate[MAL] *= (1.0-_disp_propagule_prob)/(_nb_patch-2); doDispersal = &Disperser::disperse_island_propagule; break; case 2: // 1D steppings stone model int factorIn, factorOut; doDispersal = &Disperser::disperse_1D_stepping_stone; // edge effect switch(_border_model) { default: case 0: // circle factorIn = 2; factorOut = 2; break; case 1: // reflecting factorIn = 1; factorOut = 0; break; case 2: // absorbing // negative number means removing individuals factorIn = 2; factorOut = -2; break; } _migr_rateIn[FEM] = _migr_rate[FEM]/factorIn; _migr_rateIn[MAL] = _migr_rate[MAL]/factorIn; _migr_rateOut[FEM] = factorOut ? _migr_rate[FEM]/factorOut : 0; _migr_rateOut[MAL] = factorOut ? _migr_rate[MAL]/factorOut : 0; _migr_rate[FEM] /= 2; _migr_rate[MAL] /= 2; break; case 3: // 2D stepping stone int factorIn4, factorOut4, factorInCorner4; int factorIn8, factorOut8, factorInCorner8; // edge effect switch(_border_model) { default: case 0: // torus factorIn4 = 4; factorIn8 = 8; factorOut4 = 4; factorOut8 = 8; factorInCorner4 = 4; factorInCorner8 = 8; break; case 1: // reflecting factorIn4 = 3; factorIn8 = 5; factorOut4 = 0; factorOut8 = 0; factorInCorner4 = 2; factorInCorner8 = 3; break; case 2: // absorbing factorIn4 = 4; factorIn8 = 8; // negative number means removing individuals factorOut4 = -4; factorOut8 = -8; factorInCorner4 = 4; factorInCorner8 = 8; break; } // number of neighbours if(_lattice_range==0) { // 4 neighbours doDispersal = &Disperser::disperse_2D_stepping_stone_4Neighbour; _migr_rateIn[FEM] = _migr_rate[FEM]/factorIn4; _migr_rateIn[MAL] = _migr_rate[MAL]/factorIn4; _migr_rateOut[FEM] = factorOut4 ? _migr_rate[FEM]/factorOut4 : 0; _migr_rateOut[MAL] = factorOut4 ? _migr_rate[MAL]/factorOut4 : 0; _migr_rateCorner[FEM] = _migr_rate[FEM]/factorInCorner4; _migr_rateCorner[MAL] = _migr_rate[MAL]/factorInCorner4; _migr_rate[FEM] /= 4; _migr_rate[MAL] /= 4; } else { // 8 neighbours doDispersal = &Disperser::disperse_2D_stepping_stone_8Neighbour; _migr_rateIn[FEM] = _migr_rate[FEM]/factorIn8; _migr_rateIn[MAL] = _migr_rate[MAL]/factorIn8; _migr_rateOut[FEM] = factorOut8 ? _migr_rate[FEM]/factorOut8 : 0; _migr_rateOut[MAL] = factorOut8 ? _migr_rate[MAL]/factorOut8 : 0; _migr_rateCorner[FEM] = _migr_rate[FEM]/factorInCorner8; _migr_rateCorner[MAL] = _migr_rate[MAL]/factorInCorner8; _migr_rate[FEM] /= 8; _migr_rate[MAL] /= 8; } break; default: fatal("\nDispersal model '%i' not available!\n",_disp_model); } }
[ [ [ 1, 1305 ] ] ]
e4dbe9cdf4ba5c424280b3472d9460dcc8b6ec06
cbb40e1d71bc4585ad3a58d32024090901487b76
/trunk/tokamaksrc/src/ne_interface.cpp
750cdfbf0e729435ac817222bb6cb54abefc128b
[]
no_license
huangleon/tokamak
c0dee7b8182ced6b514b37cf9c526934839c6c2e
0218e4d17dcf93b7ab476e3e8bd4026f390f82ca
refs/heads/master
2021-01-10T10:11:42.617076
2011-08-22T02:32:16
2011-08-22T02:32:16
50,816,154
0
0
null
null
null
null
UTF-8
C++
false
false
90,656
cpp
/************************************************************************* * * * Tokamak Physics Engine, Copyright (C) 2002-2007 David Lam. * * All rights reserved. Email: [email protected] * * Web: www.tokamakphysics.com * * * * 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 files * * LICENSE.TXT for more details. * * * *************************************************************************/ #include "math/ne_type.h" #include "math/ne_debug.h" #include "tokamak.h" #include "containers.h" #include "scenery.h" #include "collision.h" #include "constraint.h" #include "rigidbody.h" #ifdef _WIN32 #include <windows.h> #endif #include "stack.h" #include "simulator.h" #include "message.h" #include "stdio.h" namespace Tokamak { #define CAST_THIS(a, b) a& b = reinterpret_cast<a&>(*this); #ifdef TOKAMAK_COMPILE_DLL BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } #endif /**************************************************************************** * * neGeometry::SetBoxSize * ****************************************************************************/ void neGeometry::SetBoxSize(f32 width, f32 height, f32 depth) { CAST_THIS(TConvex, con); con.SetBoxSize(width, height, depth); } /**************************************************************************** * * neGeometry::SetBoxSize * ****************************************************************************/ void neGeometry::SetBoxSize(const neV3 & boxSize) { CAST_THIS(TConvex, con); con.SetBoxSize(boxSize[0], boxSize[1], boxSize[2]); } /**************************************************************************** * * neGeometry::SetCylinder * ****************************************************************************/ void neGeometry::SetCylinder(f32 diameter, f32 height) { CAST_THIS(TConvex, con); con.type = TConvex::CYLINDER; con.as.cylinder.radius = diameter * 0.5f; con.as.cylinder.radiusSq = con.as.cylinder.radius * con.as.cylinder.radius; con.as.cylinder.halfHeight = height * 0.5f; } /**************************************************************************** * * neGeometry::GetCylinder * ****************************************************************************/ neBool neGeometry::GetCylinder(f32 & diameter, f32 & height) // return false if geometry is not a cylinder { CAST_THIS(TConvex, con); if (con.type != TConvex::CYLINDER) return false; diameter = con.CylinderRadius() * 2.0f; height = con.CylinderHalfHeight() * 2.0f; return true; } /**************************************************************************** * * neGeometry::SetConvexMesh * ****************************************************************************/ void neGeometry::SetConvexMesh(neByte * convexData) { CAST_THIS(TConvex, con); con.SetConvexMesh(convexData); } /**************************************************************************** * * neGeometry::GetConvexMesh * ****************************************************************************/ neBool neGeometry::GetConvexMesh(neByte *& convexData) { CAST_THIS(TConvex, con); if (con.type != TConvex::CONVEXDCD) return false; convexData = con.as.convexDCD.convexData; return true; } /**************************************************************************** * * neGeometry::SetTransform * ****************************************************************************/ void neGeometry::SetTransform(neT3 & t) { CAST_THIS(TConvex, con); con.SetTransform(t); } /**************************************************************************** * * neGeometry::SetMaterialIndex * ****************************************************************************/ void neGeometry::SetMaterialIndex(s32 index) { CAST_THIS(TConvex, con); con.SetMaterialId(index); } /**************************************************************************** * * neGeometry::GetMaterialIndex * ****************************************************************************/ s32 neGeometry::GetMaterialIndex() { CAST_THIS(TConvex, con); return con.matIndex; } /**************************************************************************** * * neGeometry::GetTransform * ****************************************************************************/ neT3 neGeometry::GetTransform() { CAST_THIS(TConvex, con); return con.c2p; } /**************************************************************************** * * neGeometry::SetUserData * ****************************************************************************/ void neGeometry::SetUserData(u32 userData) { CAST_THIS(TConvex, con); con.userData = userData; } /**************************************************************************** * * neGeometry::GetUserData * ****************************************************************************/ u32 neGeometry::GetUserData() { CAST_THIS(TConvex, con); return con.userData; } /**************************************************************************** * * neGeometry::GetBoxSize * ****************************************************************************/ neBool neGeometry::GetBoxSize(neV3 & boxSize) // return false if geometry is not a box { CAST_THIS(TConvex, con); if (con.type != TConvex::BOX) return false; boxSize = con.as.box.boxSize * 2.0f; return true; } /**************************************************************************** * * neGeometry::SetSphereDiameter * ****************************************************************************/ void neGeometry::SetSphereDiameter(f32 diameter) { CAST_THIS(TConvex, con); con.type = TConvex::SPHERE; con.as.sphere.radius = diameter * 0.5f; con.as.sphere.radiusSq = con.as.sphere.radius * con.as.sphere.radius; } /**************************************************************************** * * neGeometry::GetSphereDiameter * ****************************************************************************/ neBool neGeometry::GetSphereDiameter(f32 & diameter) // return false if geometry is not a sphere { CAST_THIS(TConvex, con); if (con.type != TConvex::SPHERE) return false; diameter = con.Radius() * 2.0f; return true; } /**************************************************************************** * * neGeometry::SetBreakFlag * ****************************************************************************/ void neGeometry::SetBreakageFlag(neBreakFlag flag) { CAST_THIS(TConvex, con); con.breakInfo.flag = flag; } /**************************************************************************** * * neGeometry::GetBreakFlag * ****************************************************************************/ neGeometry::neBreakFlag neGeometry::GetBreakageFlag() { CAST_THIS(TConvex, con); return con.breakInfo.flag; } /**************************************************************************** * * neGeometry::SetBreakageMass * ****************************************************************************/ void neGeometry::SetBreakageMass(f32 mass) { CAST_THIS(TConvex, con); con.breakInfo.mass = mass; } /**************************************************************************** * * neGeometry::GetBreakageMass * ****************************************************************************/ f32 neGeometry::GetBreakageMass() { CAST_THIS(TConvex, con); return con.breakInfo.mass; } /**************************************************************************** * * neGeometry::SetBreakageInertiaTensor * ****************************************************************************/ void neGeometry::SetBreakageInertiaTensor(const neV3 & tensor) { CAST_THIS(TConvex, con); con.breakInfo.inertiaTensor = tensor; } /**************************************************************************** * * neGeometry::GetBreakageInertiaTensor * ****************************************************************************/ neV3 neGeometry::GetBreakageInertiaTensor() { CAST_THIS(TConvex, con); return con.breakInfo.inertiaTensor; } /**************************************************************************** * * neGeometry::SetBreakageMagnitude * ****************************************************************************/ void neGeometry::SetBreakageMagnitude(f32 mag) { CAST_THIS(TConvex, con); con.breakInfo.breakMagnitude = mag; } /**************************************************************************** * * neGeometry::GetBreakageMagnitude * ****************************************************************************/ f32 neGeometry::GetBreakageMagnitude() { CAST_THIS(TConvex, con); return con.breakInfo.breakMagnitude; } /**************************************************************************** * * neGeometry::SetBreakageAbsorption * ****************************************************************************/ void neGeometry::SetBreakageAbsorption(f32 absorb) { CAST_THIS(TConvex, con); con.breakInfo.breakAbsorb = absorb; } void neGeometry::SetBreakagePlane(const neV3 & planeNormal) { CAST_THIS(TConvex, con); con.breakInfo.breakPlane = planeNormal; } neV3 neGeometry::GetBreakagePlane() { CAST_THIS(TConvex, con); return con.breakInfo.breakPlane; } /**************************************************************************** * * neGeometry::GetBreakageAbsorption * ****************************************************************************/ f32 neGeometry::GetBreakageAbsorption() { CAST_THIS(TConvex, con); return con.breakInfo.breakAbsorb; } /**************************************************************************** * * neGeometry::SetBreakNeighbourRadius * ****************************************************************************/ void neGeometry::SetBreakageNeighbourRadius(f32 radius) { CAST_THIS(TConvex, con); con.breakInfo.neighbourRadius = radius; } /**************************************************************************** * * neGeometry::GetBreakNeighbourRadius * ****************************************************************************/ f32 neGeometry::GetBreakageNeighbourRadius() { CAST_THIS(TConvex, con); return con.breakInfo.neighbourRadius; } /**************************************************************************** * * neAnimatedBody::GetPos * ****************************************************************************/ neV3 neAnimatedBody::GetPos() { CAST_THIS(neCollisionBody_, cb); return cb.b2w.pos; } /**************************************************************************** * * neAnimatedBody::SetPos * ****************************************************************************/ void neAnimatedBody::SetPos(const neV3 & p) { CAST_THIS(neCollisionBody_, cb); cb.b2w.pos = p; cb.UpdateAABB(); cb.moved = true; } /**************************************************************************** * * neAnimatedBody::GetRotationM3 * ****************************************************************************/ neM3 neAnimatedBody::GetRotationM3() { CAST_THIS(neCollisionBody_, cb); return cb.b2w.rot; } /**************************************************************************** * * neAnimatedBody::GetRotationQ * ****************************************************************************/ neQ neAnimatedBody::GetRotationQ() { CAST_THIS(neCollisionBody_, cb); neQ q; q.SetupFromMatrix3(cb.b2w.rot); return q; } /**************************************************************************** * * neAnimatedBody::SetRotation * ****************************************************************************/ void neAnimatedBody::SetRotation(const neM3 & m) { CAST_THIS(neCollisionBody_, cb); cb.b2w.rot = m; cb.moved = true; } /**************************************************************************** * * neAnimatedBody::SetRotation * ****************************************************************************/ void neAnimatedBody::SetRotation(const neQ & q) { CAST_THIS(neCollisionBody_, cb); cb.b2w.rot = q.BuildMatrix3(); cb.moved = true; } /**************************************************************************** * * neAnimatedBody::GetTransform * ****************************************************************************/ neT3 neAnimatedBody::GetTransform() { CAST_THIS(neCollisionBody_, cb); return cb.b2w; } /**************************************************************************** * * neAnimatedBody::SetCollisionID * ****************************************************************************/ void neAnimatedBody::SetCollisionID(s32 cid) { CAST_THIS(neCollisionBody_, cb); cb.cid = cid; } /**************************************************************************** * * neAnimatedBody::GetCollisionID * ****************************************************************************/ s32 neAnimatedBody::GetCollisionID() { CAST_THIS(neCollisionBody_, cb); return cb.cid; } /**************************************************************************** * * neAnimatedBody::SetUserData * ****************************************************************************/ void neAnimatedBody::SetUserData(u32 cookies) { CAST_THIS(neCollisionBody_, cb); cb.cookies = cookies; } /**************************************************************************** * * neAnimatedBody::GetUserData * ****************************************************************************/ u32 neAnimatedBody::GetUserData() { CAST_THIS(neCollisionBody_, cb); return cb.cookies; } /**************************************************************************** * * neAnimatedBody::GetGeometryCount * ****************************************************************************/ s32 neAnimatedBody::GetGeometryCount() { CAST_THIS(neCollisionBody_, cb); return cb.col.convexCount; } /**************************************************************************** * * neAnimatedBody::GetGeometry * ****************************************************************************/ /* neGeometry * neAnimatedBody::GetGeometry(s32 index) { CAST_THIS(neCollisionBody_, cb); return reinterpret_cast<neGeometry*>(cb.GetConvex(index)); } */ /**************************************************************************** * * neAnimatedBody::SetGeometry * ****************************************************************************/ /* void neAnimatedBody::SetGeometry(s32 geometryCount, neGeometry * geometryArray) { CAST_THIS(neCollisionBody_, cb); //todo } */ /**************************************************************************** * * neAnimatedBody::UpdateBoundingInfo * ****************************************************************************/ void neAnimatedBody::UpdateBoundingInfo() { CAST_THIS(neRigidBodyBase, rb); rb.RecalcBB(); } /**************************************************************************** * * neAnimatedBody::CollideConnected * ****************************************************************************/ void neAnimatedBody::CollideConnected(neBool yes) { CAST_THIS(neRigidBodyBase, rb); rb.CollideConnected(yes); } /**************************************************************************** * * neAnimatedBody::IsCollideConnected * ****************************************************************************/ neBool neAnimatedBody::CollideConnected() { CAST_THIS(neRigidBodyBase, rb); return rb.CollideConnected(); } /**************************************************************************** * * neAnimatedBody::CollideDirectlyConnected * ****************************************************************************/ void neAnimatedBody::CollideDirectlyConnected(neBool yes) { CAST_THIS(neRigidBodyBase, rb); rb.isCollideDirectlyConnected = yes; } /**************************************************************************** * * neAnimatedBody::CollideDirectlyConnected * ****************************************************************************/ neBool neAnimatedBody::CollideDirectlyConnected() { CAST_THIS(neRigidBodyBase, rb); return rb.isCollideDirectlyConnected; } /**************************************************************************** * * neAnimatedBody::AddGeometry * ****************************************************************************/ neGeometry * neAnimatedBody::AddGeometry() { CAST_THIS(neCollisionBody_, ab); TConvex * g = ab.AddGeometry(); return reinterpret_cast<neGeometry *>(g); } /**************************************************************************** * * neAnimatedBody::RemoveGeometry * ****************************************************************************/ neBool neAnimatedBody::RemoveGeometry(neGeometry * g) { CAST_THIS(neCollisionBody_, ab); if (!ab.col.convex) return false; TConvexItem * gi = (TConvexItem *)ab.col.convex; while (gi) { TConvex * convex = reinterpret_cast<TConvex *>(gi); gi = gi->next; if (convex == reinterpret_cast<TConvex *>(g)) { if (ab.col.convex == convex) { ab.col.convex = (TConvex*)gi; } ab.sim->geometryHeap.Dealloc(convex, 1); ab.col.convexCount--; if (ab.col.convexCount == 0) { ab.col.convex = NULL; if (ab.IsInRegion() && !ab.isCustomCD) ab.sim->region.RemoveBody(&ab); } return true; } } return false; } /**************************************************************************** * * neAnimatedBody::BeginIterateGeometry * ****************************************************************************/ void neAnimatedBody::BeginIterateGeometry() { CAST_THIS(neCollisionBody_, ab); ab.BeginIterateGeometry(); } /**************************************************************************** * * neAnimatedBody::GetNextGeometry * ****************************************************************************/ neGeometry * neAnimatedBody::GetNextGeometry() { CAST_THIS(neCollisionBody_, ab); return reinterpret_cast<neGeometry *>(ab.GetNextGeometry()); } /**************************************************************************** * * neAnimatedBody::BreakGeometry * ****************************************************************************/ neRigidBody * neAnimatedBody::BreakGeometry(neGeometry * g) { CAST_THIS(neCollisionBody_, ab); neRigidBody_ * newBody = ab.sim->CreateRigidBodyFromConvex((TConvex*)g, &ab); return (neRigidBody *)newBody; } /**************************************************************************** * * neAnimatedBody::UseCustomCollisionDetection * ****************************************************************************/ void neAnimatedBody::UseCustomCollisionDetection(neBool yes, const neT3 * obb, f32 boundingRadius) { CAST_THIS(neCollisionBody_, ab); if (yes) { ab.obb = *obb; ab.col.boundingRadius = boundingRadius; ab.isCustomCD = yes; if (ab.isActive && !ab.IsInRegion()) { ab.sim->region.AddBody(&ab, NULL); } } else { ab.isCustomCD = yes; this->UpdateBoundingInfo(); if (ab.IsInRegion() && GetGeometryCount() == 0) { ab.sim->region.RemoveBody(&ab); } } } /**************************************************************************** * * neAnimatedBody::UseCustomCollisionDetection * ****************************************************************************/ neBool neAnimatedBody::UseCustomCollisionDetection() { CAST_THIS(neCollisionBody_, ab); return ab.isCustomCD; } /**************************************************************************** * * neAnimatedBody::AddSensor * ****************************************************************************/ neSensor * neAnimatedBody::AddSensor() { CAST_THIS(neRigidBodyBase, ab); neSensor_ * s = ab.AddSensor(); return reinterpret_cast<neSensor *>(s); } /**************************************************************************** * * neAnimatedBody::RemoveSensor * ****************************************************************************/ neBool neAnimatedBody::RemoveSensor(neSensor * s) { CAST_THIS(neRigidBodyBase, ab); if (!ab.sensors) return false; neSensorItem * si = (neSensorItem *)ab.sensors; while (si) { neSensor_ * sensor = (neSensor_ *) si; si = si->next; if (sensor == reinterpret_cast<neSensor_*>(s)) { //reinterpret_cast<neSensorItem *>(s)->Remove(); ab.sim->sensorHeap.Dealloc(sensor, 1); return true; } } return false; } /**************************************************************************** * * neAnimatedBody::BeginIterateSensor * ****************************************************************************/ void neAnimatedBody::BeginIterateSensor() { CAST_THIS(neRigidBodyBase, ab); ab.BeginIterateSensor(); } /**************************************************************************** * * neAnimatedBody::GetNextSensor * ****************************************************************************/ neSensor * neAnimatedBody::GetNextSensor() { CAST_THIS(neRigidBodyBase, ab); return reinterpret_cast<neSensor *>(ab.GetNextSensor()); } /**************************************************************************** * * neAnimatedBody::Active * ****************************************************************************/ void neAnimatedBody::Active(neBool yes, neRigidBody * hint) { CAST_THIS(neRigidBodyBase, ab); ab.Active(yes, (neRigidBodyBase *)hint); } /**************************************************************************** * * neAnimatedBody::Active * ****************************************************************************/ void neAnimatedBody::Active(neBool yes, neAnimatedBody * hint) { CAST_THIS(neRigidBodyBase, ab); ab.Active(yes, (neRigidBodyBase *)hint); } /**************************************************************************** * * neAnimatedBody::IsActive * ****************************************************************************/ neBool neAnimatedBody::Active() { CAST_THIS(neRigidBodyBase, ab); return ab.isActive; } /**************************************************************************** * * neRigidBody::GetMass * ****************************************************************************/ f32 neRigidBody::GetMass() { CAST_THIS(neRigidBody_, rb); return rb.mass; } /**************************************************************************** * * neRigidBody::SetMass * ****************************************************************************/ void neRigidBody::SetMass(f32 mass) { CAST_THIS(neRigidBody_, rb); ASSERT(neIsFinite(mass)); rb.mass = mass; rb.oneOnMass = 1.0f / mass; } /**************************************************************************** * * neRigidBody::SetInertiaTensor * ****************************************************************************/ void neRigidBody::SetInertiaTensor(const neM3 & tensor) { CAST_THIS(neRigidBody_, rb); rb.Ibody = tensor; rb.IbodyInv.SetInvert(tensor); //ASSERT(tensor.Invert(rb.IbodyInv)); } /**************************************************************************** * * neRigidBody::SetInertiaTensor * ****************************************************************************/ void neRigidBody::SetInertiaTensor(const neV3 & tensor) { CAST_THIS(neRigidBody_, rb); neM3 i; i.SetIdentity(); i[0][0] = tensor[0]; i[1][1] = tensor[1]; i[2][2] = tensor[2]; rb.Ibody = i; rb.IbodyInv.SetInvert(rb.Ibody); } /**************************************************************************** * * neRigidBody::SetCollisionID * ****************************************************************************/ void neRigidBody::SetCollisionID(s32 cid) { CAST_THIS(neRigidBodyBase, rb); rb.cid = cid; } /**************************************************************************** * * neRigidBody::GetCollisionID * ****************************************************************************/ s32 neRigidBody::GetCollisionID() { CAST_THIS(neRigidBodyBase, rb); return rb.cid; } /**************************************************************************** * * neRigidBody::SetUserData * ****************************************************************************/ void neRigidBody::SetUserData(u32 cookies) { CAST_THIS(neRigidBodyBase, rb); rb.cookies = cookies; } /**************************************************************************** * * neRigidBody::GetUserData * ****************************************************************************/ u32 neRigidBody::GetUserData() { CAST_THIS(neRigidBodyBase, rb); return rb.cookies; } /**************************************************************************** * * neRigidBody::GetGeometryCount * ****************************************************************************/ s32 neRigidBody::GetGeometryCount() { CAST_THIS(neRigidBodyBase, rb); return rb.col.convexCount; } void neRigidBody::SetLinearDamping(f32 damp) { CAST_THIS(neRigidBody_, rb); rb.linearDamp = neAbs(damp); } f32 neRigidBody::GetLinearDamping() { CAST_THIS(neRigidBody_, rb); return rb.linearDamp; } void neRigidBody::SetAngularDamping(f32 damp) { CAST_THIS(neRigidBody_, rb); rb.angularDamp = neAbs(damp); } f32 neRigidBody::GetAngularDamping() { CAST_THIS(neRigidBody_, rb); return rb.angularDamp; } void neRigidBody::SetSleepingParameter(f32 sleepingParam) { CAST_THIS(neRigidBody_, rb); rb.sleepingParam = sleepingParam; } f32 neRigidBody::GetSleepingParameter() { CAST_THIS(neRigidBody_, rb); return rb.sleepingParam; } /**************************************************************************** * * neRigidBody::GetGeometry * ****************************************************************************/ /* neGeometry * neRigidBody::GetGeometry(s32 index) { CAST_THIS(neRigidBodyBase, rb); return reinterpret_cast<neGeometry*>(rb.GetConvex(index)); } */ /**************************************************************************** * * neRigidBody::SetGeometry * ****************************************************************************/ /* void neRigidBody::SetGeometry(s32 geometryCount, neGeometry * geometryArray) { //todo } */ /**************************************************************************** * * neRigidBody::GetPos * ****************************************************************************/ neV3 neRigidBody::GetPos() { CAST_THIS(neRigidBody_, rb); return rb.GetPos(); } /**************************************************************************** * * neRigidBody::SetPos * ****************************************************************************/ void neRigidBody::SetPos(const neV3 & p) { CAST_THIS(neRigidBody_, rb); rb.SetPos(p); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::GetRotationM3 * ****************************************************************************/ neM3 neRigidBody::GetRotationM3() { CAST_THIS(neRigidBody_, rb); return rb.State().rot(); } /**************************************************************************** * * neRigidBody::GetRotationQ * ****************************************************************************/ neQ neRigidBody::GetRotationQ() { CAST_THIS(neRigidBody_, rb); return rb.State().q; } /**************************************************************************** * * neRigidBody::SetRotation * ****************************************************************************/ void neRigidBody::SetRotation(const neM3 & m) { ASSERT(m.IsOrthogonalNormal()); CAST_THIS(neRigidBody_, rb); rb.State().rot() = m; rb.State().q.SetupFromMatrix3(m); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::SetRotation * ****************************************************************************/ void neRigidBody::SetRotation(const neQ & q) { CAST_THIS(neRigidBody_, rb); rb.State().q = q; rb.State().rot() = q.BuildMatrix3(); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::GetTransform * ****************************************************************************/ neT3 neRigidBody::GetTransform() { CAST_THIS(neRigidBody_, rb); rb.State().b2w.rot[0].v[3] = 0.0f; rb.State().b2w.rot[1].v[3] = 0.0f; rb.State().b2w.rot[2].v[3] = 0.0f; rb.State().b2w.pos.v[3] = 1.0f; return rb.State().b2w; } /**************************************************************************** * * neRigidBody::GetVelocity * ****************************************************************************/ neV3 neRigidBody::GetVelocity() { CAST_THIS(neRigidBody_, rb); return rb.Derive().linearVel; } /**************************************************************************** * * neRigidBody::SetVelocity * ****************************************************************************/ void neRigidBody::SetVelocity(const neV3 & v) { CAST_THIS(neRigidBody_, rb); rb.Derive().linearVel = v; rb.WakeUpAllJoint(); } /**************************************************************************** * * neRigidBody::GetAngularVelocity * ****************************************************************************/ neV3 neRigidBody::GetAngularVelocity() { CAST_THIS(neRigidBody_, rb); return rb.Derive().angularVel; } /**************************************************************************** * * neRigidBody::GetAngularMomentum * ****************************************************************************/ neV3 neRigidBody::GetAngularMomentum() { CAST_THIS(neRigidBody_, rb); return rb.State().angularMom; } /**************************************************************************** * * neRigidBody::SetAngularMomemtum * ****************************************************************************/ void neRigidBody::SetAngularMomentum(const neV3& am) { CAST_THIS(neRigidBody_, rb); rb.SetAngMom(am); rb.WakeUpAllJoint(); } /**************************************************************************** * * neRigidBody::GetVelocityAtPoint * ****************************************************************************/ neV3 neRigidBody::GetVelocityAtPoint(const neV3 & pt) { CAST_THIS(neRigidBody_, rb); return rb.VelocityAtPoint(pt); } /**************************************************************************** * * neRigidBody::UpdateBoundingInfo * ****************************************************************************/ void neRigidBody::UpdateBoundingInfo() { CAST_THIS(neRigidBodyBase, rb); rb.RecalcBB(); } /**************************************************************************** * * neRigidBody::UpdateInertiaTensor * ****************************************************************************/ void neRigidBody::UpdateInertiaTensor() { CAST_THIS(neRigidBody_, rb); rb.RecalcInertiaTensor(); } /**************************************************************************** * * neRigidBody::SetForce * ****************************************************************************/ void neRigidBody::SetForce(const neV3 & force, const neV3 & pos) { CAST_THIS(neRigidBody_, rb); if (force.IsConsiderZero()) { rb.force = force; rb.torque = ((pos - rb.GetPos()).Cross(force)); return; } rb.force = force; rb.torque = ((pos - rb.GetPos()).Cross(force)); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::SetForce * ****************************************************************************/ void neRigidBody::SetTorque(const neV3 & torque) { CAST_THIS(neRigidBody_, rb); if (torque.IsConsiderZero()) { rb.torque = torque; return; } rb.torque = torque; rb.WakeUp(); } /**************************************************************************** * * neRigidBody::ApplyForceCOG * ****************************************************************************/ void neRigidBody::SetForce(const neV3 & force) { CAST_THIS(neRigidBody_, rb); if (force.IsConsiderZero()) { rb.force = force; return; } rb.force = force; rb.WakeUp(); } neV3 neRigidBody::GetForce() { CAST_THIS(neRigidBody_, rb); return rb.force; } neV3 neRigidBody::GetTorque() { CAST_THIS(neRigidBody_, rb); return rb.torque; } /**************************************************************************** * * neRigidBody::AddImpulse * ****************************************************************************/ void neRigidBody::ApplyImpulse(const neV3 & impulse) { CAST_THIS(neRigidBody_, rb); neV3 dv = impulse * rb.oneOnMass; rb.Derive().linearVel += dv; //rb.WakeUp(); rb.WakeUpAllJoint(); } /**************************************************************************** * * neRigidBody::AddImpulseWithTwist * ****************************************************************************/ void neRigidBody::ApplyImpulse(const neV3 & impulse, const neV3 & pos) { CAST_THIS(neRigidBody_, rb); neV3 dv = impulse * rb.oneOnMass; neV3 da = (pos - rb.GetPos()).Cross(impulse); rb.Derive().linearVel += dv; neV3 newAM = rb.State().angularMom + da; rb.SetAngMom(newAM); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::ApplyTwist * ****************************************************************************/ void neRigidBody::ApplyTwist(const neV3 & twist) { CAST_THIS(neRigidBody_, rb); neV3 newAM = twist; rb.SetAngMom(newAM); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::AddController * ****************************************************************************/ neRigidBodyController * neRigidBody::AddController(neRigidBodyControllerCallback * controller, s32 period) { CAST_THIS(neRigidBody_, rb); return (neRigidBodyController *)rb.AddController(controller, period); } /**************************************************************************** * * neRigidBody::RemoveController * ****************************************************************************/ neBool neRigidBody::RemoveController(neRigidBodyController * rbController) { CAST_THIS(neRigidBody_, rb); if (!rb.controllers) return false; neControllerItem * ci = (neControllerItem *)rb.controllers; while (ci) { neController * con = reinterpret_cast<neController *>(ci); ci = ci->next; if (con == reinterpret_cast<neController *>(rbController)) { //reinterpret_cast<neControllerItem *>(con)->Remove(); rb.sim->controllerHeap.Dealloc(con, 1); return true; } } return false; } /**************************************************************************** * * neRigidBody::BeginIterateController * ****************************************************************************/ void neRigidBody::BeginIterateController() { CAST_THIS(neRigidBody_, rb); rb.BeginIterateController(); } /**************************************************************************** * * neRigidBody::GetNextController * ****************************************************************************/ neRigidBodyController * neRigidBody::GetNextController() { CAST_THIS(neRigidBody_, rb); return (neRigidBodyController *)rb.GetNextController(); } /**************************************************************************** * * neRigidBody::GravityEnable * ****************************************************************************/ void neRigidBody::GravityEnable(neBool yes) { CAST_THIS(neRigidBody_, rb); rb.GravityEnable(yes); } /**************************************************************************** * * neRigidBody::GravityEnable * ****************************************************************************/ neBool neRigidBody::GravityEnable() { CAST_THIS(neRigidBody_, rb); return rb.gravityOn; } /**************************************************************************** * * neRigidBody::CollideConnected * ****************************************************************************/ void neRigidBody::CollideConnected(neBool yes) { CAST_THIS(neRigidBody_, rb); rb.CollideConnected(yes); } /**************************************************************************** * * neRigidBody::CollideConnected * ****************************************************************************/ neBool neRigidBody::CollideConnected() { CAST_THIS(neRigidBody_, rb); return rb.CollideConnected(); } /**************************************************************************** * * neRigidBody::CollideDirectlyConnected * ****************************************************************************/ void neRigidBody::CollideDirectlyConnected(neBool yes) { CAST_THIS(neRigidBody_, rb); rb.isCollideDirectlyConnected = yes; } /**************************************************************************** * * neRigidBody::CollideConnected * ****************************************************************************/ neBool neRigidBody::CollideDirectlyConnected() { CAST_THIS(neRigidBody_, rb); return rb.isCollideDirectlyConnected; } /**************************************************************************** * * neRigidBody::AddGeometry * ****************************************************************************/ neGeometry * neRigidBody::AddGeometry() { CAST_THIS(neRigidBody_, rb); TConvex * g = rb.AddGeometry(); return reinterpret_cast<neGeometry *>(g); } /**************************************************************************** * * neRigidBody::RemoveGeometry * ****************************************************************************/ neBool neRigidBody::RemoveGeometry(neGeometry * g) { CAST_THIS(neRigidBody_, rb); if (!rb.col.convex) return false; TConvexItem * gi = (TConvexItem *)rb.col.convex; while (gi) { TConvex * convex = reinterpret_cast<TConvex *>(gi); gi = gi->next; if (convex == reinterpret_cast<TConvex *>(g)) { if (rb.col.convex == convex) { rb.col.convex = (TConvex*)gi; } rb.sim->geometryHeap.Dealloc(convex, 1); rb.col.convexCount--; if (rb.col.convexCount == 0) { rb.col.convex = NULL; if (rb.IsInRegion() && !rb.isCustomCD) rb.sim->region.RemoveBody(&rb); } return true; } } return false; } /**************************************************************************** * * neRigidBody::BeginIterateGeometry * ****************************************************************************/ void neRigidBody::BeginIterateGeometry() { CAST_THIS(neRigidBody_, rb); rb.BeginIterateGeometry(); } /**************************************************************************** * * neRigidBody::GetNextGeometry * ****************************************************************************/ neGeometry * neRigidBody::GetNextGeometry() { CAST_THIS(neRigidBody_, rb); return reinterpret_cast<neGeometry *>(rb.GetNextGeometry()); } /**************************************************************************** * * neRigidBody::BreakGeometry * ****************************************************************************/ neRigidBody * neRigidBody::BreakGeometry(neGeometry * g) { CAST_THIS(neRigidBody_, rb); neRigidBody_ * newBody = rb.sim->CreateRigidBodyFromConvex((TConvex*)g, &rb); return (neRigidBody *)newBody; } /**************************************************************************** * * neRigidBody::UseCustomCollisionDetection * ****************************************************************************/ void neRigidBody::UseCustomCollisionDetection(neBool yes, const neT3 * obb, f32 boundingRadius) { CAST_THIS(neRigidBody_, rb); if (yes) { rb.obb = *obb; rb.col.boundingRadius = boundingRadius; rb.isCustomCD = yes; if (rb.isActive && !rb.IsInRegion()) { rb.sim->region.AddBody(&rb, NULL); } } else { rb.isCustomCD = yes; this->UpdateBoundingInfo(); if (rb.IsInRegion() && GetGeometryCount() == 0) { rb.sim->region.RemoveBody(&rb); } } } /**************************************************************************** * * neRigidBody::UseCustomCollisionDetection * ****************************************************************************/ neBool neRigidBody::UseCustomCollisionDetection() { CAST_THIS(neRigidBody_, rb); return rb.isCustomCD; } /**************************************************************************** * * neRigidBody::AddSensor * ****************************************************************************/ neSensor * neRigidBody::AddSensor() { CAST_THIS(neRigidBody_, rb); neSensor_ * s = rb.AddSensor(); return reinterpret_cast<neSensor *>(s); } /**************************************************************************** * * neRigidBody::RemoveSensor * ****************************************************************************/ neBool neRigidBody::RemoveSensor(neSensor * s) { CAST_THIS(neRigidBody_, rb); if (!rb.sensors) return false; neSensorItem * si = (neSensorItem *)rb.sensors; while (si) { neSensor_ * sensor = reinterpret_cast<neSensor_ *>(si); si = si->next; if (sensor == reinterpret_cast<neSensor_ *>(s)) { //reinterpret_cast<neSensorItem *>(s)->Remove(); rb.sim->sensorHeap.Dealloc(sensor, 1); return true; } } return false; } /**************************************************************************** * * neRigidBody::BeginIterateSensor * ****************************************************************************/ void neRigidBody::BeginIterateSensor() { CAST_THIS(neRigidBody_, rb); rb.BeginIterateSensor(); } /**************************************************************************** * * neRigidBody::GetNextSensor * ****************************************************************************/ neSensor * neRigidBody::GetNextSensor() { CAST_THIS(neRigidBody_, rb); return reinterpret_cast<neSensor *>(rb.GetNextSensor()); } /**************************************************************************** * * neRigidBody::Active * ****************************************************************************/ void neRigidBody::Active(neBool yes, neRigidBody * hint) { CAST_THIS(neRigidBodyBase, ab); ab.Active(yes, (neRigidBodyBase *)hint); } /**************************************************************************** * * neRigidBody::Active * ****************************************************************************/ void neRigidBody::Active(neBool yes, neAnimatedBody * hint) { CAST_THIS(neRigidBodyBase, ab); ab.Active(yes, (neRigidBodyBase *)hint); } /**************************************************************************** * * neAnimatedBody::IsActive * ****************************************************************************/ neBool neRigidBody::Active() { CAST_THIS(neRigidBodyBase, ab); return ab.isActive; } neBool neRigidBody::IsIdle() { CAST_THIS(neRigidBody_, rb); return (rb.status == neRigidBody_::NE_RBSTATUS_IDLE); } /**************************************************************************** * * neSimulator::CreateSimulator * ****************************************************************************/ neSimulator * neSimulator::CreateSimulator(const neSimulatorSizeInfo & sizeInfo, neAllocatorAbstract * alloc, const neV3 * grav) { neFixedTimeStepSimulator * s = new neFixedTimeStepSimulator(sizeInfo, alloc, grav); return reinterpret_cast<neSimulator*>(s); } /**************************************************************************** * * neSimulator::DestroySimulator(neSimulator * sim); * ****************************************************************************/ void neSimulator::DestroySimulator(neSimulator * sim) { neFixedTimeStepSimulator * s = reinterpret_cast<neFixedTimeStepSimulator *>(sim); delete s; } /**************************************************************************** * * neSimulator::Gravity * ****************************************************************************/ neV3 neSimulator::Gravity() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.gravity; } /**************************************************************************** * * neSimulator::Gravity * ****************************************************************************/ void neSimulator::Gravity(const neV3 & g) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.SetGravity(g); /* sim.gravity = g; sim.gravityVector = g; sim.gravityVector.Normalize(); */ } /**************************************************************************** * * neSimulator::CreateRigidBody * ****************************************************************************/ neRigidBody * neSimulator::CreateRigidBody() { CAST_THIS(neFixedTimeStepSimulator, sim); neRigidBody_ * ret = sim.CreateRigidBody(); return reinterpret_cast<neRigidBody *>(ret); } /**************************************************************************** * * neSimulator::CreateRigidParticle * ****************************************************************************/ neRigidBody * neSimulator::CreateRigidParticle() { CAST_THIS(neFixedTimeStepSimulator, sim); neRigidBody_ * ret = sim.CreateRigidBody(true); return reinterpret_cast<neRigidBody *>(ret); } /**************************************************************************** * * neSimulator::CreateCollisionBody() * ****************************************************************************/ neAnimatedBody * neSimulator::CreateAnimatedBody() { CAST_THIS(neFixedTimeStepSimulator, sim); neCollisionBody_ * ret = sim.CreateCollisionBody(); return reinterpret_cast<neAnimatedBody *>(ret); } /**************************************************************************** * * neSimulator::FreeBody * ****************************************************************************/ void neSimulator::FreeRigidBody(neRigidBody * body) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.Free(reinterpret_cast<neRigidBody_*>(body)); } /**************************************************************************** * * neSimulator::FreeCollisionBody * ****************************************************************************/ void neSimulator::FreeAnimatedBody(neAnimatedBody * body) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.Free(reinterpret_cast<neRigidBody_*>(body)); } /**************************************************************************** * * neSimulator::GetCollisionTable * ****************************************************************************/ neCollisionTable * neSimulator::GetCollisionTable() { CAST_THIS(neFixedTimeStepSimulator, sim); return (neCollisionTable *)(&sim.colTable); } /**************************************************************************** * * neSimulator::GetMaterial * ****************************************************************************/ bool neSimulator::SetMaterial(s32 index, f32 friction, f32 restitution) { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.SetMaterial(index, friction, restitution, 0.0f); } /**************************************************************************** * * neSimulator::GetMaterial * ****************************************************************************/ bool neSimulator::GetMaterial(s32 index, f32& friction, f32& restitution) { CAST_THIS(neFixedTimeStepSimulator, sim); f32 density; return sim.GetMaterial(index, friction, restitution, density); } /**************************************************************************** * * neSimulator::Advance * ****************************************************************************/ void neSimulator::Advance(f32 sec, s32 step, nePerformanceReport * perfReport) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.Advance(sec, step, perfReport); } void neSimulator::Advance(f32 sec, f32 minTimeStep, f32 maxTimeStep, nePerformanceReport * perfReport) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.Advance(sec, minTimeStep, maxTimeStep, perfReport); } /**************************************************************************** * * neSimulator::SetTerrainMesh * ****************************************************************************/ void neSimulator::SetTerrainMesh(neTriangleMesh * tris) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.SetTerrainMesh(tris); } void neSimulator::FreeTerrainMesh() { CAST_THIS(neFixedTimeStepSimulator, sim); sim.FreeTerrainMesh(); } /**************************************************************************** * * neSimulator::CreateJoint * ****************************************************************************/ neJoint * neSimulator::CreateJoint(neRigidBody * bodyA) { CAST_THIS(neFixedTimeStepSimulator, sim); if (!bodyA) return NULL; _neConstraint * constr = sim.constraintHeap.Alloc(1); // 1 means make it solo if (!constr) { sprintf(sim.logBuffer, MSG_CONSTRAINT_FULL); sim.LogOutput(neSimulator::LOG_OUTPUT_LEVEL_ONE); return NULL; } constr->Reset(); constr->sim = &sim; constr->bodyA = (neRigidBody_*)bodyA; neRigidBody_ * ba = (neRigidBody_*)bodyA; ba->constraintCollection.Add(&constr->bodyAHandle); return reinterpret_cast<neJoint*>(constr); } /**************************************************************************** * * neSimulator::CreateJoint * ****************************************************************************/ neJoint * neSimulator::CreateJoint(neRigidBody * bodyA, neRigidBody * bodyB) { CAST_THIS(neFixedTimeStepSimulator, sim); if (!bodyA) return NULL; if (!bodyB) return NULL; _neConstraint * constr = sim.constraintHeap.Alloc(1); // 1 means make it solo if (!constr) { sprintf(sim.logBuffer, MSG_CONSTRAINT_FULL); sim.LogOutput(neSimulator::LOG_OUTPUT_LEVEL_ONE); return NULL; } constr->Reset(); constr->sim = &sim; constr->bodyA = (neRigidBody_*)bodyA; neRigidBody_ * ba = (neRigidBody_*)bodyA; ba->constraintCollection.Add(&constr->bodyAHandle); constr->bodyB = (neRigidBodyBase*)bodyB; neRigidBody_ * bb = (neRigidBody_*)bodyB; bb->constraintCollection.Add(&constr->bodyBHandle); return reinterpret_cast<neJoint*>(constr); } /**************************************************************************** * * neSimulator::CreateJoint * ****************************************************************************/ neJoint * neSimulator::CreateJoint(neRigidBody * bodyA, neAnimatedBody * bodyB) { CAST_THIS(neFixedTimeStepSimulator, sim); if (!bodyA) return NULL; if (!bodyB) return NULL; _neConstraint * constr = sim.constraintHeap.Alloc(1); // 1 means make it solo if (!constr) { sprintf(sim.logBuffer, MSG_CONSTRAINT_FULL); sim.LogOutput(neSimulator::LOG_OUTPUT_LEVEL_ONE); return NULL; } constr->Reset(); constr->sim = &sim; constr->bodyA = (neRigidBody_*)bodyA; neRigidBody_ * ba = (neRigidBody_*)bodyA; ba->constraintCollection.Add(&constr->bodyAHandle); constr->bodyB = (neRigidBodyBase*)bodyB; neRigidBodyBase * bb = (neRigidBodyBase*)bodyB; bb->constraintCollection.Add(&constr->bodyBHandle); return reinterpret_cast<neJoint*>(constr); } /**************************************************************************** * * neSimulator::FreeJoint * ****************************************************************************/ void neSimulator::FreeJoint(neJoint * constraint) { CAST_THIS(neFixedTimeStepSimulator, sim); _neConstraint * c = (_neConstraint *)constraint; ASSERT(sim.constraintHeap.CheckBelongAndInUse(c)); if (c->bodyA) { c->bodyA->constraintCollection.Remove(&c->bodyAHandle); if (c->bodyB) c->bodyB->constraintCollection.Remove(&c->bodyBHandle); neConstraintHeader * h = c->bodyA->GetConstraintHeader(); if (h) { h->Remove(c); h->flag = neConstraintHeader::FLAG_NEED_REORG; } sim.constraintHeap.Dealloc(c, 1); if (c->bodyA->constraintCollection.count == 0) c->bodyA->RemoveConstraintHeader(); if (c->bodyB && c->bodyB->constraintCollection.count == 0) c->bodyB->RemoveConstraintHeader(); } else { sim.constraintHeap.Dealloc(c, 1); } } /**************************************************************************** * * neSimulator::SetCollisionCallback * ****************************************************************************/ void neSimulator::SetCollisionCallback(neCollisionCallback * fn) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.SetCollisionCallback(fn); } /**************************************************************************** * * neSimulator::GetCollisionCallback * ****************************************************************************/ neCollisionCallback * neSimulator::GetCollisionCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.collisionCallback; } /**************************************************************************** * * neSimulator::SetBreakageCallback * ****************************************************************************/ void neSimulator::SetBreakageCallback(neBreakageCallback * cb) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.breakageCallback = cb; } /**************************************************************************** * * neSimulator::GetBreakageCallback * ****************************************************************************/ neBreakageCallback * neSimulator::GetBreakageCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.breakageCallback; } /**************************************************************************** * * neSimulator::SetTerrainTriangleQueryCallback * ****************************************************************************/ void neSimulator::SetTerrainTriangleQueryCallback(neTerrainTriangleQueryCallback * cb) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.terrainQueryCallback = cb; } /**************************************************************************** * * neSimulator::GetTerrainTriangleQueryCallback * ****************************************************************************/ neTerrainTriangleQueryCallback * neSimulator::GetTerrainTriangleQueryCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.terrainQueryCallback; } /**************************************************************************** * * neSimulator::SetCustomCDRB2RBCallback * ****************************************************************************/ void neSimulator::SetCustomCDRB2RBCallback(neCustomCDRB2RBCallback * cb) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.customCDRB2RBCallback = cb; } /**************************************************************************** * * neSimulator::GetCustomCDRB2RBCallback * ****************************************************************************/ neCustomCDRB2RBCallback * neSimulator::GetCustomCDRB2RBCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.customCDRB2RBCallback; } /**************************************************************************** * * neSimulator::SetCustomCDRB2ABCallback * ****************************************************************************/ void neSimulator::SetCustomCDRB2ABCallback(neCustomCDRB2ABCallback * cb) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.customCDRB2ABCallback = cb; } /**************************************************************************** * * neSimulator::GetCustomCDRB2ABCallback * ****************************************************************************/ neCustomCDRB2ABCallback * neSimulator::GetCustomCDRB2ABCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.customCDRB2ABCallback; } /**************************************************************************** * * neSimulator::SetLogOutputCallback * ****************************************************************************/ void neSimulator::SetLogOutputCallback(neLogOutputCallback * fn) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.SetLogOutputCallback(fn); } /* f32 neSimulator::GetMagicNumber() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.magicNumber; } */ /**************************************************************************** * * neSimulator::GetLogOutputCallback * ****************************************************************************/ neLogOutputCallback * neSimulator::GetLogOutputCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.logCallback; } /**************************************************************************** * * neSimulator::SetLogOutputLevel * ****************************************************************************/ void neSimulator::SetLogOutputLevel(LOG_OUTPUT_LEVEL lvl) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.SetLogOutputLevel(lvl); } /**************************************************************************** * * neSimulator::GetCurrentSizeInfo * ****************************************************************************/ neSimulatorSizeInfo neSimulator::GetCurrentSizeInfo() { CAST_THIS(neFixedTimeStepSimulator, sim); neSimulatorSizeInfo ret; ret.rigidBodiesCount = sim.rigidBodyHeap.GetUsedCount(); ret.animatedBodiesCount = sim.collisionBodyHeap.GetUsedCount(); ret.rigidParticleCount = sim.rigidParticleHeap.GetUsedCount(); ret.controllersCount = sim.controllerHeap.GetUsedCount(); ret.overlappedPairsCount = sim.region.overlappedPairs.GetUsedCount(); ret.geometriesCount = sim.geometryHeap.GetUsedCount(); ret.constraintsCount = sim.constraintHeap.GetUsedCount(); ret.constraintSetsCount = sim.constraintHeaders.GetUsedCount(); // ret.constraintBufferSize = sim.miniConstraintHeap.GetUsedCount(); ret.sensorsCount = sim.sensorHeap.GetUsedCount(); ret.terrainNodesStartCount = sim.region.terrainTree.nodes.GetUsedCount(); ret.terrainNodesGrowByCount = sim.sizeInfo.terrainNodesGrowByCount; return ret; } /**************************************************************************** * * neSimulator::GetStartSizeInfo * ****************************************************************************/ neSimulatorSizeInfo neSimulator::GetStartSizeInfo() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.sizeInfo; } /**************************************************************************** * * neSimulator::GetMemoryUsage * ****************************************************************************/ void neSimulator::GetMemoryAllocated(s32 & memoryAllocated) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.GetMemoryAllocated(memoryAllocated); } /**************************************************************************** * * neJoint::SetType * ****************************************************************************/ void neJoint::SetType(ConstraintType t) { CAST_THIS(_neConstraint, c); c.SetType(t); } /**************************************************************************** * * neJoint::GetType * ****************************************************************************/ neJoint::ConstraintType neJoint::GetType() { CAST_THIS(_neConstraint, c); return c.type; } /**************************************************************************** * * neJoint::GetRigidBodyA * ****************************************************************************/ neRigidBody * neJoint::GetRigidBodyA() { CAST_THIS(_neConstraint, c); return reinterpret_cast<neRigidBody *>(c.bodyA); } /**************************************************************************** * * neJoint::GetRigidBodyB * ****************************************************************************/ neRigidBody * neJoint::GetRigidBodyB() { CAST_THIS(_neConstraint, c); if (!c.bodyB) return NULL; if (c.bodyB->AsCollisionBody()) return NULL; return reinterpret_cast<neRigidBody *>(c.bodyB); } /**************************************************************************** * * neJoint::GetAnimatedBodyB * ****************************************************************************/ neAnimatedBody * neJoint::GetAnimatedBodyB() { CAST_THIS(_neConstraint, c); if (!c.bodyB) return NULL; if (c.bodyB->AsRigidBody()) return NULL; return reinterpret_cast<neAnimatedBody *>(c.bodyB); } /**************************************************************************** * * neJoint::SetJointFrameA * ****************************************************************************/ void neJoint::SetJointFrameA(const neT3 & frameA) { CAST_THIS(_neConstraint, c); c.frameA = frameA; } /**************************************************************************** * * neJoint::SetJointFrameB * ****************************************************************************/ void neJoint::SetJointFrameB(const neT3 & frameB) { CAST_THIS(_neConstraint, c); c.frameB = frameB; } void neJoint::SetJointFrameWorld(const neT3 & frame) { CAST_THIS(_neConstraint, c); neT3 w2b; w2b = c.bodyA->GetB2W().FastInverse(); c.frameA = w2b * frame; if (!c.bodyB) { c.frameB = frame; return; } w2b = c.bodyB->GetB2W().FastInverse(); c.frameB = w2b * frame; } /**************************************************************************** * * neJoint::GetJointFrameA * ****************************************************************************/ neT3 neJoint::GetJointFrameA() { CAST_THIS(_neConstraint, c); if (!c.bodyA) { return c.frameA; } neT3 ret; ret = c.bodyA->State().b2w * c.frameA; return ret; } /**************************************************************************** * * neJoint::GetJointFrameB * ****************************************************************************/ neT3 neJoint::GetJointFrameB() { CAST_THIS(_neConstraint, c); if (!c.bodyB) { return c.frameB; } neT3 ret; neCollisionBody_ * cb = c.bodyB->AsCollisionBody(); if (cb) { ret = cb->b2w * c.frameB; } else { neRigidBody_ * rb = c.bodyB->AsRigidBody(); ret = rb->State().b2w * c.frameB; } return ret; } /**************************************************************************** * * neJoint::SetJointLength * ****************************************************************************/ void neJoint::SetJointLength(f32 length) { CAST_THIS(_neConstraint, c); c.jointLength = length; } /**************************************************************************** * * neJoint::GetJointLength * ****************************************************************************/ f32 neJoint::GetJointLength() { CAST_THIS(_neConstraint, c); return c.jointLength; } /**************************************************************************** * * neJoint::Enable * ****************************************************************************/ void neJoint::Enable(neBool yes) { CAST_THIS(_neConstraint, c); c.Enable(yes); } /**************************************************************************** * * neJoint::IsEnable * ****************************************************************************/ neBool neJoint::Enable() { CAST_THIS(_neConstraint, c); return c.enable; } /**************************************************************************** * * neJoint::InfiniteMassB * ****************************************************************************/ /* void neJoint::InfiniteMassB(neBool yes) { CAST_THIS(_neConstraint, c); c.InfiniteMassB(yes); } */ /**************************************************************************** * * neJoint::SetDampingFactor * ****************************************************************************/ void neJoint::SetDampingFactor(f32 damp) { CAST_THIS(_neConstraint, c); c.jointDampingFactor = damp; } /**************************************************************************** * * neJoint::GetDampingFactor * ****************************************************************************/ f32 neJoint::GetDampingFactor() { CAST_THIS(_neConstraint, c); return c.jointDampingFactor; } /**************************************************************************** * * neJoint::SetEpsilon * ****************************************************************************/ void neJoint::SetEpsilon(f32 t) { CAST_THIS(_neConstraint, c); c.accuracy = t; } /**************************************************************************** * * neJoint::GetEpsilon * ****************************************************************************/ f32 neJoint::GetEpsilon() { CAST_THIS(_neConstraint, c); if (c.accuracy <= 0.0f) return DEFAULT_CONSTRAINT_EPSILON; return c.accuracy; } /**************************************************************************** * * neJoint::SetIteration2 * ****************************************************************************/ void neJoint::SetIteration(s32 i) { CAST_THIS(_neConstraint, c); c.iteration = i; } /**************************************************************************** * * neJoint::GetIteration2 * ****************************************************************************/ s32 neJoint::GetIteration() { CAST_THIS(_neConstraint, c); return c.iteration; } /**************************************************************************** * * neJoint::GetUpperLimit * ****************************************************************************/ f32 neJoint::GetUpperLimit() { CAST_THIS(_neConstraint, c); return c.limitStates[0].upperLimit; } /**************************************************************************** * * neJoint::SetUpperLimit * ****************************************************************************/ void neJoint::SetUpperLimit(f32 upperLimit) { CAST_THIS(_neConstraint, c); c.limitStates[0].upperLimit = upperLimit; } /**************************************************************************** * * neJoint::GetLowerLimit * ****************************************************************************/ f32 neJoint::GetLowerLimit() { CAST_THIS(_neConstraint, c); return c.limitStates[0].lowerLimit; } /**************************************************************************** * * neJoint::SetLowerLimit * ****************************************************************************/ void neJoint::SetLowerLimit(f32 lowerLimit) { CAST_THIS(_neConstraint, c); c.limitStates[0].lowerLimit = lowerLimit; } /**************************************************************************** * * neJoint::IsEnableLimit * ****************************************************************************/ neBool neJoint::EnableLimit() { CAST_THIS(_neConstraint, c); return c.limitStates[0].enableLimit; } /**************************************************************************** * * neJoint::EnableLimite * ****************************************************************************/ void neJoint::EnableLimit(neBool yes) { CAST_THIS(_neConstraint, c); c.limitStates[0].enableLimit = yes; } /**************************************************************************** * * neJoint::GetUpperLimit2 * ****************************************************************************/ f32 neJoint::GetUpperLimit2() { CAST_THIS(_neConstraint, c); return c.limitStates[1].upperLimit; } /**************************************************************************** * * neJoint::SetUpperLimit2 * ****************************************************************************/ void neJoint::SetUpperLimit2(f32 upperLimit) { CAST_THIS(_neConstraint, c); c.limitStates[1].upperLimit = upperLimit; } /**************************************************************************** * * neJoint::GetLowerLimit2 * ****************************************************************************/ f32 neJoint::GetLowerLimit2() { CAST_THIS(_neConstraint, c); return c.limitStates[1].lowerLimit; } /**************************************************************************** * * neJoint::SetLowerLimit2 * ****************************************************************************/ void neJoint::SetLowerLimit2(f32 lowerLimit) { CAST_THIS(_neConstraint, c); c.limitStates[1].lowerLimit = lowerLimit; } /**************************************************************************** * * neJoint::IsEnableLimit2 * ****************************************************************************/ neBool neJoint::EnableLimit2() { CAST_THIS(_neConstraint, c); return c.limitStates[1].enableLimit; } /**************************************************************************** * * neJoint::EnableMotor * ****************************************************************************/ neBool neJoint::EnableMotor() { CAST_THIS(_neConstraint, c); return c.motors[0].enable; } /**************************************************************************** * * neJoint::EnableMotor * ****************************************************************************/ void neJoint::EnableMotor(neBool yes) { CAST_THIS(_neConstraint, c); c.motors[0].enable = yes; } /**************************************************************************** * * neJoint::SetMotor * ****************************************************************************/ void neJoint::SetMotor(MotorType motorType, f32 desireValue, f32 maxForce) { CAST_THIS(_neConstraint, c); c.motors[0].motorType = motorType; c.motors[0].desireVelocity = desireValue; c.motors[0].maxForce = neAbs(maxForce); } /**************************************************************************** * * neJoint::GetMotor * ****************************************************************************/ void neJoint::GetMotor(MotorType & motorType, f32 & desireValue, f32 & maxForce) { CAST_THIS(_neConstraint, c); motorType = c.motors[0].motorType; desireValue = c.motors[0].desireVelocity; maxForce = c.motors[0].maxForce; } /**************************************************************************** * * neJoint::EnableMotor2 * ****************************************************************************/ neBool neJoint::EnableMotor2() { CAST_THIS(_neConstraint, c); return c.motors[1].enable; } /**************************************************************************** * * neJoint::EnableMotor2 * ****************************************************************************/ void neJoint::EnableMotor2(neBool yes) { CAST_THIS(_neConstraint, c); c.motors[1].enable = yes; } /**************************************************************************** * * neJoint::SetMotor2 * ****************************************************************************/ void neJoint::SetMotor2(MotorType motorType, f32 desireValue, f32 maxForce) { CAST_THIS(_neConstraint, c); c.motors[1].motorType = motorType; c.motors[1].desireVelocity = desireValue; c.motors[1].maxForce = neAbs(maxForce); } /**************************************************************************** * * neJoint::GetMotor2 * ****************************************************************************/ void neJoint::GetMotor2(MotorType & motorType, f32 & desireValue, f32 & maxForce) { CAST_THIS(_neConstraint, c); motorType = c.motors[1].motorType; desireValue = c.motors[1].desireVelocity; maxForce = c.motors[1].maxForce; } /**************************************************************************** * * neJoint::EnableLimite * ****************************************************************************/ void neJoint::EnableLimit2(neBool yes) { CAST_THIS(_neConstraint, c); c.limitStates[1].enableLimit = yes; } /**************************************************************************** * * neJoint::AddController * ****************************************************************************/ neJointController * neJoint::AddController(neJointControllerCallback * controller, s32 period) { CAST_THIS(_neConstraint, c); return (neJointController *)c.AddController(controller, period); } /**************************************************************************** * * neJoint::RemoveController * ****************************************************************************/ neBool neJoint::RemoveController(neJointController * jController) { CAST_THIS(_neConstraint, c); if (!c.controllers) return false; neControllerItem * ci = (neControllerItem *)c.controllers; while (ci) { neController * con = reinterpret_cast<neController *>(ci); ci = ci->next; if (con == reinterpret_cast<neController *>(jController)) { //reinterpret_cast<neControllerItem *>(con)->Remove(); c.sim->controllerHeap.Dealloc(con, 1); return true; } } return false; } /**************************************************************************** * * neJoint::BeginIterateController * ****************************************************************************/ void neJoint::BeginIterateController() { CAST_THIS(_neConstraint, c); c.BeginIterateController(); } /**************************************************************************** * * neJoint::GetNextController * ****************************************************************************/ neJointController * neJoint::GetNextController() { CAST_THIS(_neConstraint, c); return (neJointController *)c.GetNextController(); } /**************************************************************************** * * neJoint::SetBSPoints * ****************************************************************************/ /* neBool neJoint::SetBSPoints(const neV3 & pointA, const neV3 & pointB) { CAST_THIS(_neConstraint, c); if (c.type != NE_Constraint_BALLSOCKET) return false; c.cpointsA[0].PtBody() = pointA; c.cpointsB[0].PtBody() = pointB; return true; } */ /**************************************************************************** * * neJoint::SetHingePoints * ****************************************************************************/ /* neBool neJoint::SetHingePoints(const neV3 & pointA1, const neV3 & pointA2, const neV3 & pointB1, const neV3 & pointB2) { CAST_THIS(_neConstraint, c); if (c.type != NE_Constraint_HINGE) return false; c.cpointsA[0].PtBody() = pointA1; c.cpointsA[1].PtBody() = pointA2; c.cpointsB[0].PtBody() = pointB1; c.cpointsB[1].PtBody() = pointB2; return true; } */ /**************************************************************************** * * neSensor::SetLineSensor * ****************************************************************************/ void neSensor::SetLineSensor(const neV3 & pos, const neV3 & lineVector) { CAST_THIS(neSensor_, sensor); sensor.pos = pos; sensor.dir = lineVector; sensor.dirNormal = lineVector; sensor.dirNormal.Normalize(); sensor.length = lineVector.Length(); } /**************************************************************************** * * neSensor::SetUserData * ****************************************************************************/ void neSensor::SetUserData(u32 cookies) { CAST_THIS(neSensor_, sensor); sensor.cookies = cookies; } /**************************************************************************** * * neSensor::GetUserData * ****************************************************************************/ u32 neSensor::GetUserData() { CAST_THIS(neSensor_, sensor); return sensor.cookies; } /**************************************************************************** * * neSensor::GetLineNormal * ****************************************************************************/ neV3 neSensor::GetLineVector() { CAST_THIS(neSensor_, sensor); return sensor.dir; } /**************************************************************************** * * neSensor::GetLineNormal * ****************************************************************************/ neV3 neSensor::GetLineUnitVector() { CAST_THIS(neSensor_, sensor); return sensor.dirNormal ; } /**************************************************************************** * * neSensor::GetLinePos * ****************************************************************************/ neV3 neSensor::GetLinePos() { CAST_THIS(neSensor_, sensor); return sensor.pos; } /**************************************************************************** * * neSensor::GetDetectDepth * ****************************************************************************/ f32 neSensor::GetDetectDepth() { CAST_THIS(neSensor_, sensor); return sensor.depth; } /**************************************************************************** * * neSensor::GetDetectNormal * ****************************************************************************/ neV3 neSensor::GetDetectNormal() { CAST_THIS(neSensor_, sensor); return sensor.normal; } /**************************************************************************** * * neSensor::GetDetectContactPoint * ****************************************************************************/ neV3 neSensor::GetDetectContactPoint() { CAST_THIS(neSensor_, sensor); return sensor.contactPoint; } /**************************************************************************** * * neSensor::GetDetectRigidBody * ****************************************************************************/ neRigidBody * neSensor::GetDetectRigidBody() { CAST_THIS(neSensor_, sensor); if (!sensor.body) return NULL; if (sensor.body->AsCollisionBody()) return NULL; return (neRigidBody *)sensor.body; } /**************************************************************************** * * neSensor::GetDetectAnimatedBody * ****************************************************************************/ neAnimatedBody * neSensor::GetDetectAnimatedBody() { CAST_THIS(neSensor_, sensor); if (!sensor.body) return NULL; if (sensor.body->AsRigidBody()) return NULL; return (neAnimatedBody *)sensor.body; } /**************************************************************************** * * neSensor:: * ****************************************************************************/ s32 neSensor::GetDetectMaterial() { CAST_THIS(neSensor_, sensor); return sensor.materialID; } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ neRigidBody * neRigidBodyController::GetRigidBody() { CAST_THIS(neController, c); return (neRigidBody *)c.rb; } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ neV3 neRigidBodyController::GetControllerForce() { CAST_THIS(neController, c); return c.forceA; } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ neV3 neRigidBodyController::GetControllerTorque() { CAST_THIS(neController, c); return c.torqueA; } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ void neRigidBodyController::SetControllerForce(const neV3 & force) { CAST_THIS(neController, c); c.forceA = force; } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ void neRigidBodyController::SetControllerForceWithTorque(const neV3 & force, const neV3 & pos) { CAST_THIS(neController, c); c.forceA = force; c.torqueA = ((pos - c.rb->GetPos()).Cross(force)); } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ void neRigidBodyController::SetControllerTorque(const neV3 & torque) { CAST_THIS(neController, c); c.torqueA = torque; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ neJoint * neJointController::GetJoint() { CAST_THIS(neController, c); return (neJoint *)c.constraint; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ neV3 neJointController::GetControllerForceBodyA() { CAST_THIS(neController, c); return c.forceA; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ neV3 neJointController::GetControllerForceBodyB() { CAST_THIS(neController, c); return c.forceB; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ neV3 neJointController::GetControllerTorqueBodyA() { CAST_THIS(neController, c); return c.torqueA; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ neV3 neJointController::GetControllerTorqueBodyB() { CAST_THIS(neController, c); return c.torqueB; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerForceBodyA(const neV3 & force) { CAST_THIS(neController, c); c.forceA = force; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerForceWithTorqueBodyA(const neV3 & force, const neV3 & pos) { CAST_THIS(neController, c); c.forceA = force; c.torqueA = ((pos - c.constraint->bodyA->GetPos()).Cross(force)); } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerForceWithTorqueBodyB(const neV3 & force, const neV3 & pos) { CAST_THIS(neController, c); c.forceB = force; if (c.constraint->bodyB && !c.constraint->bodyB->AsCollisionBody()) { neRigidBody_ * rb = (neRigidBody_*)c.constraint->bodyB; c.torqueB = ((pos - rb->GetPos()).Cross(force)); } } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerForceBodyB(const neV3 & force) { CAST_THIS(neController, c); c.forceB = force; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerTorqueBodyA(const neV3 & torque) { CAST_THIS(neController, c); c.torqueA = torque; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerTorqueBodyB(const neV3 & torque) { CAST_THIS(neController, c); c.torqueB = torque; } /**************************************************************************** * * neCollisionTable::Set * ****************************************************************************/ void neCollisionTable::Set(s32 collisionID1, s32 collisionID2, neReponseBitFlag response) { CAST_THIS(neCollisionTable_, ct); ct.Set(collisionID1, collisionID2, response); } /**************************************************************************** * * neCollisionTable::Get * ****************************************************************************/ neCollisionTable::neReponseBitFlag neCollisionTable::Get(s32 collisionID1, s32 collisionID2) { CAST_THIS(neCollisionTable_, ct); ASSERT(collisionID1 < NE_COLLISION_TABLE_MAX); ASSERT(collisionID2 < NE_COLLISION_TABLE_MAX); if (collisionID1 < NE_COLLISION_TABLE_MAX && collisionID2 < NE_COLLISION_TABLE_MAX) { return ct.table[collisionID1][collisionID2]; } else { return RESPONSE_IGNORE; } } /**************************************************************************** * * neCollisionTable::GetMaxCollisionID * ****************************************************************************/ s32 neCollisionTable::GetMaxCollisionID() { return NE_COLLISION_TABLE_MAX; } /**************************************************************************** * * Helper functions * ****************************************************************************/ /**************************************************************************** * * BoxInertiaTensor * ****************************************************************************/ neV3 neBoxInertiaTensor(const neV3 & boxSize, f32 mass) { return neBoxInertiaTensor(boxSize[0], boxSize[1], boxSize[2], mass); } neV3 neBoxInertiaTensor(f32 width, f32 height, f32 depth, f32 mass) { neV3 ret; f32 maxdim = width; if (height > maxdim) maxdim = height; if (depth > maxdim) maxdim = depth; #if 0 f32 xsq = width; f32 ysq = height; f32 zsq = depth; #else f32 xsq = maxdim; f32 ysq = maxdim; f32 zsq = maxdim; #endif xsq *= xsq; ysq *= ysq; zsq *= zsq; ret[0] = (ysq + zsq) * mass / 3.0f; ret[1] = (xsq + zsq) * mass / 3.0f; ret[2] = (xsq + ysq) * mass / 3.0f; return ret; } neV3 neSphereInertiaTensor(f32 diameter, f32 mass) { f32 radius = diameter * 0.5f; f32 value = 2.0f / 5.0f * mass * radius * radius; neV3 ret; ret.Set(value); return ret; } neV3 neCylinderInertiaTensor(f32 diameter, f32 height, f32 mass) { // if (height > diameter) // { // diameter = height; // } f32 radius = diameter * 0.5f; f32 radiusSq = radius * radius; f32 Ixz = 1.0f / 12.0f * mass * height * height + 0.25f * mass * radiusSq; f32 Iyy = 0.5f * mass * radiusSq; neV3 ret; ret.Set(Ixz, Iyy, Ixz); return ret; } /* neBool IsEnableLimit(); void EnableLimit(neBool yes); f32 GetUpperLimit(); void SetUpperLimit(f32 upperLimit); f32 GetLowerLimit(); void SetLowerLimit(f32 lowerLimit); */ }
[ [ [ 1, 3844 ] ] ]
a41489028fd9b36b55a0678ae1b488997aea4c3d
12203ea9fe0801d613bbb2159d4f69cab3c84816
/Export/cpp/windows/obj/src/nme/utils/ByteArray.cpp
e3d6384131e0f0f34a930d17d7f53cfced869ab4
[]
no_license
alecmce/haxe_game_of_life
91b5557132043c6e9526254d17fdd9bcea9c5086
35ceb1565e06d12c89481451a7bedbbce20fa871
refs/heads/master
2016-09-16T00:47:24.032302
2011-10-10T12:38:14
2011-10-10T12:38:14
2,547,793
0
0
null
null
null
null
UTF-8
C++
false
false
40,338
cpp
#include <hxcpp.h> #ifndef INCLUDED_cpp_Lib #include <cpp/Lib.h> #endif #ifndef INCLUDED_cpp_zip_Compress #include <cpp/zip/Compress.h> #endif #ifndef INCLUDED_cpp_zip_Uncompress #include <cpp/zip/Uncompress.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_nme_Loader #include <nme/Loader.h> #endif #ifndef INCLUDED_nme_errors_EOFError #include <nme/errors/EOFError.h> #endif #ifndef INCLUDED_nme_errors_Error #include <nme/errors/Error.h> #endif #ifndef INCLUDED_nme_utils_ByteArray #include <nme/utils/ByteArray.h> #endif #ifndef INCLUDED_nme_utils_IDataInput #include <nme/utils/IDataInput.h> #endif namespace nme{ namespace utils{ Void ByteArray_obj::__construct(Dynamic __o_inSize) { int inSize = __o_inSize.Default(0); { HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",33) this->bigEndian = true; HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",34) this->position = (int)0; HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",35) if (((inSize >= (int)0))){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",42) Array< unsigned char > data = Array_obj< unsigned char >::__new(); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",43) if (((inSize > (int)0))){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",44) data[(inSize - (int)1)] = (int)0; } HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",45) super::__construct(inSize,data); } } ; return null(); } ByteArray_obj::~ByteArray_obj() { } Dynamic ByteArray_obj::__CreateEmpty() { return new ByteArray_obj; } hx::ObjectPtr< ByteArray_obj > ByteArray_obj::__new(Dynamic __o_inSize) { hx::ObjectPtr< ByteArray_obj > result = new ByteArray_obj(); result->__construct(__o_inSize); return result;} Dynamic ByteArray_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< ByteArray_obj > result = new ByteArray_obj(); result->__construct(inArgs[0]); return result;} hx::Object *ByteArray_obj::__ToInterface(const type_info &inType) { if (inType==typeid( ::nme::utils::IDataInput_obj)) return operator ::nme::utils::IDataInput_obj *(); return super::__ToInterface(inType); } void ByteArray_obj::__init__(){ HX_BEGIN_LOCAL_FUNC_S0(hx::LocalFunc,_Function_1_1) ::nme::utils::ByteArray run(int inLen){ { HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",428) return ::nme::utils::ByteArray_obj::__new(inLen); } return null(); } HX_END_LOCAL_FUNC1(return) HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",428) ::nme::utils::ByteArray_obj::factory = Dynamic(new _Function_1_1()); HX_BEGIN_LOCAL_FUNC_S0(hx::LocalFunc,_Function_1_2) Void run(::nme::utils::ByteArray inArray,int inLen){ { HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",430) if (((inLen > (int)0))){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",431) inArray->__Field(HX_CSTRING("ensureElem"))((inLen - (int)1),true); } HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",432) inArray->__FieldRef(HX_CSTRING("length")) = inLen; } return null(); } HX_END_LOCAL_FUNC2((void)) HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",429) ::nme::utils::ByteArray_obj::resize = Dynamic(new _Function_1_2()); HX_BEGIN_LOCAL_FUNC_S0(hx::LocalFunc,_Function_1_3) Array< unsigned char > run(::nme::utils::ByteArray inArray){ { HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",434) return inArray->__Field(HX_CSTRING("b")); } return null(); } HX_END_LOCAL_FUNC1(return) HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",434) ::nme::utils::ByteArray_obj::bytes = Dynamic(new _Function_1_3()); HX_BEGIN_LOCAL_FUNC_S0(hx::LocalFunc,_Function_1_4) int run(::nme::utils::ByteArray inArray){ { HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",435) return ( (((inArray == null()))) ? int((int)0) : int(inArray->__Field(HX_CSTRING("length"))) ); } return null(); } HX_END_LOCAL_FUNC1(return) HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",435) ::nme::utils::ByteArray_obj::slen = Dynamic(new _Function_1_4()); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",437) Dynamic init = ::nme::Loader_obj::load(HX_CSTRING("nme_byte_array_init"),(int)4); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",438) init(::nme::utils::ByteArray_obj::factory,::nme::utils::ByteArray_obj::slen,::nme::utils::ByteArray_obj::resize,::nme::utils::ByteArray_obj::bytes); } Void ByteArray_obj::setLength( int inLength){ { HX_SOURCE_PUSH("ByteArray_obj::setLength") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",64) if (((inLength > (int)0))){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",65) this->ensureElem((inLength - (int)1),false); } HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",66) this->length = inLength; } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,setLength,(void)) Void ByteArray_obj::checkData( int inLength){ { HX_SOURCE_PUSH("ByteArray_obj::checkData") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",70) if ((((inLength + this->position) > this->length))){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",72) this->ThrowEOFi(); } } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,checkData,(void)) Void ByteArray_obj::writeFile( ::String inString){ { HX_SOURCE_PUSH("ByteArray_obj::writeFile") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",83) ::nme::utils::ByteArray_obj::nme_byte_array_overwrite_file(inString,hx::ObjectPtr<OBJ_>(this)); } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,writeFile,(void)) int ByteArray_obj::__get( int pos){ HX_SOURCE_PUSH("ByteArray_obj::__get") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",92) return this->b->__get(pos); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,__get,return ) Void ByteArray_obj::__set( int pos,int v){ { HX_SOURCE_PUSH("ByteArray_obj::__set") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",102) this->b[pos] = v; } return null(); } HX_DEFINE_DYNAMIC_FUNC2(ByteArray_obj,__set,(void)) Void ByteArray_obj::compress( Dynamic __o_algorithm){ ::String algorithm = __o_algorithm.Default(HX_CSTRING("")); HX_SOURCE_PUSH("ByteArray_obj::compress"); { HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",116) ::nme::utils::ByteArray src = hx::ObjectPtr<OBJ_>(this); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",118) ::haxe::io::Bytes result = ::cpp::zip::Compress_obj::run(src,(int)8); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",119) this->b = result->b; HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",120) this->length = result->length; HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",121) this->position = this->length; } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,compress,(void)) Void ByteArray_obj::uncompress( Dynamic __o_algorithm){ ::String algorithm = __o_algorithm.Default(HX_CSTRING("")); HX_SOURCE_PUSH("ByteArray_obj::uncompress"); { HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",132) ::nme::utils::ByteArray src = hx::ObjectPtr<OBJ_>(this); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",135) ::haxe::io::Bytes result = ::cpp::zip::Uncompress_obj::run(src,null()); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",136) this->b = result->b; HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",137) this->length = result->length; HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",138) this->position = (int)0; } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,uncompress,(void)) int ByteArray_obj::ThrowEOFi( ){ HX_SOURCE_PUSH("ByteArray_obj::ThrowEOFi") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",144) hx::Throw (::nme::errors::EOFError_obj::__new()); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",144) return (int)0; } HX_DEFINE_DYNAMIC_FUNC0(ByteArray_obj,ThrowEOFi,return ) int ByteArray_obj::nmeGetBytesAvailable( ){ HX_SOURCE_PUSH("ByteArray_obj::nmeGetBytesAvailable") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",149) return (this->length - this->position); } HX_DEFINE_DYNAMIC_FUNC0(ByteArray_obj,nmeGetBytesAvailable,return ) int ByteArray_obj::readByte( ){ HX_SOURCE_PUSH("ByteArray_obj::readByte") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",152) return ( (((this->position < this->length))) ? int(this->b->__get((this->position)++)) : int(this->ThrowEOFi()) ); } HX_DEFINE_DYNAMIC_FUNC0(ByteArray_obj,readByte,return ) bool ByteArray_obj::readBoolean( ){ HX_SOURCE_PUSH("ByteArray_obj::readBoolean") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",156) return ( ((((this->position + (int)1) < this->length))) ? bool((this->b->__get((this->position)++) != (int)0)) : bool((this->ThrowEOFi() != (int)0)) ); } HX_DEFINE_DYNAMIC_FUNC0(ByteArray_obj,readBoolean,return ) Void ByteArray_obj::readBytes( ::nme::utils::ByteArray outData,Dynamic __o_inOffset,Dynamic __o_inLen){ int inOffset = __o_inOffset.Default(0); int inLen = __o_inLen.Default(0); HX_SOURCE_PUSH("ByteArray_obj::readBytes"); { HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",161) if (((inLen == (int)0))){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",162) inLen = (this->length - this->position); } HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",163) if ((((this->position + inLen) > this->length))){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",164) this->ThrowEOFi(); } HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",165) if (((outData->length < (inOffset + inLen)))){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",166) outData->ensureElem(((inOffset + inLen) - (int)1),true); } HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",171) Array< unsigned char > b1 = this->b; HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",172) Array< unsigned char > b2 = outData->b; HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",173) int p = this->position; HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",174) { HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",174) int _g = (int)0; HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",174) while(((_g < inLen))){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",174) int i = (_g)++; HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",175) b2[(inOffset + i)] = b1->__get((p + i)); } } HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",177) hx::AddEq(this->position,inLen); } return null(); } HX_DEFINE_DYNAMIC_FUNC3(ByteArray_obj,readBytes,(void)) double ByteArray_obj::readFloat( ){ HX_SOURCE_PUSH("ByteArray_obj::readFloat") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",182) if ((((this->position + (int)4) > this->length))){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",183) this->ThrowEOFi(); } HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",188) ::haxe::io::Bytes bytes = ::haxe::io::Bytes_obj::__new((int)4,this->b->slice(this->position,(this->position + (int)4))); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",191) hx::AddEq(this->position,(int)4); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",192) return ::nme::utils::ByteArray_obj::_float_of_bytes(bytes->b,this->bigEndian); } HX_DEFINE_DYNAMIC_FUNC0(ByteArray_obj,readFloat,return ) double ByteArray_obj::readDouble( ){ HX_SOURCE_PUSH("ByteArray_obj::readDouble") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",197) if ((((this->position + (int)8) > this->length))){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",198) this->ThrowEOFi(); } HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",203) ::haxe::io::Bytes bytes = ::haxe::io::Bytes_obj::__new((int)8,this->b->slice(this->position,(this->position + (int)8))); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",206) hx::AddEq(this->position,(int)8); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",207) return ::nme::utils::ByteArray_obj::_double_of_bytes(bytes->b,this->bigEndian); } HX_DEFINE_DYNAMIC_FUNC0(ByteArray_obj,readDouble,return ) int ByteArray_obj::readInt( ){ HX_SOURCE_PUSH("ByteArray_obj::readInt") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",213) int ch1 = ( (((this->position < this->length))) ? int(this->b->__get((this->position)++)) : int(this->ThrowEOFi()) ); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",214) int ch2 = ( (((this->position < this->length))) ? int(this->b->__get((this->position)++)) : int(this->ThrowEOFi()) ); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",215) int ch3 = ( (((this->position < this->length))) ? int(this->b->__get((this->position)++)) : int(this->ThrowEOFi()) ); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",216) int ch4 = ( (((this->position < this->length))) ? int(this->b->__get((this->position)++)) : int(this->ThrowEOFi()) ); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",217) return ( ((this->bigEndian)) ? int((int((int((int((int(ch1) << int((int)24))) | int((int(ch2) << int((int)16))))) | int((int(ch3) << int((int)8))))) | int(ch4))) : int((int((int((int((int(ch4) << int((int)24))) | int((int(ch3) << int((int)16))))) | int((int(ch2) << int((int)8))))) | int(ch1))) ); } HX_DEFINE_DYNAMIC_FUNC0(ByteArray_obj,readInt,return ) int ByteArray_obj::readShort( ){ HX_SOURCE_PUSH("ByteArray_obj::readShort") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",223) int ch1 = ( (((this->position < this->length))) ? int(this->b->__get((this->position)++)) : int(this->ThrowEOFi()) ); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",224) int ch2 = ( (((this->position < this->length))) ? int(this->b->__get((this->position)++)) : int(this->ThrowEOFi()) ); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",225) int val = ( ((this->bigEndian)) ? int((int((int(ch1) << int((int)8))) | int(ch2))) : int((((int(ch2) << int((int)8))) + ch1)) ); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",226) return ( (((val >= (int)32768))) ? int(((int)65534 - val)) : int(val) ); } HX_DEFINE_DYNAMIC_FUNC0(ByteArray_obj,readShort,return ) int ByteArray_obj::readUnsignedByte( ){ HX_SOURCE_PUSH("ByteArray_obj::readUnsignedByte") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",229) return ( (((this->position < this->length))) ? int(this->b->__get((this->position)++)) : int(this->ThrowEOFi()) ); } HX_DEFINE_DYNAMIC_FUNC0(ByteArray_obj,readUnsignedByte,return ) int ByteArray_obj::readUnsignedInt( ){ HX_SOURCE_PUSH("ByteArray_obj::readUnsignedInt") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",232) int ch1 = ( (((this->position < this->length))) ? int(this->b->__get((this->position)++)) : int(this->ThrowEOFi()) ); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",233) int ch2 = ( (((this->position < this->length))) ? int(this->b->__get((this->position)++)) : int(this->ThrowEOFi()) ); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",234) int ch3 = ( (((this->position < this->length))) ? int(this->b->__get((this->position)++)) : int(this->ThrowEOFi()) ); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",235) int ch4 = ( (((this->position < this->length))) ? int(this->b->__get((this->position)++)) : int(this->ThrowEOFi()) ); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",236) return ( ((this->bigEndian)) ? int((int((int((int((int(ch1) << int((int)24))) | int((int(ch2) << int((int)16))))) | int((int(ch3) << int((int)8))))) | int(ch4))) : int((int((int((int((int(ch4) << int((int)24))) | int((int(ch3) << int((int)16))))) | int((int(ch2) << int((int)8))))) | int(ch1))) ); } HX_DEFINE_DYNAMIC_FUNC0(ByteArray_obj,readUnsignedInt,return ) int ByteArray_obj::readUnsignedShort( ){ HX_SOURCE_PUSH("ByteArray_obj::readUnsignedShort") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",241) int ch1 = ( (((this->position < this->length))) ? int(this->b->__get((this->position)++)) : int(this->ThrowEOFi()) ); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",242) int ch2 = ( (((this->position < this->length))) ? int(this->b->__get((this->position)++)) : int(this->ThrowEOFi()) ); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",243) return ( ((this->bigEndian)) ? int((int((int(ch1) << int((int)8))) | int(ch2))) : int((((int(ch2) << int((int)8))) + ch1)) ); } HX_DEFINE_DYNAMIC_FUNC0(ByteArray_obj,readUnsignedShort,return ) ::String ByteArray_obj::readUTF( ){ HX_SOURCE_PUSH("ByteArray_obj::readUTF") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",247) int len = this->readUnsignedShort(); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",248) return this->readUTFBytes(len); } HX_DEFINE_DYNAMIC_FUNC0(ByteArray_obj,readUTF,return ) ::String ByteArray_obj::readUTFBytes( int inLen){ HX_SOURCE_PUSH("ByteArray_obj::readUTFBytes") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",253) if ((((this->position + inLen) > this->length))){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",254) this->ThrowEOFi(); } HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",255) int p = this->position; HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",256) hx::AddEq(this->position,inLen); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",261) ::String result = HX_CSTRING(""); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",262) ::__hxcpp_string_of_bytes(this->b,result,p,inLen); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",263) return result; } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,readUTFBytes,return ) ::String ByteArray_obj::asString( ){ HX_SOURCE_PUSH("ByteArray_obj::asString") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",267) return this->readUTFBytes(this->length); } HX_DEFINE_DYNAMIC_FUNC0(ByteArray_obj,asString,return ) ::String ByteArray_obj::nmeGetEndian( ){ HX_SOURCE_PUSH("ByteArray_obj::nmeGetEndian") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",270) return ( ((this->bigEndian)) ? ::String(HX_CSTRING("bigEndian")) : ::String(HX_CSTRING("littleEndian")) ); } HX_DEFINE_DYNAMIC_FUNC0(ByteArray_obj,nmeGetEndian,return ) ::String ByteArray_obj::nmeSetEndian( ::String s){ HX_SOURCE_PUSH("ByteArray_obj::nmeSetEndian") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",276) this->bigEndian = (s == HX_CSTRING("bigEndian")); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",277) return s; } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,nmeSetEndian,return ) Void ByteArray_obj::ensureElem( int inSize,bool inUpdateLenght){ { HX_SOURCE_PUSH("ByteArray_obj::ensureElem") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",283) int len = (inSize + (int)1); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",293) if (((this->b->length < len))){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",294) this->b->__SetSize(len); } HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",296) if (((bool(inUpdateLenght) && bool((this->length < len))))){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",297) this->length = len; } } return null(); } HX_DEFINE_DYNAMIC_FUNC2(ByteArray_obj,ensureElem,(void)) Void ByteArray_obj::push_uncheck( int inByte){ { HX_SOURCE_PUSH("ByteArray_obj::push_uncheck") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",302) this->b->__unsafe_set((this->length)++,inByte); } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,push_uncheck,(void)) Void ByteArray_obj::push( int inByte){ { HX_SOURCE_PUSH("ByteArray_obj::push") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",311) this->b[(this->length)++] = inByte; } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,push,(void)) Void ByteArray_obj::writeBoolean( bool value){ { HX_SOURCE_PUSH("ByteArray_obj::writeBoolean") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",322) this->b[(this->length)++] = ( ((value)) ? int((int)1) : int((int)0) ); } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,writeBoolean,(void)) Void ByteArray_obj::writeByte( int value){ { HX_SOURCE_PUSH("ByteArray_obj::writeByte") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",326) this->b[(this->length)++] = value; } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,writeByte,(void)) Void ByteArray_obj::writeBytes( ::haxe::io::Bytes bytes,Dynamic __o_inOffset,Dynamic __o_inLength){ int inOffset = __o_inOffset.Default(0); int inLength = __o_inLength.Default(0); HX_SOURCE_PUSH("ByteArray_obj::writeBytes"); { HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",331) if (((inLength == (int)0))){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",332) inLength = bytes->length; } HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",333) this->ensureElem(((this->length + inLength) - (int)1),false); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",334) int olen = this->length; HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",335) hx::AddEq(this->length,inLength); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",336) this->blit(olen,bytes,inOffset,inLength); } return null(); } HX_DEFINE_DYNAMIC_FUNC3(ByteArray_obj,writeBytes,(void)) Void ByteArray_obj::writeDouble( double x){ { HX_SOURCE_PUSH("ByteArray_obj::writeDouble") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",343) ::haxe::io::Bytes bytes = ::haxe::io::Bytes_obj::ofData(::nme::utils::ByteArray_obj::_double_bytes(x,this->bigEndian)); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",345) this->writeBytes(bytes,null(),null()); } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,writeDouble,(void)) Void ByteArray_obj::writeFloat( double x){ { HX_SOURCE_PUSH("ByteArray_obj::writeFloat") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",352) ::haxe::io::Bytes bytes = ::haxe::io::Bytes_obj::ofData(::nme::utils::ByteArray_obj::_float_bytes(x,this->bigEndian)); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",354) this->writeBytes(bytes,null(),null()); } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,writeFloat,(void)) Void ByteArray_obj::writeInt( int value){ { HX_SOURCE_PUSH("ByteArray_obj::writeInt") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",358) this->ensureElem((this->length + (int)3),false); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",359) if ((this->bigEndian)){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",361) this->b->__unsafe_set((this->length)++,(int(value) >> int((int)24))); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",362) this->b->__unsafe_set((this->length)++,(int(value) >> int((int)16))); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",363) this->b->__unsafe_set((this->length)++,(int(value) >> int((int)8))); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",364) this->b->__unsafe_set((this->length)++,value); } else{ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",368) this->b->__unsafe_set((this->length)++,value); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",369) this->b->__unsafe_set((this->length)++,(int(value) >> int((int)8))); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",370) this->b->__unsafe_set((this->length)++,(int(value) >> int((int)16))); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",371) this->b->__unsafe_set((this->length)++,(int(value) >> int((int)24))); } } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,writeInt,(void)) Void ByteArray_obj::writeShort( int value){ { HX_SOURCE_PUSH("ByteArray_obj::writeShort") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",378) this->ensureElem((this->length + (int)1),false); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",379) if ((this->bigEndian)){ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",381) this->b->__unsafe_set((this->length)++,(int(value) >> int((int)8))); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",382) this->b->__unsafe_set((this->length)++,value); } else{ HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",386) this->b->__unsafe_set((this->length)++,value); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",387) this->b->__unsafe_set((this->length)++,(int(value) >> int((int)8))); } } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,writeShort,(void)) Void ByteArray_obj::writeUnsignedInt( int value){ { HX_SOURCE_PUSH("ByteArray_obj::writeUnsignedInt") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",391) this->writeInt(value); } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,writeUnsignedInt,(void)) Void ByteArray_obj::writeUTF( ::String s){ { HX_SOURCE_PUSH("ByteArray_obj::writeUTF") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",399) ::haxe::io::Bytes bytes = ::haxe::io::Bytes_obj::ofString(s); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",401) this->writeShort(bytes->length); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",402) this->writeBytes(bytes,null(),null()); } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,writeUTF,(void)) Void ByteArray_obj::writeUTFBytes( ::String s){ { HX_SOURCE_PUSH("ByteArray_obj::writeUTFBytes") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",409) ::haxe::io::Bytes bytes = ::haxe::io::Bytes_obj::ofString(s); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",411) this->writeBytes(bytes,null(),null()); } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,writeUTFBytes,(void)) ::nme::utils::ByteArray ByteArray_obj::fromBytes( ::haxe::io::Bytes inBytes){ HX_SOURCE_PUSH("ByteArray_obj::fromBytes") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",52) ::nme::utils::ByteArray result = ::nme::utils::ByteArray_obj::__new((int)-1); HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",53) result->b = inBytes->b; HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",54) result->length = inBytes->length; HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",58) return result; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,fromBytes,return ) ::nme::utils::ByteArray ByteArray_obj::readFile( ::String inString){ HX_SOURCE_PUSH("ByteArray_obj::readFile") HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/utils/ByteArray.hx",78) return ::nme::utils::ByteArray_obj::nme_byte_array_read_file(inString); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(ByteArray_obj,readFile,return ) Dynamic ByteArray_obj::_float_of_bytes; Dynamic ByteArray_obj::_double_of_bytes; Dynamic ByteArray_obj::_float_bytes; Dynamic ByteArray_obj::_double_bytes; Dynamic ByteArray_obj::factory; Dynamic ByteArray_obj::resize; Dynamic ByteArray_obj::slen; Dynamic ByteArray_obj::bytes; Dynamic ByteArray_obj::nme_byte_array_overwrite_file; Dynamic ByteArray_obj::nme_byte_array_read_file; ByteArray_obj::ByteArray_obj() { } void ByteArray_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(ByteArray); HX_MARK_MEMBER_NAME(position,"position"); HX_MARK_MEMBER_NAME(endian,"endian"); HX_MARK_MEMBER_NAME(bytesAvailable,"bytesAvailable"); HX_MARK_MEMBER_NAME(bigEndian,"bigEndian"); super::__Mark(HX_MARK_ARG); HX_MARK_END_CLASS(); } Dynamic ByteArray_obj::__Field(const ::String &inName) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"slen") ) { return slen; } if (HX_FIELD_EQ(inName,"push") ) { return push_dyn(); } break; case 5: if (HX_FIELD_EQ(inName,"bytes") ) { return bytes; } if (HX_FIELD_EQ(inName,"__get") ) { return __get_dyn(); } if (HX_FIELD_EQ(inName,"__set") ) { return __set_dyn(); } break; case 6: if (HX_FIELD_EQ(inName,"resize") ) { return resize; } if (HX_FIELD_EQ(inName,"endian") ) { return nmeGetEndian(); } break; case 7: if (HX_FIELD_EQ(inName,"factory") ) { return factory; } if (HX_FIELD_EQ(inName,"readInt") ) { return readInt_dyn(); } if (HX_FIELD_EQ(inName,"readUTF") ) { return readUTF_dyn(); } break; case 8: if (HX_FIELD_EQ(inName,"readFile") ) { return readFile_dyn(); } if (HX_FIELD_EQ(inName,"position") ) { return position; } if (HX_FIELD_EQ(inName,"compress") ) { return compress_dyn(); } if (HX_FIELD_EQ(inName,"readByte") ) { return readByte_dyn(); } if (HX_FIELD_EQ(inName,"asString") ) { return asString_dyn(); } if (HX_FIELD_EQ(inName,"writeInt") ) { return writeInt_dyn(); } if (HX_FIELD_EQ(inName,"writeUTF") ) { return writeUTF_dyn(); } break; case 9: if (HX_FIELD_EQ(inName,"fromBytes") ) { return fromBytes_dyn(); } if (HX_FIELD_EQ(inName,"bigEndian") ) { return bigEndian; } if (HX_FIELD_EQ(inName,"setLength") ) { return setLength_dyn(); } if (HX_FIELD_EQ(inName,"checkData") ) { return checkData_dyn(); } if (HX_FIELD_EQ(inName,"writeFile") ) { return writeFile_dyn(); } if (HX_FIELD_EQ(inName,"ThrowEOFi") ) { return ThrowEOFi_dyn(); } if (HX_FIELD_EQ(inName,"readBytes") ) { return readBytes_dyn(); } if (HX_FIELD_EQ(inName,"readFloat") ) { return readFloat_dyn(); } if (HX_FIELD_EQ(inName,"readShort") ) { return readShort_dyn(); } if (HX_FIELD_EQ(inName,"writeByte") ) { return writeByte_dyn(); } break; case 10: if (HX_FIELD_EQ(inName,"uncompress") ) { return uncompress_dyn(); } if (HX_FIELD_EQ(inName,"readDouble") ) { return readDouble_dyn(); } if (HX_FIELD_EQ(inName,"ensureElem") ) { return ensureElem_dyn(); } if (HX_FIELD_EQ(inName,"writeBytes") ) { return writeBytes_dyn(); } if (HX_FIELD_EQ(inName,"writeFloat") ) { return writeFloat_dyn(); } if (HX_FIELD_EQ(inName,"writeShort") ) { return writeShort_dyn(); } break; case 11: if (HX_FIELD_EQ(inName,"readBoolean") ) { return readBoolean_dyn(); } if (HX_FIELD_EQ(inName,"writeDouble") ) { return writeDouble_dyn(); } break; case 12: if (HX_FIELD_EQ(inName,"_float_bytes") ) { return _float_bytes; } if (HX_FIELD_EQ(inName,"readUTFBytes") ) { return readUTFBytes_dyn(); } if (HX_FIELD_EQ(inName,"nmeGetEndian") ) { return nmeGetEndian_dyn(); } if (HX_FIELD_EQ(inName,"nmeSetEndian") ) { return nmeSetEndian_dyn(); } if (HX_FIELD_EQ(inName,"push_uncheck") ) { return push_uncheck_dyn(); } if (HX_FIELD_EQ(inName,"writeBoolean") ) { return writeBoolean_dyn(); } break; case 13: if (HX_FIELD_EQ(inName,"_double_bytes") ) { return _double_bytes; } if (HX_FIELD_EQ(inName,"writeUTFBytes") ) { return writeUTFBytes_dyn(); } break; case 14: if (HX_FIELD_EQ(inName,"bytesAvailable") ) { return nmeGetBytesAvailable(); } break; case 15: if (HX_FIELD_EQ(inName,"_float_of_bytes") ) { return _float_of_bytes; } if (HX_FIELD_EQ(inName,"readUnsignedInt") ) { return readUnsignedInt_dyn(); } break; case 16: if (HX_FIELD_EQ(inName,"_double_of_bytes") ) { return _double_of_bytes; } if (HX_FIELD_EQ(inName,"readUnsignedByte") ) { return readUnsignedByte_dyn(); } if (HX_FIELD_EQ(inName,"writeUnsignedInt") ) { return writeUnsignedInt_dyn(); } break; case 17: if (HX_FIELD_EQ(inName,"readUnsignedShort") ) { return readUnsignedShort_dyn(); } break; case 20: if (HX_FIELD_EQ(inName,"nmeGetBytesAvailable") ) { return nmeGetBytesAvailable_dyn(); } break; case 24: if (HX_FIELD_EQ(inName,"nme_byte_array_read_file") ) { return nme_byte_array_read_file; } break; case 29: if (HX_FIELD_EQ(inName,"nme_byte_array_overwrite_file") ) { return nme_byte_array_overwrite_file; } } return super::__Field(inName); } Dynamic ByteArray_obj::__SetField(const ::String &inName,const Dynamic &inValue) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"slen") ) { slen=inValue.Cast< Dynamic >(); return inValue; } break; case 5: if (HX_FIELD_EQ(inName,"bytes") ) { bytes=inValue.Cast< Dynamic >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"resize") ) { resize=inValue.Cast< Dynamic >(); return inValue; } if (HX_FIELD_EQ(inName,"endian") ) { return nmeSetEndian(inValue); } break; case 7: if (HX_FIELD_EQ(inName,"factory") ) { factory=inValue.Cast< Dynamic >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"position") ) { position=inValue.Cast< int >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"bigEndian") ) { bigEndian=inValue.Cast< bool >(); return inValue; } break; case 12: if (HX_FIELD_EQ(inName,"_float_bytes") ) { _float_bytes=inValue.Cast< Dynamic >(); return inValue; } break; case 13: if (HX_FIELD_EQ(inName,"_double_bytes") ) { _double_bytes=inValue.Cast< Dynamic >(); return inValue; } break; case 14: if (HX_FIELD_EQ(inName,"bytesAvailable") ) { bytesAvailable=inValue.Cast< int >(); return inValue; } break; case 15: if (HX_FIELD_EQ(inName,"_float_of_bytes") ) { _float_of_bytes=inValue.Cast< Dynamic >(); return inValue; } break; case 16: if (HX_FIELD_EQ(inName,"_double_of_bytes") ) { _double_of_bytes=inValue.Cast< Dynamic >(); return inValue; } break; case 24: if (HX_FIELD_EQ(inName,"nme_byte_array_read_file") ) { nme_byte_array_read_file=inValue.Cast< Dynamic >(); return inValue; } break; case 29: if (HX_FIELD_EQ(inName,"nme_byte_array_overwrite_file") ) { nme_byte_array_overwrite_file=inValue.Cast< Dynamic >(); return inValue; } } return super::__SetField(inName,inValue); } void ByteArray_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_CSTRING("position")); outFields->push(HX_CSTRING("endian")); outFields->push(HX_CSTRING("bytesAvailable")); outFields->push(HX_CSTRING("bigEndian")); super::__GetFields(outFields); }; static ::String sStaticFields[] = { HX_CSTRING("fromBytes"), HX_CSTRING("readFile"), HX_CSTRING("_float_of_bytes"), HX_CSTRING("_double_of_bytes"), HX_CSTRING("_float_bytes"), HX_CSTRING("_double_bytes"), HX_CSTRING("factory"), HX_CSTRING("resize"), HX_CSTRING("slen"), HX_CSTRING("bytes"), HX_CSTRING("nme_byte_array_overwrite_file"), HX_CSTRING("nme_byte_array_read_file"), String(null()) }; static ::String sMemberFields[] = { HX_CSTRING("position"), HX_CSTRING("endian"), HX_CSTRING("bytesAvailable"), HX_CSTRING("bigEndian"), HX_CSTRING("setLength"), HX_CSTRING("checkData"), HX_CSTRING("writeFile"), HX_CSTRING("__get"), HX_CSTRING("__set"), HX_CSTRING("compress"), HX_CSTRING("uncompress"), HX_CSTRING("ThrowEOFi"), HX_CSTRING("nmeGetBytesAvailable"), HX_CSTRING("readByte"), HX_CSTRING("readBoolean"), HX_CSTRING("readBytes"), HX_CSTRING("readFloat"), HX_CSTRING("readDouble"), HX_CSTRING("readInt"), HX_CSTRING("readShort"), HX_CSTRING("readUnsignedByte"), HX_CSTRING("readUnsignedInt"), HX_CSTRING("readUnsignedShort"), HX_CSTRING("readUTF"), HX_CSTRING("readUTFBytes"), HX_CSTRING("asString"), HX_CSTRING("nmeGetEndian"), HX_CSTRING("nmeSetEndian"), HX_CSTRING("ensureElem"), HX_CSTRING("push_uncheck"), HX_CSTRING("push"), HX_CSTRING("writeBoolean"), HX_CSTRING("writeByte"), HX_CSTRING("writeBytes"), HX_CSTRING("writeDouble"), HX_CSTRING("writeFloat"), HX_CSTRING("writeInt"), HX_CSTRING("writeShort"), HX_CSTRING("writeUnsignedInt"), HX_CSTRING("writeUTF"), HX_CSTRING("writeUTFBytes"), String(null()) }; static void sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(ByteArray_obj::_float_of_bytes,"_float_of_bytes"); HX_MARK_MEMBER_NAME(ByteArray_obj::_double_of_bytes,"_double_of_bytes"); HX_MARK_MEMBER_NAME(ByteArray_obj::_float_bytes,"_float_bytes"); HX_MARK_MEMBER_NAME(ByteArray_obj::_double_bytes,"_double_bytes"); HX_MARK_MEMBER_NAME(ByteArray_obj::factory,"factory"); HX_MARK_MEMBER_NAME(ByteArray_obj::resize,"resize"); HX_MARK_MEMBER_NAME(ByteArray_obj::slen,"slen"); HX_MARK_MEMBER_NAME(ByteArray_obj::bytes,"bytes"); HX_MARK_MEMBER_NAME(ByteArray_obj::nme_byte_array_overwrite_file,"nme_byte_array_overwrite_file"); HX_MARK_MEMBER_NAME(ByteArray_obj::nme_byte_array_read_file,"nme_byte_array_read_file"); }; Class ByteArray_obj::__mClass; void ByteArray_obj::__register() { Static(__mClass) = hx::RegisterClass(HX_CSTRING("nme.utils.ByteArray"), hx::TCanCast< ByteArray_obj> ,sStaticFields,sMemberFields, &__CreateEmpty, &__Create, &super::__SGetClass(), 0, sMarkStatics); } void ByteArray_obj::__boot() { hx::Static(_float_of_bytes) = ::cpp::Lib_obj::load(HX_CSTRING("std"),HX_CSTRING("float_of_bytes"),(int)2); hx::Static(_double_of_bytes) = ::cpp::Lib_obj::load(HX_CSTRING("std"),HX_CSTRING("double_of_bytes"),(int)2); hx::Static(_float_bytes) = ::cpp::Lib_obj::load(HX_CSTRING("std"),HX_CSTRING("float_bytes"),(int)2); hx::Static(_double_bytes) = ::cpp::Lib_obj::load(HX_CSTRING("std"),HX_CSTRING("double_bytes"),(int)2); hx::Static(factory); hx::Static(resize); hx::Static(slen); hx::Static(bytes); hx::Static(nme_byte_array_overwrite_file) = ::nme::Loader_obj::load(HX_CSTRING("nme_byte_array_overwrite_file"),(int)2); hx::Static(nme_byte_array_read_file) = ::nme::Loader_obj::load(HX_CSTRING("nme_byte_array_read_file"),(int)1); } } // end namespace nme } // end namespace utils
[ [ [ 1, 1029 ] ] ]
4b093a4bec862a4644cdb986a860cc2931da9bfa
444a151706abb7bbc8abeb1f2194a768ed03f171
/trunk/ENIGMAsystem/SHELL/Graphics_Systems/OpenGL/GSfont.cpp
a07d5e8b8936c040d9c1a2674280730ead654a36
[]
no_license
amorri40/Enigma-Game-Maker
9d01f70ab8de42f7c80af9a0f8c7a66e412d19d6
c6b701201b6037f2eb57c6938c184a5d4ba917cf
refs/heads/master
2021-01-15T11:48:39.834788
2011-11-22T04:09:28
2011-11-22T04:09:28
1,855,342
1
1
null
null
null
null
ISO-8859-13
C++
false
false
44,854
cpp
/** Copyright (C) 2011 Josh Ventura, Harijs Grīnbergs *** *** This file is a part of the ENIGMA Development Environment. *** *** ENIGMA is free software: you can redistribute it and/or modify it under the *** terms of the GNU General Public License as published by the Free Software *** Foundation, version 3 of the license or any later version. *** *** This application and its source code is distributed AS-IS, WITHOUT ANY *** WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS *** FOR A PARTICULAR PURPOSE. See the GNU General Public License for more *** details. *** *** You should have received a copy of the GNU General Public License along *** with this code. If not, see <http://www.gnu.org/licenses/> **/ #include <math.h> #include <string> #include "OpenGLHeaders.h" #include "../../Universal_System/var4.h" #include "../../libEGMstd.h" #include "GScolors.h" #include "GSfont.h" #include "binding.h" using namespace std; #include "../../Universal_System/fontstruct.h" #define __GETR(x) ((x & 0x0000FF)) #define __GETG(x) ((x & 0x00FF00) >> 8) #define __GETB(x) ((x & 0xFF0000) >> 16) namespace enigma { static int currentfont = -1; extern size_t font_idmax; } using namespace enigma; /*const int fa_left = 0; const int fa_center = 1; const int fa_right = 2; const int fa_top = 0; const int fa_middle = 1; const int fa_bottom = 2;*/ unsigned halign = fa_left; //default alignment unsigned valign = fa_top; //default alignment void draw_set_halign(unsigned align){ halign = align; } void draw_set_valign(unsigned align){ valign = align; } unsigned draw_get_halign(){ return halign; } unsigned draw_get_valign(){ return valign; } #ifdef DEBUG_MODE #include "../../Widget_Systems/widgets_mandatory.h" #define get_font(fnt,id,r) \ if (id < -1 or size_t(id+1) >= (enigma::font_idmax-1) or !fontstructarray[id]) { \ show_error("Cannot access font with id " + toString(id), false); \ return r; \ } const font *const fnt = fontstructarray[id]; #define get_fontv(fnt,id) \ if (id < -1 or size_t(id+1) >= (enigma::font_idmax-1) or !fontstructarray[id]) { \ show_error("Cannot access font with id " + toString(id), false); \ return; \ } const font *const fnt = fontstructarray[id]; #define get_font_null(fnt,id,r) \ if (id < -1 or size_t(id+1) >= (enigma::font_idmax-1)) { \ show_error("Cannot access font with id " + toString(id), false); \ return r; \ } const font *const fnt = fontstructarray[id]; #else #define get_font(fnt,id,r) \ const font *const fnt = fontstructarray[id]; #define get_fontv(fnt,id) \ const font *const fnt = fontstructarray[id]; #define get_font_null(fnt,id,r) \ const font *const fnt = fontstructarray[id]; #endif /////////////////////////////////////////////////// unsigned int string_width_line(variant vstr, int line) { string str = toString(vstr); get_font(fnt,currentfont,0); int len = 0, cl = 0; for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r'){ if (cl == line) return len; cl += 1; len = 0; i += str[i+1] == '\n'; } else if (str[i] == '\n'){ if (cl == line) return len; cl += 1; len = 0; } else if (str[i] == ' ') len += fnt->height/3; // FIXME: what's GM do about this? else { len += fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount].xs; } } return len; } unsigned int string_width_ext_line(variant vstr, int w, int line) { string str = toString(vstr); get_font(fnt,currentfont,0); unsigned int width = 0, tw = 0; int cl = 0; for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r') if (cl == line) return width; else width = 0, cl +=1, i += str[i+1] == '\n'; else if (str[i] == '\n') if (cl == line) return width; else width = 0, cl +=1; else if (str[i] == ' '){ width += fnt->height/3, tw = 0; for (unsigned c = i+1; c < str.length(); c++) { if (str[c] == ' ' or str[c] == '\r' or str[c] == '\n') break; tw += fnt->glyphs[(unsigned char)(str[c] - fnt->glyphstart) % fnt->glyphcount].xs; } if (width+tw >= unsigned(w) && w != -1) if (cl == line) return width; else width = 0, cl +=1; else; } else width += fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount].xs; } return width; } unsigned int string_width_ext_line_count(variant vstr, int w) { string str = toString(vstr); get_font(fnt,currentfont,0); unsigned int width = 0, tw = 0, cl = 1; for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r') width = 0, cl +=1, i += str[i+1] == '\n'; else if (str[i] == '\n') width = 0, cl +=1; else if (str[i] == ' '){ width += fnt->height/3, tw = 0; for (unsigned c = i+1; c < str.length(); c++) { if (str[c] == ' ' or str[c] == '\r' or str[c] == '\n') break; tw += fnt->glyphs[(unsigned char)(str[c] - fnt->glyphstart) % fnt->glyphcount].xs; } if (width+tw >= unsigned(w) && w != -1) width = 0, cl +=1; } else width += fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount].xs; } return cl; } unsigned int string_width(variant vstr) { string str = toString(vstr); get_font(fnt,currentfont,0); int mlen = 0, tlen = 0; for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r' or str[i] == '\n') tlen = 0; else if (str[i] == ' ') tlen += fnt->height/3; // FIXME: what's GM do about this? else { tlen += fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount].xs; if (tlen > mlen) mlen = tlen; } } return mlen; } unsigned int string_height(variant vstr) { string str = toString(vstr); get_font(fnt,currentfont,0); int hgt = fnt->height; for (unsigned i = 0; i < str.length(); i++) if (str[i] == '\r' or str[i] == '\n') hgt += fnt->height; return hgt; } unsigned int string_width_ext(variant vstr, int sep, int w) //here sep doesn't do anything, but I can't make it 'default = ""', because its the second argument { string str = toString(vstr); get_font(fnt,currentfont,0); unsigned int width = 0, maxwidth = 0; for (unsigned i = 0; i < str.length(); i++) { if (str[i] == ' '){ if (width >= unsigned(w) && w!=-1) (width>maxwidth ? maxwidth=width, width = 0 : width = 0); else width += fnt->height/3; // FIXME: what's GM do about this? } else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; width += g.xs; } } return maxwidth; } unsigned int string_height_ext(variant vstr, int sep, int w) { string str = toString(vstr); get_font(fnt,currentfont,0); unsigned int width = 0, tw = 0, height = fnt->height; for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r' or str[i] == '\n') width = 0, height += (sep+2 ? fnt->height : sep); else if (str[i] == ' '){ width += fnt->height/3; tw = 0; for (unsigned c = i+1; c < str.length(); c++) { if (str[c] == ' ' or str[i] == '\r' or str[i] == '\n') break; fontglyph &g = fnt->glyphs[(unsigned char)(str[c] - fnt->glyphstart) % fnt->glyphcount]; tw += g.xs; } if (width+tw >= unsigned(w) && w != -1) height += (sep==-1 ? fnt->height : sep), width = 0, tw = 0; } else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; width += g.xs; } } return height; } //////////////////////////////////////////////////// void draw_text(int x,int y,variant vstr) { string str = toString(vstr); get_fontv(fnt,currentfont); bind_texture(fnt->texture); int yy = valign == fa_top ? y+fnt->yoffset : valign == fa_middle ? y +fnt->yoffset - string_height(str)/2 : y + fnt->yoffset - string_height(str); if (halign == fa_left){ int xx = x; glBegin(GL_QUADS); for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r') xx = x, yy += fnt->height, i += str[i+1] == '\n'; else if (str[i] == '\n') xx = x, yy += fnt->height; else if (str[i] == ' ') xx += fnt->height/3; // FIXME: what's GM do about this? else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; glTexCoord2f(g.tx, g.ty); glVertex2i(xx + g.x, yy + g.y); glTexCoord2f(g.tx2, g.ty); glVertex2i(xx + g.x2, yy + g.y); glTexCoord2f(g.tx2, g.ty2); glVertex2i(xx + g.x2, yy + g.y2); glTexCoord2f(g.tx, g.ty2); glVertex2i(xx + g.x, yy + g.y2); xx += int(g.xs); } } glEnd(); } else { int xx = halign == fa_center ? x-int(string_width_line(str,0)/2) : x-int(string_width_line(str,0)), line = 0; glBegin(GL_QUADS); for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r'){ line +=1, yy += fnt->height, i += str[i+1] == '\n'; xx = halign == fa_center ? x-int(string_width_line(str,line)/2) : x-int(string_width_line(str,line)); } else if (str[i] == '\n'){ line +=1, yy += fnt->height; xx = halign == fa_center ? x-int(string_width_line(str,line)/2) : x-int(string_width_line(str,line)); } else if (str[i] == ' ') xx += fnt->height/3; // FIXME: what's GM do about this? else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; glTexCoord2f(g.tx, g.ty); glVertex2i(xx + g.x, yy + g.y); glTexCoord2f(g.tx2, g.ty); glVertex2i(xx + g.x2, yy + g.y); glTexCoord2f(g.tx2, g.ty2); glVertex2i(xx + g.x2, yy + g.y2); glTexCoord2f(g.tx, g.ty2); glVertex2i(xx + g.x, yy + g.y2); xx += int(g.xs); } } glEnd(); } } void draw_text_ext(int x,int y,variant vstr, int sep, int w) { string str = toString(vstr); get_fontv(fnt,currentfont); bind_texture(fnt->texture); int yy = valign == fa_top ? y+fnt->yoffset : valign == fa_middle ? y + fnt->yoffset - string_height_ext(str,sep,w)/2 : y + fnt->yoffset - string_height_ext(str,sep,w); if (halign == fa_left){ int xx = x, width = 0, tw = 0; glBegin(GL_QUADS); for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r') xx = x, yy += (sep+2 ? fnt->height : sep), i += str[i+1] == '\n'; else if (str[i] == '\n') xx = x, yy += (sep+2 ? fnt->height : sep); else if (str[i] == ' '){ xx += fnt->height/3, width = xx-x; tw = 0; for (unsigned c = i+1; c < str.length(); c++) { if (str[c] == ' ' or str[c] == '\r' or str[c] == '\n') break; fontglyph &g = fnt->glyphs[(unsigned char)(str[c] - fnt->glyphstart) % fnt->glyphcount]; tw += g.xs; } if (width+tw >= w && w != -1) xx = x, yy += (sep==-1 ? fnt->height : sep), width = 0, tw = 0; } else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; glTexCoord2f(g.tx, g.ty); glVertex2i(xx + g.x, yy + g.y); glTexCoord2f(g.tx2, g.ty); glVertex2i(xx + g.x2, yy + g.y); glTexCoord2f(g.tx2, g.ty2); glVertex2i(xx + g.x2, yy + g.y2); glTexCoord2f(g.tx, g.ty2); glVertex2i(xx + g.x, yy + g.y2); xx += int(g.xs); } } glEnd(); } else { int xx = halign == fa_center ? x-int(string_width_ext_line(str,w,0)/2) : x-int(string_width_ext_line(str,w,0)), line = 0, width = 0, tw = 0; glBegin(GL_QUADS); for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r') line += 1, xx = halign == fa_center ? x-int(string_width_ext_line(str,w,line)/2) : x-int(string_width_ext_line(str,w,line)), yy += (sep+2 ? fnt->height : sep), i += str[i+1] == '\n', width = 0; else if (str[i] == '\n') line += 1, xx = halign == fa_center ? x-int(string_width_ext_line(str,w,line)/2) : x-int(string_width_ext_line(str,w,line)), yy += (sep+2 ? fnt->height : sep), width = 0; else if (str[i] == ' '){ xx += fnt->height/3, width += fnt->height/3, tw = 0; for (unsigned c = i+1; c < str.length(); c++) { if (str[c] == ' ' or str[c] == '\r' or str[c] == '\n') break; fontglyph &g = fnt->glyphs[(unsigned char)(str[c] - fnt->glyphstart) % fnt->glyphcount]; tw += g.xs; } if (width+tw >= w && w != -1) line += 1, xx = halign == fa_center ? x-int(string_width_ext_line(str,w,line)/2) : x-int(string_width_ext_line(str,w,line)), yy += (sep==-1 ? fnt->height : sep), width = 0, tw = 0; } else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; glTexCoord2f(g.tx, g.ty); glVertex2i(xx + g.x, yy + g.y); glTexCoord2f(g.tx2, g.ty); glVertex2i(xx + g.x2, yy + g.y); glTexCoord2f(g.tx2, g.ty2); glVertex2i(xx + g.x2, yy + g.y2); glTexCoord2f(g.tx, g.ty2); glVertex2i(xx + g.x, yy + g.y2); xx += int(g.xs); width += g.xs; } } glEnd(); } } void draw_text_transformed(double x,double y,variant vstr,double xscale,double yscale,double rot) { string str = toString(vstr); get_fontv(fnt,currentfont); bind_texture(fnt->texture); rot *= M_PI/180; const float sv = sin(rot), cv = cos(rot), svx = sv*xscale, cvx = cv*xscale, svy = sv * yscale, cvy = cv*yscale, sw = fnt->height/3 * cvx, sh = fnt->height/3 * svx, chi = fnt->height * cvy, shi = fnt->height * svy; float xx, yy, tmpx, tmpy, tmpsize; if (valign == fa_top) yy = y + fnt->yoffset * cvy, xx = x + fnt->yoffset * svy; else if (valign == fa_middle) tmpsize = string_height(str), yy = y + (fnt->yoffset - tmpsize/2) * cvy, xx = x + (fnt->yoffset - tmpsize/2) * svy; else tmpsize = string_height(str), yy = y + (fnt->yoffset - tmpsize) * cvy, xx = x + (fnt->yoffset - tmpsize) * svy; tmpx = xx, tmpy = yy; if (halign == fa_left){ int lines = 0, w; glBegin(GL_QUADS); for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r') lines += 1, xx = tmpx + lines * shi, yy = tmpy + lines * chi, i += str[i+1] == '\n'; else if (str[i] == '\n') lines += 1, xx = tmpx + lines * shi, yy = tmpy + lines * chi; else if (str[i] == ' ') xx += sw, yy -= sh; else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; w = g.x2-g.x; const float lx = xx + g.y * svy; const float ly = yy + g.y * cvy; glTexCoord2f(g.tx, g.ty); glVertex2f(lx, ly); glTexCoord2f(g.tx2, g.ty); glVertex2f(lx + w * cvx, ly - w * svx); glTexCoord2f(g.tx2, g.ty2); glVertex2f(xx + w * cvx + g.y2 * svy, yy - w * svx + g.y2 * cvy); glTexCoord2f(g.tx, g.ty2); glVertex2f(xx + g.y2 * svy, yy + g.y2 * cvy); xx += int(g.xs) * cvx; yy -= int(g.xs) * svx; } } glEnd(); } else { tmpsize = string_width_line(str,0); if (halign == fa_center) xx = tmpx-tmpsize/2 * cvx, yy = tmpy+tmpsize/2 * svx; else xx = tmpx-tmpsize * cvx, yy = tmpy+tmpsize * svx; int lines = 0, w; glBegin(GL_QUADS); for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r'){ lines += 1, tmpsize = string_width_line(str,lines), i += str[i+1] == '\n'; if (halign == fa_center) xx = tmpx-tmpsize/2 * cvx + lines * shi, yy = tmpy+tmpsize/2 * svx + lines * chi; else xx = tmpx-tmpsize * cvx + lines * shi, yy = tmpy+tmpsize * svx + lines * chi; } else if (str[i] == '\n'){ lines += 1, tmpsize = string_width_line(str,lines); if (halign == fa_center) xx = tmpx-tmpsize/2 * cvx + lines * shi, yy = tmpy+tmpsize/2 * svx + lines * chi; else xx = tmpx-tmpsize * cvx + lines * shi, yy = tmpy+tmpsize * svx + lines * chi; } else if (str[i] == ' ') xx += sw, yy -= sh; else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; w = g.x2-g.x; const float lx = xx + g.y * svy; const float ly = yy + g.y * cvy; glTexCoord2f(g.tx, g.ty); glVertex2f(lx, ly); glTexCoord2f(g.tx2, g.ty); glVertex2f(lx + w * cvx, ly - w * svx); glTexCoord2f(g.tx2, g.ty2); glVertex2f(xx + w * cvx + g.y2 * svy, yy - w * svx + g.y2 * cvy); glTexCoord2f(g.tx, g.ty2); glVertex2f(xx + g.y2 * svy, yy + g.y2 * cvy); xx += int(g.xs) * cvx; yy -= int(g.xs) * svx; } } glEnd(); } } void draw_text_ext_transformed(double x,double y,variant vstr,int sep, int w, double xscale,double yscale,double rot) { string str = toString(vstr); get_fontv(fnt,currentfont); bind_texture(fnt->texture); rot *= M_PI/180; const float sv = sin(rot), cv = cos(rot), svx = sv*xscale, cvx = cv*xscale, svy = sv * yscale, cvy = cv*yscale, sw = fnt->height/3 * cvx, sh = fnt->height/3 * svx, chi = fnt->height * cvy, shi = fnt->height * svy; float xx, yy, tmpx, tmpy, wi, tmpsize; if (valign == fa_top) yy = y + fnt->yoffset * cvy, xx = x + fnt->yoffset * svy; else if (valign == fa_middle) tmpsize = string_height_ext(str,sep,w), yy = y + (fnt->yoffset - tmpsize/2) * cvy, xx = x + (fnt->yoffset - tmpsize/2) * svy; else tmpsize = string_height_ext(str,sep,w), yy = y + (fnt->yoffset - tmpsize) * cvy, xx = x + (fnt->yoffset - tmpsize) * svy; tmpx = xx, tmpy = yy; if (halign == fa_left){ int lines = 0,width = 0, tw = 0; glBegin(GL_QUADS); for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r') lines += 1, xx = tmpx + lines * shi, width = 0, yy = tmpy + lines * chi, i += str[i+1] == '\n'; else if (str[i] == '\n') lines += 1, xx = tmpx + lines * shi, width = 0, yy = tmpy + lines * chi; else if (str[i] == ' '){ xx += sw, yy -= sh; width += fnt->height/3; tw = 0; for (unsigned c = i+1; c < str.length(); c++) { if (str[c] == ' ' or str[c] == '\r' or str[c] == '\n') break; fontglyph &g = fnt->glyphs[(unsigned char)(str[c] - fnt->glyphstart) % fnt->glyphcount]; tw += g.xs; } if (width+tw >= w && w != -1) lines += 1, xx = tmpx + lines * shi, yy = tmpy + lines * chi, width = 0, tw = 0; } else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; wi = g.x2-g.x; const float lx = xx + g.y * svy; const float ly = yy + g.y * cvy; glTexCoord2f(g.tx, g.ty); glVertex2f(lx, ly); glTexCoord2f(g.tx2, g.ty); glVertex2f(lx + wi * cvx, ly - wi * svx); glTexCoord2f(g.tx2, g.ty2); glVertex2f(xx + wi * cvx + g.y2 * svy, yy - wi * svx + g.y2 * cvy); glTexCoord2f(g.tx, g.ty2); glVertex2f(xx + g.y2 * svy, yy + g.y2 * cvy); xx += int(g.xs) * cvx; yy -= int(g.xs) * svx; width += int(g.xs); } } glEnd(); } else { int lines = 0,width = 0, tw = 0; tmpsize = string_width_ext_line(str,w,0); if (halign == fa_center) xx = tmpx-tmpsize/2 * cvx, yy = tmpy+tmpsize/2 * svx; else xx = tmpx-tmpsize * cvx, yy = tmpy+tmpsize * svx; glBegin(GL_QUADS); for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r'){ lines += 1, tmpsize = string_width_ext_line(str,w,lines), width = 0, i += str[i+1] == '\n'; if (halign == fa_center) xx = tmpx-tmpsize/2 * cvx + lines * shi, yy = tmpy+tmpsize/2 * svx + lines * chi; else xx = tmpx-tmpsize * cvx + lines * shi, yy = tmpy+tmpsize * svx + lines * chi; } else if (str[i] == '\n'){ lines += 1, tmpsize = string_width_ext_line(str,w,lines), width = 0; if (halign == fa_center) xx = tmpx-tmpsize/2 * cvx + lines * shi, yy = tmpy+tmpsize/2 * svx + lines * chi; else xx = tmpx-tmpsize * cvx + lines * shi, yy = tmpy+tmpsize * svx + lines * chi; } else if (str[i] == ' '){ xx += sw, yy -= sh; width += fnt->height/3; tw = 0; for (unsigned c = i+1; c < str.length(); c++) { if (str[c] == ' ' or str[c] == '\r' or str[c] == '\n') break; fontglyph &g = fnt->glyphs[(unsigned char)(str[c] - fnt->glyphstart) % fnt->glyphcount]; tw += g.xs; } if (width+tw >= w && w != -1){ lines += 1, tmpsize = string_width_ext_line(str,w,lines); if (halign == fa_center) xx = tmpx-tmpsize/2 * cvx + lines * shi, yy = tmpy+tmpsize/2 * svx + lines * chi; else xx = tmpx-tmpsize * cvx + lines * shi, yy = tmpy+tmpsize * svx + lines * chi; width = 0, tw = 0; } } else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; wi = g.x2-g.x; const float lx = xx + g.y * svy; const float ly = yy + g.y * cvy; glTexCoord2f(g.tx, g.ty); glVertex2f(lx, ly); glTexCoord2f(g.tx2, g.ty); glVertex2f(lx + wi * cvx, ly - wi * svx); glTexCoord2f(g.tx2, g.ty2); glVertex2f(xx + wi * cvx + g.y2 * svy, yy - wi * svx + g.y2 * cvy); glTexCoord2f(g.tx, g.ty2); glVertex2f(xx + g.y2 * svy, yy + g.y2 * cvy); xx += int(g.xs) * cvx; yy -= int(g.xs) * svx; width += int(g.xs); } } glEnd(); } } void draw_text_transformed_color(double x,double y,variant vstr,double xscale,double yscale,double rot,int c1,int c2,int c3,int c4,double a) { string str = toString(vstr); get_fontv(fnt,currentfont); bind_texture(fnt->texture); rot *= M_PI/180; const float sv = sin(rot), cv = cos(rot), svx = sv*xscale, cvx = cv*xscale, svy = sv * yscale, cvy = cv*yscale, sw = fnt->height/3 * cvx, sh = fnt->height/3 * svx, chi = fnt->height * cvy, shi = fnt->height * svy; float xx, yy, tmpx, tmpy, tmpsize; int hcol1 = c1, hcol2 = c1, hcol3 = c3, hcol4 = c4, width = 0; if (valign == fa_top) yy = y + fnt->yoffset * cvy, xx = x + fnt->yoffset * svy; else if (valign == fa_middle) tmpsize = string_height(str), yy = y + (fnt->yoffset - tmpsize/2) * cvy, xx = x + (fnt->yoffset - tmpsize/2) * svy; else tmpsize = string_height(str), yy = y + (fnt->yoffset - tmpsize) * cvy, xx = x + (fnt->yoffset - tmpsize) * svy; tmpx = xx, tmpy = yy; glPushAttrib(GL_CURRENT_BIT); glBegin(GL_QUADS); if (halign == fa_left){ int lines = 0, w; tmpsize = string_width_line(str,0); for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r') lines += 1, width = 0, xx = tmpx + lines * shi, yy = tmpy + lines * chi, i += str[i+1] == '\n', tmpsize = string_width_line(str,lines); else if (str[i] == '\n') lines += 1, width = 0, xx = tmpx + lines * shi, yy = tmpy + lines * chi, tmpsize = string_width_line(str,lines); else if (str[i] == ' ') xx += sw, yy -= sh, width += fnt->height/3; else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; w = g.x2-g.x; const float lx = xx + g.y * svy; const float ly = yy + g.y * cvy; hcol1 = merge_color(c1,c2,(float)(width)/tmpsize); hcol2 = merge_color(c1,c2,(float)(width+g.xs)/tmpsize); hcol3 = merge_color(c4,c3,(float)(width)/tmpsize); hcol4 = merge_color(c4,c3,(float)(width+g.xs)/tmpsize); glColor4ub(__GETR(hcol1),__GETG(hcol1),__GETB(hcol1),char(a*255)); glTexCoord2f(g.tx, g.ty); glVertex2f(lx, ly); glColor4ub(__GETR(hcol2),__GETG(hcol2),__GETB(hcol2),char(a*255)); glTexCoord2f(g.tx2, g.ty); glVertex2f(lx + w * cvx, ly - w * svx); glColor4ub(__GETR(hcol3),__GETG(hcol3),__GETB(hcol3),char(a*255)); glTexCoord2f(g.tx2, g.ty2); glVertex2f(xx + w * cvx + g.y2 * svy, yy - w * svx + g.y2 * cvy); glColor4ub(__GETR(hcol4),__GETG(hcol4),__GETB(hcol4),char(a*255)); glTexCoord2f(g.tx, g.ty2); glVertex2f(xx + g.y2 * svy, yy + g.y2 * cvy); xx += int(g.xs) * cvx; yy -= int(g.xs) * svx; width += int(g.xs); } } } else { tmpsize = string_width_line(str,0); if (halign == fa_center) xx = tmpx-tmpsize/2 * cvx, yy = tmpy+tmpsize/2 * svx; else xx = tmpx-tmpsize * cvx, yy = tmpy+tmpsize * svx; int lines = 0, w; for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r'){ lines += 1, tmpsize = string_width_line(str,lines), i += str[i+1] == '\n', width = 0; if (halign == fa_center) xx = tmpx-tmpsize/2 * cvx + lines * shi, yy = tmpy+tmpsize/2 * svx + lines * chi; else xx = tmpx-tmpsize * cvx + lines * shi, yy = tmpy+tmpsize * svx + lines * chi; } else if (str[i] == '\n'){ lines += 1, tmpsize = string_width_line(str,lines), width = 0; if (halign == fa_center) xx = tmpx-tmpsize/2 * cvx + lines * shi, yy = tmpy+tmpsize/2 * svx + lines * chi; else xx = tmpx-tmpsize * cvx + lines * shi, yy = tmpy+tmpsize * svx + lines * chi; } else if (str[i] == ' ') xx += sw, yy -= sh, width += fnt->height/3; else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; w = g.x2-g.x; const float lx = xx + g.y * svy; const float ly = yy + g.y * cvy; hcol1 = merge_color(c1,c2,(float)(width)/tmpsize); hcol2 = merge_color(c1,c2,(float)(width+g.xs)/tmpsize); hcol3 = merge_color(c4,c3,(float)(width)/tmpsize); hcol4 = merge_color(c4,c3,(float)(width+g.xs)/tmpsize); glColor4ub(__GETR(hcol1),__GETG(hcol1),__GETB(hcol1),char(a*255)); glTexCoord2f(g.tx, g.ty); glVertex2f(lx, ly); glColor4ub(__GETR(hcol2),__GETG(hcol2),__GETB(hcol2),char(a*255)); glTexCoord2f(g.tx2, g.ty); glVertex2f(lx + w * cvx, ly - w * svx); glColor4ub(__GETR(hcol3),__GETG(hcol3),__GETB(hcol3),char(a*255)); glTexCoord2f(g.tx2, g.ty2); glVertex2f(xx + w * cvx + g.y2 * svy, yy - w * svx + g.y2 * cvy); glColor4ub(__GETR(hcol4),__GETG(hcol4),__GETB(hcol4),char(a*255)); glTexCoord2f(g.tx, g.ty2); glVertex2f(xx + g.y2 * svy, yy + g.y2 * cvy); xx += int(g.xs) * cvx; yy -= int(g.xs) * svx; width += int(g.xs); } } } glEnd(); glPopAttrib(); } void draw_text_ext_transformed_color(double x,double y,variant vstr,int sep,int w,double xscale,double yscale,double rot,int c1,int c2,int c3,int c4,double a) { string str = toString(vstr); get_fontv(fnt,currentfont); bind_texture(fnt->texture); rot *= M_PI/180; const float sv = sin(rot), cv = cos(rot), svx = sv*xscale, cvx = cv*xscale, svy = sv * yscale, cvy = cv*yscale, sw = fnt->height/3 * cvx, sh = fnt->height/3 * svx, chi = fnt->height * cvy, shi = fnt->height * svy; float xx, yy, tmpx, tmpy, tmpsize; int hcol1 = c1, hcol2 = c1, hcol3 = c3, hcol4 = c4, width = 0; if (valign == fa_top) yy = y + fnt->yoffset * cvy, xx = x + fnt->yoffset * svy; else if (valign == fa_middle) tmpsize = string_height_ext(str,sep,w), yy = y + (fnt->yoffset - tmpsize/2) * cvy, xx = x + (fnt->yoffset - tmpsize/2) * svy; else tmpsize = string_height_ext(str,sep,w), yy = y + (fnt->yoffset - tmpsize) * cvy, xx = x + (fnt->yoffset - tmpsize) * svy; tmpx = xx, tmpy = yy; glPushAttrib(GL_CURRENT_BIT); glBegin(GL_QUADS); if (halign == fa_left){ int lines = 0, tw = 0, wi; tmpsize = string_width_ext_line(str,w,0); for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r') lines += 1, width = 0, xx = tmpx + lines * shi, yy = tmpy + lines * chi, i += str[i+1] == '\n', tmpsize = string_width_ext_line(str,w,lines); else if (str[i] == '\n') lines += 1, width = 0, xx = tmpx + lines * shi, yy = tmpy + lines * chi, tmpsize = string_width_ext_line(str,w,lines); else if (str[i] == ' '){ xx += sw, yy -= sh, width += fnt->height/3; tw = 0; for (unsigned c = i+1; c < str.length(); c++) { if (str[c] == ' ' or str[c] == '\r' or str[c] == '\n') break; fontglyph &g = fnt->glyphs[(unsigned char)(str[c] - fnt->glyphstart) % fnt->glyphcount]; tw += g.xs; } if (width+tw >= w && w != -1) lines += 1, xx = tmpx + lines * shi, yy = tmpy + lines * chi, width = 0, tmpsize = string_width_ext_line(str,w,lines); } else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; wi = g.x2-g.x; const float lx = xx + g.y * svy; const float ly = yy + g.y * cvy; hcol1 = merge_color(c1,c2,(float)(width)/tmpsize); hcol2 = merge_color(c1,c2,(float)(width+g.xs)/tmpsize); hcol3 = merge_color(c4,c3,(float)(width)/tmpsize); hcol4 = merge_color(c4,c3,(float)(width+g.xs)/tmpsize); glColor4ub(__GETR(hcol1),__GETG(hcol1),__GETB(hcol1),char(a*255)); glTexCoord2f(g.tx, g.ty); glVertex2f(lx, ly); glColor4ub(__GETR(hcol2),__GETG(hcol2),__GETB(hcol2),char(a*255)); glTexCoord2f(g.tx2, g.ty); glVertex2f(lx + wi * cvx, ly - wi * svx); glColor4ub(__GETR(hcol3),__GETG(hcol3),__GETB(hcol3),char(a*255)); glTexCoord2f(g.tx2, g.ty2); glVertex2f(xx + wi * cvx + g.y2 * svy, yy - wi * svx + g.y2 * cvy); glColor4ub(__GETR(hcol4),__GETG(hcol4),__GETB(hcol4),char(a*255)); glTexCoord2f(g.tx, g.ty2); glVertex2f(xx + g.y2 * svy, yy + g.y2 * cvy); xx += int(g.xs) * cvx; yy -= int(g.xs) * svx; width += int(g.xs); } } } else { tmpsize = string_width_ext_line(str,w,0); if (halign == fa_center) xx = tmpx-tmpsize/2 * cvx, yy = tmpy+tmpsize/2 * svx; else xx = tmpx-tmpsize * cvx, yy = tmpy+tmpsize * svx; int lines = 0, wi, tw = 0; for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r'){ lines += 1, tmpsize = string_width_ext_line(str,w,lines), i += str[i+1] == '\n', width = 0; if (halign == fa_center) xx = tmpx-tmpsize/2 * cvx + lines * shi, yy = tmpy+tmpsize/2 * svx + lines * chi; else xx = tmpx-tmpsize * cvx + lines * shi, yy = tmpy+tmpsize * svx + lines * chi; } else if (str[i] == '\n'){ lines += 1, tmpsize = string_width_ext_line(str,w,lines), width = 0; if (halign == fa_center) xx = tmpx-tmpsize/2 * cvx + lines * shi, yy = tmpy+tmpsize/2 * svx + lines * chi; else xx = tmpx-tmpsize * cvx + lines * shi, yy = tmpy+tmpsize * svx + lines * chi; } else if (str[i] == ' '){ xx += sw, yy -= sh, width += fnt->height/3; tw = 0; for (unsigned c = i+1; c < str.length(); c++) { if (str[c] == ' ' or str[c] == '\r' or str[c] == '\n') break; fontglyph &g = fnt->glyphs[(unsigned char)(str[c] - fnt->glyphstart) % fnt->glyphcount]; tw += g.xs; } if (width+tw >= w && w != -1){ lines += 1, tmpsize = string_width_ext_line(str,w,lines); if (halign == fa_center) xx = tmpx-tmpsize/2 * cvx + lines * shi, yy = tmpy+tmpsize/2 * svx + lines * chi; else xx = tmpx-tmpsize * cvx + lines * shi, yy = tmpy+tmpsize * svx + lines * chi; width = 0; } } else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; wi = g.x2-g.x; const float lx = xx + g.y * svy; const float ly = yy + g.y * cvy; hcol1 = merge_color(c1,c2,(float)(width)/tmpsize); hcol2 = merge_color(c1,c2,(float)(width+g.xs)/tmpsize); hcol3 = merge_color(c4,c3,(float)(width)/tmpsize); hcol4 = merge_color(c4,c3,(float)(width+g.xs)/tmpsize); glColor4ub(__GETR(hcol1),__GETG(hcol1),__GETB(hcol1),char(a*255)); glTexCoord2f(g.tx, g.ty); glVertex2f(lx, ly); glColor4ub(__GETR(hcol2),__GETG(hcol2),__GETB(hcol2),char(a*255)); glTexCoord2f(g.tx2, g.ty); glVertex2f(lx + wi * cvx, ly - wi * svx); glColor4ub(__GETR(hcol3),__GETG(hcol3),__GETB(hcol3),char(a*255)); glTexCoord2f(g.tx2, g.ty2); glVertex2f(xx + wi * cvx + g.y2 * svy, yy - wi * svx + g.y2 * cvy); glColor4ub(__GETR(hcol4),__GETG(hcol4),__GETB(hcol4),char(a*255)); glTexCoord2f(g.tx, g.ty2); glVertex2f(xx + g.y2 * svy, yy + g.y2 * cvy); xx += int(g.xs) * cvx; yy -= int(g.xs) * svx; width += int(g.xs); } } } glEnd(); glPopAttrib(); } void draw_text_color(int x,int y,variant vstr,int c1,int c2,int c3,int c4,double a) { string str = toString(vstr); get_fontv(fnt,currentfont); bind_texture(fnt->texture); glPushAttrib(GL_CURRENT_BIT); int yy = valign == fa_top ? y+fnt->yoffset : valign == fa_middle ? y +fnt->yoffset - string_height(str)/2 : y + fnt->yoffset - string_height(str); int hcol1 = c1, hcol2 = c1, hcol3 = c3, hcol4 = c4, line = 0, sw = string_width_line(str, line); float tx1, tx2; glBegin(GL_QUADS); if (halign == fa_left){ int xx = x; for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r'){ xx = x, yy += fnt->height, i += str[i+1] == '\n'; line += 1; sw = string_width_line(str, line); } else if (str[i] == '\n'){ xx = x, yy += fnt->height; line += 1; sw = string_width_line(str, line); } else if (str[i] == ' ') xx += fnt->height/3; // FIXME: what's GM do about this? else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; tx1 = (float)(xx-x)/sw, tx2 = (float)(xx+g.xs-x)/sw; hcol1 = merge_color(c1,c2,tx1); hcol2 = merge_color(c1,c2,tx2); hcol3 = merge_color(c4,c3,tx1); hcol4 = merge_color(c4,c3,tx2); glColor4ub(__GETR(hcol1),__GETG(hcol1),__GETB(hcol1),char(a*255)); glTexCoord2f(g.tx, g.ty); glVertex2i(xx + g.x, yy + g.y); glColor4ub(__GETR(hcol2),__GETG(hcol2),__GETB(hcol2),char(a*255)); glTexCoord2f(g.tx2, g.ty); glVertex2i(xx + g.x2, yy + g.y); glColor4ub(__GETR(hcol3),__GETG(hcol3),__GETB(hcol3),char(a*255)); glTexCoord2f(g.tx2, g.ty2); glVertex2i(xx + g.x2, yy + g.y2); glColor4ub(__GETR(hcol4),__GETG(hcol4),__GETB(hcol4),char(a*255)); glTexCoord2f(g.tx, g.ty2); glVertex2i(xx + g.x, yy + g.y2); xx += int(g.xs); } } } else { int xx = halign == fa_center ? x-sw/2 : x-sw, tmpx = xx; for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r'){ yy += fnt->height, i += str[i+1] == '\n', line += 1, sw = string_width_line(str, line), xx = halign == fa_center ? x-sw/2 : x-sw, tmpx = xx; } else if (str[i] == '\n'){ yy += fnt->height, line += 1, sw = string_width_line(str, line), xx = halign == fa_center ? x-sw/2 : x-sw, tmpx = xx; } else if (str[i] == ' ') xx += fnt->height/3; // FIXME: what's GM do about this? else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; tx1 = (float)(xx-tmpx)/sw, tx2 = (float)(xx+g.xs-tmpx)/sw; //tx1 = (float)tmpx/sw, tx2 = (float)(tmpx+g.xs)/sw; hcol1 = merge_color(c1,c2,tx1); hcol2 = merge_color(c1,c2,tx2); hcol3 = merge_color(c4,c3,tx1); hcol4 = merge_color(c4,c3,tx2); glColor4ub(__GETR(hcol1),__GETG(hcol1),__GETB(hcol1),char(a*255)); glTexCoord2f(g.tx, g.ty); glVertex2i(xx + g.x, yy + g.y); glColor4ub(__GETR(hcol2),__GETG(hcol2),__GETB(hcol2),char(a*255)); glTexCoord2f(g.tx2, g.ty); glVertex2i(xx + g.x2, yy + g.y); glColor4ub(__GETR(hcol3),__GETG(hcol3),__GETB(hcol3),char(a*255)); glTexCoord2f(g.tx2, g.ty2); glVertex2i(xx + g.x2, yy + g.y2); glColor4ub(__GETR(hcol4),__GETG(hcol4),__GETB(hcol4),char(a*255)); glTexCoord2f(g.tx, g.ty2); glVertex2i(xx + g.x, yy + g.y2); xx += int(g.xs); } } } glEnd(); glPopAttrib(); } void draw_text_ext_color(int x,int y,variant vstr,int sep, int w, int c1,int c2,int c3,int c4,double a) { string str = toString(vstr); get_fontv(fnt,currentfont); bind_texture(fnt->texture); glPushAttrib(GL_CURRENT_BIT); int yy = valign == fa_top ? y+fnt->yoffset : valign == fa_middle ? y + fnt->yoffset - string_height_ext(str,sep,w)/2 : y + fnt->yoffset - string_height_ext(str,sep,w); int width = 0, tw = 0, hcol1 = c1, hcol2 = c1, hcol3 = c3, hcol4 = c4, line = 0, sw = string_width_ext_line(str, w, line); glBegin(GL_QUADS); if (halign == fa_left){ int xx = x; for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r') xx = x, yy += (sep+2 ? fnt->height : sep), i += str[i+1] == '\n', width = 0, line += 1, sw = string_width_ext_line(str, w, line); else if (str[i] == '\n') xx = x, yy += (sep+2 ? fnt->height : sep), width = 0, line += 1, sw = string_width_ext_line(str, w, line); else if (str[i] == ' '){ xx += fnt->height/3; width = xx-x; tw = 0; for (unsigned c = i+1; c < str.length(); c++) { if (str[c] == ' ' or str[c] == '\r' or str[c] == '\n') break; fontglyph &g = fnt->glyphs[(unsigned char)(str[c] - fnt->glyphstart) % fnt->glyphcount]; tw += g.xs; } if (width+tw >= w && w != -1) xx = x, yy += (sep==-1 ? fnt->height : sep), width = 0, line += 1, sw = string_width_ext_line(str, w, line); } else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; hcol1 = merge_color(c1,c2,(float)(width)/sw); hcol2 = merge_color(c1,c2,(float)(width+g.xs)/sw); hcol3 = merge_color(c4,c3,(float)(width)/sw); hcol4 = merge_color(c4,c3,(float)(width+g.xs)/sw); glColor4ub(__GETR(hcol1),__GETG(hcol1),__GETB(hcol1),char(a*255)); glTexCoord2f(g.tx, g.ty); glVertex2i(xx + g.x, yy + g.y); glColor4ub(__GETR(hcol2),__GETG(hcol2),__GETB(hcol2),char(a*255)); glTexCoord2f(g.tx2, g.ty); glVertex2i(xx + g.x2, yy + g.y); glColor4ub(__GETR(hcol3),__GETG(hcol3),__GETB(hcol3),char(a*255)); glTexCoord2f(g.tx2, g.ty2); glVertex2i(xx + g.x2, yy + g.y2); glColor4ub(__GETR(hcol4),__GETG(hcol4),__GETB(hcol4),char(a*255)); glTexCoord2f(g.tx, g.ty2); glVertex2i(xx + g.x, yy + g.y2); xx += int(g.xs); width = xx-x; } } } else { int xx = halign == fa_center ? x-sw/2 : x-sw, tmpx = xx; for (unsigned i = 0; i < str.length(); i++) { if (str[i] == '\r') yy += (sep+2 ? fnt->height : sep), i += str[i+1] == '\n', width = 0, line += 1, sw = string_width_ext_line(str, w, line), xx = halign == fa_center ? x-sw/2 : x-sw, tmpx = xx; else if (str[i] == '\n') yy += (sep+2 ? fnt->height : sep), width = 0, line += 1, sw = string_width_ext_line(str, w, line), xx = halign == fa_center ? x-sw/2 : x-sw, tmpx = xx; else if (str[i] == ' '){ xx += fnt->height/3, width = xx-tmpx, tw = 0; for (unsigned c = i+1; c < str.length(); c++) { if (str[c] == ' ' or str[c] == '\r' or str[c] == '\n') break; fontglyph &g = fnt->glyphs[(unsigned char)(str[c] - fnt->glyphstart) % fnt->glyphcount]; tw += g.xs; } if (width+tw >= w && w != -1) yy += (sep==-1 ? fnt->height : sep), width = 0, line += 1, sw = string_width_ext_line(str, w, line), xx = halign == fa_center ? x-sw/2 : x-sw, tmpx = xx; } else { fontglyph &g = fnt->glyphs[(unsigned char)(str[i] - fnt->glyphstart) % fnt->glyphcount]; hcol1 = merge_color(c1,c2,(float)(width)/sw); hcol2 = merge_color(c1,c2,(float)(width+g.xs)/sw); hcol3 = merge_color(c4,c3,(float)(width)/sw); hcol4 = merge_color(c4,c3,(float)(width+g.xs)/sw); glColor4ub(__GETR(hcol1),__GETG(hcol1),__GETB(hcol1),char(a*255)); glTexCoord2f(g.tx, g.ty); glVertex2i(xx + g.x, yy + g.y); glColor4ub(__GETR(hcol2),__GETG(hcol2),__GETB(hcol2),char(a*255)); glTexCoord2f(g.tx2, g.ty); glVertex2i(xx + g.x2, yy + g.y); glColor4ub(__GETR(hcol3),__GETG(hcol3),__GETB(hcol3),char(a*255)); glTexCoord2f(g.tx2, g.ty2); glVertex2i(xx + g.x2, yy + g.y2); glColor4ub(__GETR(hcol4),__GETG(hcol4),__GETB(hcol4),char(a*255)); glTexCoord2f(g.tx, g.ty2); glVertex2i(xx + g.x, yy + g.y2); xx += int(g.xs); width = xx-tmpx; } } } glEnd(); glPopAttrib(); } unsigned int font_get_texture(int fnt) { get_font_null(f,fnt,-1); return f ? f->texture : unsigned(-1); } unsigned int font_get_texture_width(int fnt) { get_font_null(f,fnt,-1); return f ? f->twid: unsigned(-1); } unsigned int font_get_texture_height(int fnt) { get_font_null(f,fnt,-1); return f ? f->thgt: unsigned(-1); } void draw_set_font(int fnt) { enigma::currentfont = fnt; } int draw_get_font() { return enigma::currentfont; }
[ [ [ 1, 1145 ] ] ]
558929ca6c93deca1c2c6287c92415495384e0a4
cfa667b1f83649600e78ea53363ee71dfb684d81
/code/render/coregraphics/d3d9/d3d9renderdevice.cc
8ce471f2390697ecb05c0150a86eeea2f8ce30f0
[]
no_license
zhouxh1023/nebuladevice3
c5f98a9e2c02828d04fb0e1033f4fce4119e1b9f
3a888a7c6e6d1a2c91b7ebd28646054e4c9fc241
refs/heads/master
2021-01-23T08:56:15.823698
2011-08-26T02:22:25
2011-08-26T02:22:25
32,018,644
0
1
null
null
null
null
UTF-8
C++
false
false
27,176
cc
//------------------------------------------------------------------------------ // d3d9renderdevice.cc // (C) 2007 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "coregraphics/config.h" #include "coregraphics/d3d9/d3d9renderdevice.h" #include "coregraphics/displaydevice.h" #include "coregraphics/vertexbuffer.h" #include "coregraphics/indexbuffer.h" #include "coregraphics/win360/d3d9types.h" #include "coregraphics/d3d9/d3d9resourceeventhandler.h" #include "timing/time.h" #include <dxerr.h> namespace Direct3D9 { __ImplementClass(Direct3D9::D3D9RenderDevice, 'D9RD', Base::RenderDeviceBase); __ImplementSingleton(Direct3D9::D3D9RenderDevice); using namespace Win360; using namespace CoreGraphics; IDirect3D9* D3D9RenderDevice::d3d9 = 0; //------------------------------------------------------------------------------ /** */ D3D9RenderDevice::D3D9RenderDevice() : d3d9Device(0), adapter(0), displayFormat(D3DFMT_X8R8G8B8), deviceBehaviourFlags(0), frameId(0) { __ConstructSingleton; Memory::Clear(&this->presentParams, sizeof(this->presentParams)); Memory::Clear(&this->d3d9DeviceCaps, sizeof(this->d3d9DeviceCaps)); this->OpenDirect3D(); } //------------------------------------------------------------------------------ /** */ D3D9RenderDevice::~D3D9RenderDevice() { if (this->IsOpen()) { this->Close(); } this->CloseDirect3D(); __DestructSingleton; } //------------------------------------------------------------------------------ /** Get a pointer to the Direct3D interface. Opens Direct3D if not happened yet. */ IDirect3D9* D3D9RenderDevice::GetDirect3D() { OpenDirect3D(); n_assert(0 != d3d9); return d3d9; } //------------------------------------------------------------------------------ /** Test if the right Direct3D version is installed by trying to open Direct3D. */ bool D3D9RenderDevice::CanCreate() { OpenDirect3D(); return (0 != d3d9); } //------------------------------------------------------------------------------ /** Return a pointer to d3d device. Asserts that the device exists. */ IDirect3DDevice9* D3D9RenderDevice::GetDirect3DDevice() const { n_assert(0 != this->d3d9Device); return this->d3d9Device; } //------------------------------------------------------------------------------ /** Open Direct3D. This method is called by the constructor. If you're not sure whether Direct3D is supported on this machine, use the static CanCreate() method to check before creating the D3D9RenderDevice object. Note that this method may also be called by D3D9DisplayDevice because it needs access to the machine's adapters. */ void D3D9RenderDevice::OpenDirect3D() { if (0 == d3d9) { d3d9 = Direct3DCreate9(D3D_SDK_VERSION); } } //------------------------------------------------------------------------------ /** Close Direct3D9. This method is exclusively called by the destructor. */ void D3D9RenderDevice::CloseDirect3D() { if (0 != d3d9) { d3d9->Release(); d3d9 = 0; } } //------------------------------------------------------------------------------ /** Open the render device. When successful, the RenderEvent::DeviceOpen will be sent to all registered event handlers after the Direct3D device has been opened. */ bool D3D9RenderDevice::Open() { n_assert(!this->IsOpen()); this->AttachEventHandler(D3D9ResourceEventHandler::Create()); bool success = false; if (this->OpenDirect3DDevice()) { // hand to parent class, this will notify event handlers success = RenderDeviceBase::Open(); } return success; } //------------------------------------------------------------------------------ /** Close the render device. The RenderEvent::DeviceClose will be sent to all registered event handlers. */ void D3D9RenderDevice::Close() { n_assert(this->IsOpen()); RenderDeviceBase::Close(); this->CloseDirect3DDevice(); this->RemoveEventHandler(D3D9ResourceEventHandler::Instance()); } //------------------------------------------------------------------------------ /** This selects the adapter to use for the render device. This method will set the "adapter" member and the d3d9 device caps member. */ void D3D9RenderDevice::SetupAdapter() { n_assert(0 != this->d3d9); DisplayDevice* displayDevice = DisplayDevice::Instance(); Adapter::Code requestedAdapter = displayDevice->GetAdapter(); n_assert(displayDevice->AdapterExists(requestedAdapter)); #if NEBULA3_DIRECT3D_USENVPERFHUD this->adapter = this->d3d9->GetAdapterCount() - 1; #else this->adapter = (UINT) requestedAdapter; #endif HRESULT hr = this->d3d9->GetDeviceCaps(this->adapter, NEBULA3_DIRECT3D_DEVICETYPE, &(this->d3d9DeviceCaps)); n_assert(SUCCEEDED(hr)); } //------------------------------------------------------------------------------ /** Select the display, back buffer and depth buffer formats and update the presentParams member. */ void D3D9RenderDevice::SetupBufferFormats() { HRESULT hr; n_assert(0 != this->d3d9); DisplayDevice* displayDevice = DisplayDevice::Instance(); if (displayDevice->IsFullscreen()) { if (displayDevice->IsTripleBufferingEnabled()) { this->presentParams.BackBufferCount = 2; } else { this->presentParams.BackBufferCount = 1; } if (displayDevice->IsDisplayModeSwitchEnabled()) { this->presentParams.Windowed = FALSE; } else { this->presentParams.Windowed = TRUE; } } else { // windowed mode this->presentParams.BackBufferCount = 1; this->presentParams.Windowed = TRUE; } D3DFORMAT backbufferPixelFormat; if (this->presentParams.Windowed) { // windowed mode: use desktop pixel format backbufferPixelFormat = D3D9Types::AsD3D9PixelFormat(displayDevice->GetCurrentAdapterDisplayMode((Adapter::Code)this->adapter).GetPixelFormat()); } else { // fullscreen: use requested pixel format backbufferPixelFormat = D3D9Types::AsD3D9PixelFormat(displayDevice->GetDisplayMode().GetPixelFormat()); } // make sure the device supports a D24S8 depth buffers hr = this->d3d9->CheckDeviceFormat(this->adapter, NEBULA3_DIRECT3D_DEVICETYPE, backbufferPixelFormat, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, D3DFMT_D24S8); if (FAILED(hr)) { n_error("Rendering device doesn't support D24S8 depth buffer!\n"); return; } // check that the depth buffer format is compatible with the backbuffer format hr = this->d3d9->CheckDepthStencilMatch(this->adapter, NEBULA3_DIRECT3D_DEVICETYPE, backbufferPixelFormat, backbufferPixelFormat, D3DFMT_D24S8); if (FAILED(hr)) { n_error("Backbuffer format not compatible with D24S8 depth buffer!\n"); return; } // fill presentParams this->presentParams.BackBufferFormat = backbufferPixelFormat; this->presentParams.BackBufferWidth = displayDevice->GetDisplayMode().GetWidth(); this->presentParams.BackBufferHeight = displayDevice->GetDisplayMode().GetHeight(); this->presentParams.EnableAutoDepthStencil = FALSE; this->presentParams.AutoDepthStencilFormat = D3DFMT_D24S8; } //------------------------------------------------------------------------------ /** Set the deviceBehaviour member to a suitable value. */ void D3D9RenderDevice::SetupDeviceBehaviour() { #if NEBULA3_DIRECT3D_DEBUG this->deviceBehaviourFlags = D3DCREATE_FPU_PRESERVE | D3DCREATE_SOFTWARE_VERTEXPROCESSING; #else this->deviceBehaviourFlags = D3DCREATE_FPU_PRESERVE; if (this->d3d9DeviceCaps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) { this->deviceBehaviourFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING; } else { this->deviceBehaviourFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; } #endif } //------------------------------------------------------------------------------ /** Setup the (remaining) presentation parameters. This will initialize the presentParams member. */ void D3D9RenderDevice::SetupPresentParams() { DisplayDevice* displayDevice = DisplayDevice::Instance(); n_assert(displayDevice->IsOpen()); #if NEBULA3_DIRECT3D_DEBUG this->presentParams.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; #else this->presentParams.Flags = 0; #endif if (displayDevice->IsVerticalSyncEnabled()) { this->presentParams.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT; } else { this->presentParams.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; } this->presentParams.SwapEffect = D3DSWAPEFFECT_DISCARD; this->presentParams.hDeviceWindow = displayDevice->GetHwnd(); this->presentParams.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; this->presentParams.MultiSampleType = D3DMULTISAMPLE_NONE; this->presentParams.MultiSampleQuality = 0; } //------------------------------------------------------------------------------ /** Initialize the Direct3D device with initial device state. */ void D3D9RenderDevice::SetInitialDeviceState() { n_assert(this->d3d9Device); this->d3d9Device->SetRenderState(D3DRS_DITHERENABLE, FALSE); this->d3d9Device->SetRenderState(D3DRS_LIGHTING, FALSE); // setup viewport D3DVIEWPORT9 viewPort; viewPort.Width = this->presentParams.BackBufferWidth; viewPort.Height = this->presentParams.BackBufferHeight; viewPort.X = 0; viewPort.Y = 0; viewPort.MinZ = 0.0f; viewPort.MaxZ = 1.0f; this->d3d9Device->SetViewport(&viewPort); } //------------------------------------------------------------------------------ /** Open the Direct3D device. This will completely setup the device into a usable state. */ bool D3D9RenderDevice::OpenDirect3DDevice() { n_assert(0 != this->d3d9); n_assert(0 == this->d3d9Device); HRESULT hr; DisplayDevice* displayDevice = DisplayDevice::Instance(); n_assert(displayDevice->IsOpen()); // setup device creation parameters Memory::Clear(&this->presentParams, sizeof(this->presentParams)); this->SetupAdapter(); this->SetupBufferFormats(); this->SetupDeviceBehaviour(); this->SetupPresentParams(); // create device hr = this->d3d9->CreateDevice(this->adapter, NEBULA3_DIRECT3D_DEVICETYPE, displayDevice->GetHwnd(), this->deviceBehaviourFlags, &(this->presentParams), &(this->d3d9Device)); if (FAILED(hr)) { n_error("Failed to create Direct3D device object: %s!\n", DXGetErrorString(hr)); return false; } // get actual device caps this->d3d9Device->GetDeviceCaps(&this->d3d9DeviceCaps); // set initial device state this->SetInitialDeviceState(); // create queries this->SetupQueries(); return true; } //------------------------------------------------------------------------------ /** Close the Direct3D device. */ void D3D9RenderDevice::CloseDirect3DDevice() { n_assert(0 != this->d3d9); n_assert(0 != this->d3d9Device); this->UnbindD3D9Resources(); IndexT i; for (i = 1; i < 4; i++) { this->d3d9Device->SetRenderTarget(i, NULL); } this->d3d9Device->SetDepthStencilSurface(NULL); // release queries this->DiscardQueries(); // release the Direct3D device this->d3d9Device->Release(); this->d3d9Device = 0; } //------------------------------------------------------------------------------ /** This catches the lost device state, and tries to restore a lost device. The method will send out the events DeviceLost and DeviceRestored. Resources should react to these events accordingly. As long as the device is in an invalid state, the method will return false. This method is called by BeginFrame(). */ void D3D9RenderDevice::ResetDevice() { n_assert(0 != this->d3d9Device); // notify event handlers that the device was lost this->NotifyEventHandlers(RenderEvent(RenderEvent::DeviceLost)); this->DiscardQueries(); // if we are in windowed mode, the cause for the lost // device may be a desktop display mode switch, in this // case we need to find new buffer formats if (this->presentParams.Windowed) { this->SetupBufferFormats(); } #if 0 HRESULT hr = this->d3d9Device->TestCooperativeLevel(); while ((hr != S_OK) && (hr != D3DERR_DEVICENOTRESET)) { Timing::Sleep(0.01); } // try to reset the device hr = this->d3d9Device->Reset(&this->presentParams); n_assert(SUCCEEDED(hr)); #else // it seems that the TestCooperativeLevel() always return D3DERR_DEVICELOST on Win7? HRESULT hr = E_FAIL; while (S_OK != hr) { hr = this->d3d9Device->Reset(&this->presentParams); Timing::Sleep(0.01); } #endif // set initial device state this->SetInitialDeviceState(); // send the DeviceRestored event this->NotifyEventHandlers(RenderEvent(RenderEvent::DeviceRestored)); this->SetupQueries(); } //------------------------------------------------------------------------------ /** Begin a complete frame. Call this once per frame before any rendering happens. If rendering is not possible for some reason (e.g. a lost device) the method will return false. This method may also send the DeviceLost and DeviceRestored RenderEvents to attached event handlers. */ bool D3D9RenderDevice::BeginFrame() { n_assert(this->d3d9Device); if (RenderDeviceBase::BeginFrame()) { HRESULT hr = this->d3d9Device->BeginScene(); n_assert(SUCCEEDED(hr)); return true; } return false; } //------------------------------------------------------------------------------ /** End a complete frame. Call this once per frame after rendering has happened and before Present(), and only if BeginFrame() returns true. */ void D3D9RenderDevice::EndFrame() { RenderDeviceBase::EndFrame(); HRESULT hr = this->d3d9Device->EndScene(); n_assert(SUCCEEDED(hr)); this->UnbindD3D9Resources(); } //------------------------------------------------------------------------------ /** End the current rendering pass. This will flush all texture stages in order to keep the d3d9 resource reference counts consistent without too much hassle. */ void D3D9RenderDevice::EndPass() { this->UnbindD3D9Resources(); RenderDeviceBase::EndPass(); } //------------------------------------------------------------------------------ /** NOTE: Present() should be called as late as possible after EndFrame() to improve parallelism between the GPU and the CPU. */ void D3D9RenderDevice::Present() { RenderDeviceBase::Present(); // present backbuffer... n_assert(0 != this->d3d9Device); if (0 != D3D9DisplayDevice::Instance()->GetHwnd()) { HRESULT hr = this->d3d9Device->Present(NULL, NULL, 0, NULL); if (D3DERR_DEVICELOST == hr) { this->ResetDevice(); } else { n_assert(SUCCEEDED(hr)); } } // sync cpu thread with gpu this->SyncGPU(); } //------------------------------------------------------------------------------ /** Sets the vertex buffer to use for the next Draw(). */ void D3D9RenderDevice::SetStreamSource(IndexT streamIndex, const Ptr<VertexBuffer>& vb, IndexT offsetVertexIndex) { n_assert((streamIndex >= 0) && (streamIndex < MaxNumVertexStreams)); n_assert(this->inBeginPass); n_assert(0 != this->d3d9Device); n_assert(vb.isvalid()); if ((this->streamVertexBuffers[streamIndex] != vb) || (this->streamVertexOffsets[streamIndex] != offsetVertexIndex)) { HRESULT hr; IDirect3DVertexBuffer9* d3d9VertexBuffer = vb->GetD3D9VertexBuffer(); DWORD vertexByteSize = vb->GetVertexLayout()->GetVertexByteSize(); DWORD vertexByteOffset = offsetVertexIndex * vertexByteSize; hr = this->d3d9Device->SetStreamSource(streamIndex, d3d9VertexBuffer, vertexByteOffset, vertexByteSize); n_assert(SUCCEEDED(hr)); } RenderDeviceBase::SetStreamSource(streamIndex, vb, offsetVertexIndex); } //------------------------------------------------------------------------------ /** Sets the vertex layout for the next Draw() */ void D3D9RenderDevice::SetVertexLayout(const Ptr<VertexLayout>& vl) { n_assert(this->inBeginPass); n_assert(0 != this->d3d9Device); n_assert(vl.isvalid()); if (this->vertexLayout != vl) { HRESULT hr; IDirect3DVertexDeclaration9* d3d9VertexDecl = vl->GetD3D9VertexDeclaration(); hr = this->d3d9Device->SetVertexDeclaration(d3d9VertexDecl); n_assert(SUCCEEDED(hr)); } RenderDeviceBase::SetVertexLayout(vl); } //------------------------------------------------------------------------------ /** Sets the index buffer to use for the next Draw(). */ void D3D9RenderDevice::SetIndexBuffer(const Ptr<IndexBuffer>& ib) { n_assert(this->inBeginPass); n_assert(0 != this->d3d9Device); n_assert(ib.isvalid()); if (this->indexBuffer != ib) { HRESULT hr; // set the index buffer on the d3d device IDirect3DIndexBuffer9* d3d9IndexBuffer = ib->GetD3D9IndexBuffer(); hr = this->d3d9Device->SetIndices(d3d9IndexBuffer); n_assert(SUCCEEDED(hr)); } RenderDeviceBase::SetIndexBuffer(ib); } //------------------------------------------------------------------------------ /** Draw the current primitive group. Requires a vertex buffer, an optional index buffer and a primitive group to be set through the respective methods. To use non-indexed rendering, set the number of indices in the primitive group to 0. */ void D3D9RenderDevice::Draw() { n_assert(this->inBeginPass); n_assert(0 != this->d3d9Device); D3DPRIMITIVETYPE d3dPrimType = D3D9Types::AsD3D9PrimitiveType(this->primitiveGroup.GetPrimitiveTopology()); if (this->primitiveGroup.GetNumIndices() > 0) { // use indexed rendering HRESULT hr; hr = this->d3d9Device->DrawIndexedPrimitive( d3dPrimType, // Type 0, // BaseVertexIndex this->primitiveGroup.GetBaseVertex(), // MinIndex this->primitiveGroup.GetNumVertices(), // NumVertices this->primitiveGroup.GetBaseIndex(), // StartIndex this->primitiveGroup.GetNumPrimitives()); // PrimitiveCount n_assert(SUCCEEDED(hr)); } else { // use non-indexed rendering HRESULT hr; hr = this->d3d9Device->DrawPrimitive( d3dPrimType, // Type this->primitiveGroup.GetBaseVertex(), // StartVertex this->primitiveGroup.GetNumPrimitives()); // PrimitiveCount n_assert(SUCCEEDED(hr)); } // update debug stats _incr_counter(RenderDeviceNumPrimitives, this->primitiveGroup.GetNumPrimitives()); _incr_counter(RenderDeviceNumDrawCalls, 1); } //------------------------------------------------------------------------------ /** Draw N instances of the current primitive group. Requires the following setup: - vertex stream 0: vertex buffer with instancing data, one vertex per instance - vertex stream 1: vertex buffer with instance geometry data - index buffer: index buffer for geometry data - primitive group: the primitive group which describes one instance - vertex declaration: describes a combined vertex from stream 0 and stream 1 */ void D3D9RenderDevice::DrawIndexedInstanced(SizeT numInstances) { n_assert(this->inBeginPass); n_assert(numInstances > 0); n_assert(0 != this->d3d9Device); this->d3d9Device->SetStreamSourceFreq(0, D3DSTREAMSOURCE_INDEXEDDATA | numInstances); this->d3d9Device->SetStreamSourceFreq(1, D3DSTREAMSOURCE_INSTANCEDATA | 1); D3DPRIMITIVETYPE d3dPrimType = D3D9Types::AsD3D9PrimitiveType(this->primitiveGroup.GetPrimitiveTopology()); n_assert(this->primitiveGroup.GetNumIndices() > 0); HRESULT hr; hr = this->d3d9Device->DrawIndexedPrimitive( d3dPrimType, // Type 0, // BaseVertexIndex this->primitiveGroup.GetBaseVertex(), // MinIndex this->primitiveGroup.GetNumVertices(), // NumVertices this->primitiveGroup.GetBaseIndex(), // StartIndex this->primitiveGroup.GetNumPrimitives()); // PrimitiveCount n_assert(SUCCEEDED(hr)); this->d3d9Device->SetStreamSourceFreq(0, 1); this->d3d9Device->SetStreamSourceFreq(1, 1); // update debug stats _incr_counter(RenderDeviceNumPrimitives, this->primitiveGroup.GetNumPrimitives() * numInstances); _incr_counter(RenderDeviceNumDrawCalls, 1); } //------------------------------------------------------------------------------ /** Save the backbuffer to the provided stream. */ ImageFileFormat::Code D3D9RenderDevice::SaveScreenshot(ImageFileFormat::Code fmt, const Ptr<IO::Stream>& outStream) { n_assert(!this->inBeginFrame); n_assert(0 != this->d3d9Device); HRESULT hr; // create a plain offscreen surface to capture data to IDirect3DSurface9* captureSurface = NULL; hr = this->d3d9Device->CreateOffscreenPlainSurface(this->presentParams.BackBufferWidth, // Width this->presentParams.BackBufferHeight, // Height this->presentParams.BackBufferFormat, // Format D3DPOOL_SYSTEMMEM, // Pool &captureSurface, // ppSurface NULL); // pSharedHandle n_assert(SUCCEEDED(hr)); n_assert(0 != captureSurface); // get the back buffer surface IDirect3DSurface9* backBufferSurface = 0; hr = this->d3d9Device->GetBackBuffer(0,0, D3DBACKBUFFER_TYPE_MONO, &backBufferSurface); n_assert(SUCCEEDED(hr)); // capture backbuffer to offscreen surface hr = this->d3d9Device->GetRenderTargetData(backBufferSurface, captureSurface); n_assert(SUCCEEDED(hr)); backBufferSurface->Release(); // finally save the image to the provided stream D3DXIMAGE_FILEFORMAT d3dxFmt= D3D9Types::AsD3DXImageFileFormat(fmt); ID3DXBuffer* d3dxBuffer = 0; hr = D3DXSaveSurfaceToFileInMemory(&d3dxBuffer, // ppDestBuf d3dxFmt, // DestFormat captureSurface, // pSrcSurface, NULL, // pSrcPalette NULL); // pSrcRect n_assert(SUCCEEDED(hr)); captureSurface->Release(); // write result to stream void* dataPtr = d3dxBuffer->GetBufferPointer(); DWORD dataSize = d3dxBuffer->GetBufferSize(); outStream->SetAccessMode(IO::Stream::WriteAccess); if (outStream->Open()) { outStream->Write(dataPtr, dataSize); outStream->Close(); outStream->SetMediaType(ImageFileFormat::ToMediaType(fmt)); } d3dxBuffer->Release(); return fmt; } //------------------------------------------------------------------------------ /** Unbind all d3d9 resources from the device, this is necessary to keep the resource reference counts consistent. Should be called at the end of each rendering pass. */ void D3D9RenderDevice::UnbindD3D9Resources() { this->d3d9Device->SetVertexShader(NULL); this->d3d9Device->SetPixelShader(NULL); this->d3d9Device->SetIndices(NULL); IndexT i; for (i = 0; i < 8; i++) { this->d3d9Device->SetTexture(i, NULL); } for (i = 0; i < MaxNumVertexStreams; i++) { this->d3d9Device->SetStreamSource(i, NULL, 0, 0); this->streamVertexBuffers[i] = 0; } this->indexBuffer = 0; } //------------------------------------------------------------------------------ /** */ void D3D9RenderDevice::SyncGPU() { // sync with gpu, wait till command buffer is empty // add event to gpu command stream this->gpuSyncQuery[this->frameId % numSyncQueries]->Issue(D3DISSUE_END); this->frameId++; while (S_FALSE == this->gpuSyncQuery[this->frameId % numSyncQueries]->GetData(NULL, 0, D3DGETDATA_FLUSH)) { // wait till gpu has finsihed rendering the previous frame } } //------------------------------------------------------------------------------ void D3D9RenderDevice::DiscardQueries() { for (IndexT i = 0; i < numSyncQueries; ++i) { this->gpuSyncQuery[i]->Release(); this->gpuSyncQuery[i] = NULL; } } //------------------------------------------------------------------------------ void D3D9RenderDevice::SetupQueries() { // create double buffer query to avoid gpu to render more than 1 frame ahead IndexT i; for (i = 0; i < numSyncQueries; ++i) { this->d3d9Device->CreateQuery(D3DQUERYTYPE_EVENT, &this->gpuSyncQuery[i]); } } } // namespace CoreGraphics
[ [ [ 1, 819 ] ] ]
7629d7c813ef6ef931fcaf9fc29266edeea1ab60
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Vehicle/VelocityDamper/hkpVehicleVelocityDamper.h
7d1a21a3878decf6024d9ddb21a8537c9b8e8006
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,923
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HKVEHICLE_EXTERNALCONTROLLERS_HKEXTERNALVEHICLECONTROLLER_XML_H #define HKVEHICLE_EXTERNALCONTROLLERS_HKEXTERNALVEHICLECONTROLLER_XML_H #include <Common/Base/hkBase.h> class hkpVehicleInstance; /// Velocity dampers are used to reduce a vehicle's velocities in order /// to make it more stable in certain situations. class hkpVehicleVelocityDamper : public hkReferencedObject { public: HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_VEHICLE); HK_DECLARE_REFLECTION(); // // Methods // /// Applies the controller (like an action). virtual void applyVelocityDamping(const hkReal deltaTime, hkpVehicleInstance& vehicle) = 0; }; #endif // HKVEHICLE_EXTERNALCONTROLLERS_HKEXTERNALVEHICLECONTROLLER_XML_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 48 ] ] ]
2e3fa5cff60dca0a38198b75d21d3ed985101772
6477cf9ac119fe17d2c410ff3d8da60656179e3b
/Projects/openredalert/src/game/SnowMissionTheater.h
e50fc0c1bec59073be0abbbcabc4a1f6c6535ba7
[]
no_license
crutchwalkfactory/motocakerteam
1cce9f850d2c84faebfc87d0adbfdd23472d9f08
0747624a575fb41db53506379692973e5998f8fe
refs/heads/master
2021-01-10T12:41:59.321840
2010-12-13T18:19:27
2010-12-13T18:19:27
46,494,539
0
0
null
null
null
null
UTF-8
C++
false
false
935
h
// SnowMissionTheater.h // 1.0 // This file is part of OpenRedAlert. // // OpenRedAlert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 2 of the License. // // OpenRedAlert 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 OpenRedAlert. If not, see <http://www.gnu.org/licenses/>. #ifndef SNOWMISSIONTHEATER_H #define SNOWMISSIONTHEATER_H #include "MissionTheater.h" class SnowMissionTheater : public MissionTheater { public: SnowMissionTheater(); }; #endif //SNOWMISSIONTHEATER_H
[ [ [ 1, 28 ] ] ]
d9d350ce0a2793207f3d32962e9b97eb666a8c68
d34246d8eb3d75e4ab8a500711eafda0af18dcd2
/project/sensorInterface/DenseStereo/StereoVision.h
51cedef3dc6ad207936d5b0b99964eb1442e7009
[]
no_license
edrisfattahi/MasterThesis
51899d783048726d357539369f5588d28a740241
8cd06c0b494092aa43eb080feac385191d710a31
refs/heads/master
2021-01-18T01:19:59.174873
2010-06-13T20:42:16
2010-06-13T20:42:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,997
h
/* * StereoVision.h * * Created on: 17. apr. 2010 * Author: anderga */ #ifndef STEREOVISION_H_ #define STEREOVISION_H_ #include <opencv/cv.h> #include <opencv/cxmisc.h> #include <opencv/cvaux.h> #include <opencv/highgui.h> using namespace std; #include <vector> enum{ STEREO_CALIBRATE_BOTH_CAMERAS = 0, STEREO_CALIBRATE_INDIVIDUAL_CAMERAS = 1, STEREO_MATCH_BY_BM = 2, STEREO_MATCH_BY_GC = 3 }; class StereoVision { private: //chesboard board corners X,Y, N = X*Y , number of corners = (number of cells - 1) int cornersX,cornersY,cornersN; int sampleCount; bool calibrationStarted; bool calibrationDone; CvSize imageSize; vector<CvPoint2D32f> ponintsTemp[2]; vector<CvPoint3D32f> objectPoints; vector<CvPoint2D32f> points[2]; vector<int> npoints; public: StereoVision(int imageWidth,int imageHeight); StereoVision(CvSize size); ~StereoVision(); //matrices resulting from calibration (used for cvRemap to rectify images) CvMat *mx1,*my1,*mx2,*my2; CvMat * Q; //perspective transformation matrix created by stereoRectify CvMat* imagesRectified[2]; CvMat *imageDepth,*imageDepthNormalized; CvMat * disp_gc[2]; void calibrationStart(int cornersX,int cornersY); int calibrationAddSample(IplImage* imageLeft,IplImage* imageRight); int calibrationEnd(int flag, CvMat* dist1, CvMat* cam1, CvMat* dist2, CvMat* cam2,CvMat* fundamentalMat ); int calibrationSave(const char* filename); int calibrationLoad(const char* filename); int stereoProcess(CvArr* imageSrcLeft,CvArr* imageSrcRight, int match); CvSize getImageSize(){return imageSize;} bool getCalibrationStarted(){return calibrationStarted;} bool getCalibrationDone(){return calibrationDone;} int getSampleCount(){return sampleCount;} void reCalibrate(int cornersX, int cornersY); }; #endif /* STEREOVISION_H_ */
[ [ [ 1, 79 ] ] ]
fde66b5f66e41d4c0dc90a1a7bd686d0b167edca
555ce7f1e44349316e240485dca6f7cd4496ea9c
/DirectShowFilters/TsReader/source/VideoPin.h
9844eb56fed9e95f6b0c2023f26c0691d95aa76f
[]
no_license
Yura80/MediaPortal-1
c71ce5abf68c70852d261bed300302718ae2e0f3
5aae402f5aa19c9c3091c6d4442b457916a89053
refs/heads/master
2021-04-15T09:01:37.267793
2011-11-25T20:02:53
2011-11-25T20:11:02
2,851,405
2
0
null
null
null
null
UTF-8
C++
false
false
2,749
h
/* * Copyright (C) 2005 Team MediaPortal * http://www.team-mediaportal.com * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #ifndef __VideoPin_H #define __VideoPin_H #include "tsreader.h" #define NB_MTDSIZE 32 class CVideoPin : public CSourceStream, public CSourceSeeking { public: CVideoPin(LPUNKNOWN pUnk, CTsReaderFilter *pFilter, HRESULT *phr,CCritSec* section); ~CVideoPin(); STDMETHODIMP NonDelegatingQueryInterface( REFIID riid, void ** ppv ); //CSourceStream HRESULT GetMediaType(CMediaType *pMediaType); HRESULT DecideBufferSize(IMemAllocator *pAlloc, ALLOCATOR_PROPERTIES *pRequest); HRESULT CompleteConnect(IPin *pReceivePin); HRESULT CheckConnect(IPin *pReceivePin); HRESULT FillBuffer(IMediaSample *pSample); HRESULT BreakConnect(); HRESULT DoBufferProcessingLoop(void); // CSourceSeeking HRESULT ChangeStart(); HRESULT ChangeStop(); HRESULT ChangeRate(); STDMETHODIMP SetPositions(LONGLONG *pCurrent, DWORD CurrentFlags, LONGLONG *pStop, DWORD StopFlags); STDMETHODIMP GetAvailable( LONGLONG * pEarliest, LONGLONG * pLatest ); STDMETHODIMP GetDuration(LONGLONG *pDuration); STDMETHODIMP GetCurrentPosition(LONGLONG *pCurrent); STDMETHODIMP Notify(IBaseFilter * pSender, Quality q); HRESULT OnThreadStartPlay(); void SetStart(CRefTime rtStartTime); bool IsConnected(); void SetDiscontinuity(bool onOff); protected: void UpdateFromSeek(); CTsReaderFilter * const m_pTsReaderFilter; bool m_bConnected; BOOL m_bDiscontinuity; CCritSec* m_section; bool m_bPresentSample; FILTER_INFO m_filterInfo; int m_delayedDiscont; bool TimestampDisconChecker(REFERENCE_TIME timeStamp); REFERENCE_TIME m_pllMTD [NB_MTDSIZE]; // timestamp buffer for average Video sample timestamp calculation REFERENCE_TIME m_llLastMTDts; int m_nNextMTD; REFERENCE_TIME m_fMTDMean; REFERENCE_TIME m_llMTDSumAvg; }; #endif
[ [ [ 1, 1 ], [ 4, 25 ], [ 28, 30 ], [ 33, 33 ], [ 35, 35 ], [ 40, 40 ], [ 42, 43 ], [ 51, 51 ], [ 53, 56 ], [ 59, 62 ], [ 83, 85 ] ], [ [ 2, 3 ], [ 31, 32 ], [ 34, 34 ], [ 36, 39 ], [ 41, 41 ], [ 47, 50 ], [ 52, 52 ], [ 57, 58 ], [ 63, 63 ], [ 65, 65 ], [ 67, 69 ] ], [ [ 26, 27 ], [ 44, 44 ], [ 72, 82 ] ], [ [ 45, 46 ], [ 64, 64 ], [ 66, 66 ], [ 70, 71 ] ] ]
546ca6043401a12bbfea68817a2a8e9f238bcd42
011359e589f99ae5fe8271962d447165e9ff7768
/src/burner/win32/favorites.cpp
01d2db1ea343191035b353361f3eb8887fc7b0ec
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
2,619
cpp
// favorites module, added by regret /* changelog: update 1: create */ #include "burner.h" map<string, int> favoriteMap; static bool favLoaded = false; static bool favChanged = false; int initFavorites() { if (favLoaded) { return 0; } favoriteMap.clear(); //parse ips dat and update the treewidget FILE* fp = fopen("config\\favorites.ini", "rt"); if (!fp) { return 1; } int i = 0; size_t nLen = 0; char s[MAX_PATH]; string line; while (!feof(fp)) { if (fgets(s, sizeof s, fp) != NULL) { if (s[0] == ';' || (s[0] == '/' && s[1] == '/')) continue; // skip comment getLine(s); line = s; if (line == "[Favorites]" || line == "\r\n" || line == "\n") continue; favoriteMap[line] = i; i++; } } fclose(fp); favLoaded = true; return 0; } int saveFavorites() { if (!favChanged) { return 0; } FILE* fp = NULL; fp = fopen("config\\favorites.ini", "wt"); if (!fp) { return 1; } fprintf(fp, "// " APP_TITLE " v%s favorite file\n\n", WtoA(szAppBurnVer)); fprintf(fp, "[Favorites]\n"); string game; map<string, int>::iterator iter = favoriteMap.begin(); for(; iter != favoriteMap.end(); iter++) { game = iter->first; if (game != "\r" && game != "\n" && game != "") { fprintf(fp, "%s\n", game.c_str()); } } fclose(fp); favChanged = false; return 0; } void addFavorite(unsigned int index) { if (index >= nBurnDrvCount) return; unsigned int nOldBurnDrvSelect = nBurnDrvSelect; nBurnDrvSelect = index; string game = BurnDrvGetTextA(DRV_NAME); map<string, int>::iterator iter = favoriteMap.find(game); if (iter == favoriteMap.end()) { favoriteMap[game] = index; } nBurnDrvSelect = nOldBurnDrvSelect; favChanged = true; } void removeFavorite(unsigned int index) { if (index >= nBurnDrvCount) return; unsigned int nOldBurnDrvSelect = nBurnDrvSelect; nBurnDrvSelect = index; string game = BurnDrvGetTextA(DRV_NAME); map<string, int>::iterator iter = favoriteMap.find(game); if (iter != favoriteMap.end()) { favoriteMap.erase(iter); } nBurnDrvSelect = nOldBurnDrvSelect; favChanged = true; } bool filterFavorite(const unsigned int& index) { unsigned int nOldBurnDrvSelect = nBurnDrvSelect; nBurnDrvSelect = index; string game = BurnDrvGetTextA(DRV_NAME); bool ret; map<string, int>::iterator iter = favoriteMap.find(game); if (iter != favoriteMap.end()) { ret = false; } else { ret = true; } nBurnDrvSelect = nOldBurnDrvSelect; return ret; }
[ [ [ 1, 144 ] ] ]
ad005ce7631737774830b01e13cf4d71fd934367
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/Code/Flosti Engine/PhysX/PhysicCookingMesh.cpp
a00bec26563b8c09282e752f4a5a05b628854110
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
5,837
cpp
#include "__PCH_PhysX.h" #include "PhysicCookingMesh.h" //---PhysX includes---- #undef min #undef max #include "NxPhysics.h" #include "NxCooking.h" #include "PhysicUserAllocator.h" #include "PhysXLoader.h" #include "PhysicStream.h" //-------------------------- //---------------------------------------------------------------------------- // Init data //---------------------------------------------------------------------------- bool CPhysicCookingMesh::Init (NxPhysicsSDK* physicSDK, CPhysicUserAllocator* myAllocator) { m_pPhysicSDK = physicSDK; m_pMyAllocator = new CPhysicUserAllocator(); assert(m_pPhysicSDK && m_pMyAllocator); m_bIsOk = (m_pMyAllocator != NULL && m_pPhysicSDK != NULL); if (m_bIsOk) { m_pCooking = NxGetCookingLib(NX_PHYSICS_SDK_VERSION); m_bIsOk = (m_pCooking != NULL); if (m_bIsOk) { m_bIsOk = m_pCooking->NxInitCooking(m_pMyAllocator, NULL); } } if (!m_bIsOk) { Release(); } return m_bIsOk; } //---------------------------------------------------------------------------- // Finalize data //---------------------------------------------------------------------------- void CPhysicCookingMesh::Done () { if (IsOk()) { Release(); m_bIsOk = false; } } //---------------------------------------------------------------------------- // Free memory //---------------------------------------------------------------------------- void CPhysicCookingMesh::Release () { //---Delete TriangleMeshes----------- VecMeshes::iterator it(m_TriangleMeshes.begin()); VecMeshes::iterator endIt(m_TriangleMeshes.end()); while (it!=endIt) { NxTriangleMesh* mesh = it->second; if( mesh != NULL && mesh->getReferenceCount() == 0 ) { m_pPhysicSDK->releaseTriangleMesh(*mesh); } ++it; } m_TriangleMeshes.clear(); //------------------------------------ //Close Cooking if (m_pCooking != NULL) { m_pCooking->NxCloseCooking(); } CHECKED_DELETE(m_pMyAllocator); } NxTriangleMesh* CPhysicCookingMesh::GetPhysicMesh(const std::string& name) { VecMeshes::iterator it = m_TriangleMeshes.find(name); if(it != m_TriangleMeshes.end() ) { return it->second; } return NULL; } //---------------------------------------------------------------------------- // PhysicMesh created from a Bin file. This file has been saved previously //---------------------------------------------------------------------------- bool CPhysicCookingMesh::CreatePhysicMesh ( const std::string& bin_Filename, const std::string& nameMesh ) { bool isOk = false; VecMeshes::iterator it = m_TriangleMeshes.find(nameMesh); if( it == m_TriangleMeshes.end() ) { NxTriangleMesh* triangleMesh = NULL; triangleMesh = m_pPhysicSDK->createTriangleMesh(CPhysicUserStream(bin_Filename.c_str(), true)); isOk = (triangleMesh!=NULL); if( isOk ) { m_TriangleMeshes.insert( std::pair<std::string, NxTriangleMesh*>(nameMesh, triangleMesh)); } } return isOk; } //---------------------------------------------------------------------------- // Creating a PhysicMesh from a buffer //---------------------------------------------------------------------------- bool CPhysicCookingMesh::CreatePhysicMesh ( const std::vector<Vect3f>& vertices, const std::vector<uint32>& faces, const std::string &nameMesh ) { bool isOk = false; std::map<std::string,NxTriangleMesh*>::iterator it = m_TriangleMeshes.find(nameMesh); if( it == m_TriangleMeshes.end() ) { // Build physical model NxTriangleMeshDesc triangleMeshDesc; triangleMeshDesc.numVertices = (NxU32) vertices.size(); triangleMeshDesc.numTriangles = (NxU32) faces.size()/3; triangleMeshDesc.pointStrideBytes = sizeof(Vect3f); triangleMeshDesc.triangleStrideBytes = 3*sizeof(uint32); triangleMeshDesc.points = &vertices[0].x; triangleMeshDesc.triangles = &faces[0]; triangleMeshDesc.flags = 0; assert(m_pCooking); //by if the flies... CPhysicMemoryWriteBuffer buf; if (m_pCooking->NxCookTriangleMesh(triangleMeshDesc,buf)) { NxTriangleMesh* triangleMesh = NULL; triangleMesh = m_pPhysicSDK->createTriangleMesh(CPhysicMemoryReadBuffer(buf.data)); isOk = (triangleMesh != NULL); if (isOk) { m_TriangleMeshes.insert( std::pair<std::string, NxTriangleMesh*>(nameMesh, triangleMesh)); } } } return isOk; } //---------------------------------------------------------------------------- // Save a PhysicMesh in a bin file //---------------------------------------------------------------------------- bool CPhysicCookingMesh::SavePhysicMesh ( const std::vector<Vect3f>& vertices, const std::vector<uint32>& faces, const std::string &binFilename ) { // Build physical model NxTriangleMeshDesc triangleMeshDesc; triangleMeshDesc.numVertices = (NxU32)vertices.size(); triangleMeshDesc.numTriangles = (NxU32)faces.size()/3; triangleMeshDesc.pointStrideBytes = sizeof(Vect3f); triangleMeshDesc.triangleStrideBytes = 3*sizeof(uint32); triangleMeshDesc.points = &vertices[0].x; triangleMeshDesc.triangles = &faces[0]; triangleMeshDesc.flags = 0; assert(m_pCooking); bool isOk = false; isOk = m_pCooking->NxCookTriangleMesh(triangleMeshDesc, CPhysicUserStream(binFilename.c_str(), false)); return isOk; } //---------------------------------------------------------------------------- // Create a Cloth mesh //---------------------------------------------------------------------------- bool CPhysicCookingMesh::CookClothMesh(const NxClothMeshDesc& desc, NxStream& stream) { assert(m_pCooking); bool isOk = false; isOk = m_pCooking->NxCookClothMesh(desc,stream); return isOk; }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 189 ] ] ]
03bbb99961af358a468ec879acdbfdd312af6218
cb621dee2a0f09a9a2d5d14ffaac7df0cad666a0
/http/parsers/message_state.hpp
72874a5fc016ae854cf92bc69384b605a9f74e92
[ "BSL-1.0" ]
permissive
ssiloti/http
a15fb43c94c823779f11fb02e147f023ca77c932
9cdeaa5cf2ef2848238c6e4c499ebf80e136ba7e
refs/heads/master
2021-01-01T19:10:36.886248
2011-11-07T19:29:22
2011-11-07T19:29:22
1,021,325
0
1
null
null
null
null
UTF-8
C++
false
false
5,345
hpp
// // message_state.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2010 Steven Siloti ([email protected]) // // 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) // #ifndef HTTP_PARSERS_MESSAGE_STATE_HPP #define HTTP_PARSERS_MESSAGE_STATE_HPP #include <http/headers.hpp> #include <http/parsers/body.hpp> #include <boost/asio/buffer.hpp> #include <boost/range.hpp> #include <boost/logic/tribool.hpp> #include <boost/optional.hpp> #include <iostream> #include <vector> #include <utility> namespace http { namespace parsers { template <typename Msg, typename InputIterator> class message_state { enum state { state_init, state_start_line, state_start_line_cr, state_header_start, state_header_name, state_header_value, state_header_cr, state_header_lf, state_header_final_cr, state_header_final_lf, state_body, }; public: typedef Msg message_type; typedef InputIterator iterator; message_state(message_type& m) : msg_(m), state_(state_init), content_length_remaining_(message_type::default_content_length) {} void reset() { state_ = state_init; } bool is_started() { return state_ != state_init; } boost::tribool parse_headers(iterator& begin, iterator end) { if (state_ == state_init) { cur_ = begin; state_ = state_start_line; } for (;cur_ != end; ++cur_) { switch (state_) { case state_start_line: if (*cur_ == '\r') state_ = state_start_line_cr; break; case state_start_line_cr: if (*cur_ == '\n') { iterator parse_end = cur_; msg_.parse_start_line(begin, --parse_end); begin = cur_; ++begin; state_ = state_header_start; } else { return false; } break; case state_header_start: if (*cur_ == '\r') state_ = state_header_final_cr; else state_ = state_header_name; break; case state_header_name: if (*cur_ == ':') { header_sep_ = cur_; state_ = state_header_value; } break; case state_header_value: if (*cur_ == '\r') state_ = state_header_cr; break; case state_header_cr: if (*cur_ == '\n') state_ = state_header_lf; else return false; break; case state_header_lf: if (*cur_ == ' ' || *cur_ == '\t') state_ = state_header_value; else { iterator parse_end = cur_; --parse_end; --parse_end; msg_.parse_header(begin, header_sep_, parse_end); begin = cur_; if (*cur_ == '\r') state_ = state_header_final_cr; else state_ = state_header_start; } break; case state_header_final_cr: if (*cur_ == '\n') { state_ = state_body; begin = ++cur_; return get_content_length(); } else return false; break; case state_body: return true; default: return false; break; } } return boost::indeterminate; } std::vector<boost::asio::mutable_buffer> parse_body(boost::asio::const_buffer received) { if (content_length_remaining_ != std::numeric_limits<std::size_t>::max()) { content_length_remaining_ -= boost::asio::buffer_size(received); } return body_parser_.parse_body(msg_, received, content_length_remaining_); } std::size_t body_length_remaining() { return content_length_remaining_; } private: bool get_content_length() { boost::optional<const std::size_t&> maybe_length = msg_.headers.template maybe_at<headers::content_length>(); if (maybe_length) { content_length_remaining_ = *maybe_length; return content_length_remaining_ != std::numeric_limits<std::size_t>::max(); } else { return true; } } message_type& msg_; iterator cur_, header_sep_; body_parser<typename message_type::headers_type, typename message_type::body_type> body_parser_; std::size_t content_length_remaining_; state state_; }; } } // namespace parsers namespace http #endif
[ [ [ 1, 186 ] ] ]
de9b64354221fb9310049be52a74f31ff8856be7
2b32433353652d705e5558e7c2d5de8b9fbf8fc3
/Dm_new_idz/Mlita/Exam/ExamDlg.cpp
f2c2b17f9dfe5d52c9be8464a0bb3faadbcee922
[]
no_license
smarthaert/d-edit
70865143db2946dd29a4ff52cb36e85d18965be3
41d069236748c6e77a5a457280846a300d38e080
refs/heads/master
2020-04-23T12:21:51.180517
2011-01-30T00:37:18
2011-01-30T00:37:18
35,532,200
0
0
null
null
null
null
UTF-8
C++
false
false
8,697
cpp
// ExamDlg.cpp : implementation file // #include "stdafx.h" #include "Exam.h" #include "ExamDlg.h" #include "graph.h" #include "MSFlexGrid.h" #include "AlhoritmsDlg.h" #include "SearchDlg.h" #include "PathDlg.h" #include "FloydDlg.h" #include "KraskalDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif CString CaptionText="Exam message"; ///////////////////////////////////////////////////////////////////////////// // 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 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) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CExamDlg dialog CExamDlg::CExamDlg(CWnd* pParent /*=NULL*/) : CDialog(CExamDlg::IDD, pParent) { //{{AFX_DATA_INIT(CExamDlg) m_Positive = FALSE; m_Oriented = FALSE; m_Linked = FALSE; m_Priced = FALSE; m_Cycled = FALSE; m_Edges = 0; m_Tops = 0; //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CExamDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CExamDlg) DDX_Control(pDX, IDC_Alhoritms, m_Alhoritms); DDX_Control(pDX, IDC_EDIT2, m_EdgesCtrl); DDX_Control(pDX, IDC_EDIT, m_EditBtn); DDX_Control(pDX, IDC_GRAPHCTRLCTRL1, m_GraphCtrl); DDX_Check(pDX, IDC_CHECK2, m_Positive); DDX_Check(pDX, IDC_CHECK3, m_Oriented); DDX_Check(pDX, IDC_CHECK4, m_Linked); DDX_Check(pDX, IDC_CHECK6, m_Priced); DDX_Check(pDX, IDC_CHECK7, m_Cycled); DDX_Text(pDX, IDC_EDIT2, m_Edges); DDX_Text(pDX, IDC_EDIT3, m_Tops); DDX_Control(pDX, IDC_MSFLEXGRID1, m_Grid); DDX_Control(pDX, IDC_MSFLEXGRID2, m_PriceGrid); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CExamDlg, CDialog) //{{AFX_MSG_MAP(CExamDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_WM_CLOSE() ON_COMMAND(ID_HELP_ABOUT, OnHelpAbout) ON_BN_CLICKED(IDC_BUTTON2, OnGenerate) ON_BN_CLICKED(IDC_EDIT, OnEdit) ON_BN_CLICKED(IDC_CHECK4, OnLinked) ON_BN_CLICKED(IDC_CHECK7, OnCycled) ON_BN_CLICKED(IDC_Alhoritms, OnAlhoritms) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CExamDlg message handlers BOOL CExamDlg::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); } } SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon m_Current = NULL; RefreshControls(); return TRUE; // return TRUE unless you set the focus to a control } void CExamDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } 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 CExamDlg::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 { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CExamDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CExamDlg::OnClose() { delete m_Current; CDialog::OnClose(); } void CExamDlg::OnHelpAbout() { CAboutDlg Dlg; Dlg.DoModal(); } void CExamDlg::ShowGraph() { if (m_Current && !m_Current->m_error) { m_GraphCtrl.SetTops(m_Current->GetTops()); for (int i=1; i<=m_Current->GetTops(); i++) { char Text[10]; sprintf(Text,"%d",i); m_Grid.SetTextMatrix(0,i,Text); m_Grid.SetTextMatrix(i,0,Text); m_PriceGrid.SetTextMatrix(0,i,Text); m_PriceGrid.SetTextMatrix(i,0,Text); for (int j=1; j<=m_Current->GetTops(); j++) { if (m_Current->IsLinked(i,j)) m_Grid.SetTextMatrix(i,j,"1"); else m_Grid.SetTextMatrix(i,j,"0"); if (m_Current->IsLinked(i,j)) m_GraphCtrl.SetEdge(i,j); if (m_Current->GetPrice(i,j)==LARGECOST) sprintf(Text,"---"); else sprintf(Text,"%d",m_Current->GetPrice(i,j)); m_PriceGrid.SetTextMatrix(i,j,Text); } } } else { // m_Info = "ads"; } } int FormStyle(BOOL a, BOOL b, BOOL c, BOOL d, BOOL e) { int Style = 0; if (a) Style = Style | Gr_Positive; if (b) Style = Style | Gr_Oriented; if (c) Style = Style | Gr_Linked; if (d) Style = Style | Gr_Price; if (e) Style = Style | Gr_Cycled; return Style; } void CExamDlg::OnGenerate() { UpdateData(); m_GraphCtrl.SetTops(0); delete m_Current; m_Current=NULL; m_EditBtn.EnableWindow(FALSE); if (m_Edges > (m_Tops*m_Tops-m_Tops)/2) { MessageBox("Error Edges count bigger that max count",CaptionText,MB_OK); return; } if (m_Linked && m_Edges < m_Tops-1) { MessageBox("Error this graph cant be linked!",CaptionText,MB_OK); return; } if (!m_Cycled && m_Edges > m_Tops-1) { MessageBox("Error this graph must be cycled!",CaptionText,MB_OK); return; } m_Grid.SetCols(m_Tops+1); m_Grid.SetRows(m_Tops+1); for (unsigned int i=0; i<=m_Tops; i++) m_Grid.SetColWidth(i,300); int Style=0; Style=FormStyle(m_Positive,m_Oriented,m_Linked,m_Priced,m_Cycled); m_PriceGrid.SetCols(m_Tops+1); m_PriceGrid.SetRows(m_Tops+1); for (i=0; i<=m_Tops; i++) m_PriceGrid.SetColWidth(i,320); m_Current = new CGraph(m_Tops,m_Edges,Style); ShowGraph(); RefreshControls(); } void CExamDlg::OnEdit() { } void CExamDlg::OnLinked() { RefreshControls(); } void CExamDlg::OnCycled() { RefreshControls(); } void CExamDlg::RefreshControls() { UpdateData(); if (!m_Current) m_Alhoritms.EnableWindow(FALSE); else m_Alhoritms.EnableWindow(TRUE); if (m_Linked && !m_Cycled) { m_Edges=m_Tops-1; m_EdgesCtrl.EnableWindow(FALSE); } else m_EdgesCtrl.EnableWindow(TRUE); UpdateData(0); } void CExamDlg::OnAlhoritms() { if (m_Current->m_error) { MessageBox("Generate correct graph first",CaptionText,MB_OK); return; } int AlhoritmID=-1; CAlhoritmsDlg Dlg; if (Dlg.DoModal()==IDOK) { switch (Dlg.AlhoritmID) { case 0: { Search(0); break; } case 1: { Search(1); break; } case 2: { Path(); break; } case 3: { Floyd(); break; } case 4: { Kraskal(); break; } }; } } void CExamDlg::Search(int ID) { CSearchDlg Dlg; if (ID==0) { Dlg.m_StatusCaption = "Stack Status"; Dlg.m_Caption = "Search into Deep"; } else { Dlg.m_StatusCaption = "Query Status"; Dlg.m_Caption="Search into Width"; } Dlg.Graph = m_Current; Dlg.ID=ID; Dlg.DoModal(); } void CExamDlg::Path() { CPathDlg Dlg; Dlg.Graph=m_Current; Dlg.DoModal(); } void CExamDlg::Floyd() { CFloydDlg Dlg; Dlg.Graph=m_Current; Dlg.DoModal(); } void CExamDlg::Kraskal() { CKraskalDlg Dlg; Dlg.Graph = m_Current; Dlg.DoModal(); }
[ [ [ 1, 395 ] ] ]